r314141 - [analyzer] Fix crash on modeling of pointer arithmetic

2017-09-25 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Sep 25 12:32:33 2017
New Revision: 314141

URL: http://llvm.org/viewvc/llvm-project?rev=314141&view=rev
Log:
[analyzer] Fix crash on modeling of pointer arithmetic

This patch fixes analyzer's crash on the newly added test case 
(see also https://bugs.llvm.org/show_bug.cgi?id=34374).
Pointers subtraction appears to be modeled incorrectly 
in the following example:
  char* p;
  auto n = p - reinterpret_cast((unsigned long)1);
In this case the analyzer (built without this patch) 
tries to create a symbolic value for the difference 
treating reinterpret_cast((unsigned long)1) 
as an integer, that is not correct.

Differential revision: https://reviews.llvm.org/D38214

Test plan: make check-all

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
cfe/trunk/test/Analysis/ptr-arith.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp?rev=314141&r1=314140&r2=314141&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp Mon Sep 25 12:32:33 
2017
@@ -726,9 +726,11 @@ SVal SimpleSValBuilder::evalBinOpLL(Prog
 if (Optional rInt = rhs.getAs()) {
   // If one of the operands is a symbol and the other is a constant,
   // build an expression for use by the constraint manager.
-  if (SymbolRef lSym = lhs.getAsLocSymbol(true))
-return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
-
+  if (SymbolRef lSym = lhs.getAsLocSymbol(true)) {
+if (BinaryOperator::isComparisonOp(op))
+  return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
+return UnknownVal();
+  }
   // Special case comparisons to NULL.
   // This must come after the test if the LHS is a symbol, which is used to
   // build constraints. The address of any non-symbolic region is 
guaranteed

Modified: cfe/trunk/test/Analysis/ptr-arith.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/ptr-arith.cpp?rev=314141&r1=314140&r2=314141&view=diff
==
--- cfe/trunk/test/Analysis/ptr-arith.cpp (original)
+++ cfe/trunk/test/Analysis/ptr-arith.cpp Mon Sep 25 12:32:33 2017
@@ -111,3 +111,9 @@ bool ptrAsIntegerSubtractionNoCrash(__UI
   __UINTPTR_TYPE__ y = (__UINTPTR_TYPE__)p - 1;
   return y == x;
 }
+
+// Bug 34374
+bool integerAsPtrSubtractionNoCrash(char *p, __UINTPTR_TYPE__ m) {
+  auto n = p - reinterpret_cast((__UINTPTR_TYPE__)1);
+  return n == m;
+}


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


r314470 - [clang] Add getUnsignedPointerDiffType method

2017-09-28 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Thu Sep 28 16:11:31 2017
New Revision: 314470

URL: http://llvm.org/viewvc/llvm-project?rev=314470&view=rev
Log:
[clang] Add getUnsignedPointerDiffType method

C11 standard refers to the unsigned counterpart of the type ptrdiff_t 
in the paragraph 7.21.6.1p7 where it defines the format specifier %tu.
In Clang (in PrintfFormatString.cpp, lines 508-510) there is a FIXME for this 
case,
in particular, Clang didn't diagnose %tu issues at all, i.e.
it didn't emit any warnings on the code printf("%tu", 3.14).
In this diff we add a method getUnsignedPointerDiffType for getting the 
corresponding type
similarly to how it's already done in the other analogous cases (size_t, 
ssize_t, ptrdiff_t etc)
and fix -Wformat diagnostics for %tu plus the emitted fix-it as well.

Test plan: make check-all

Differential revision: https://reviews.llvm.org/D38270

Modified:
cfe/trunk/include/clang/AST/ASTContext.h
cfe/trunk/include/clang/Basic/TargetInfo.h
cfe/trunk/lib/AST/ASTContext.cpp
cfe/trunk/lib/Analysis/PrintfFormatString.cpp
cfe/trunk/lib/Analysis/ScanfFormatString.cpp
cfe/trunk/test/FixIt/format.m
cfe/trunk/test/Sema/format-strings-scanf.c

Modified: cfe/trunk/include/clang/AST/ASTContext.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ASTContext.h?rev=314470&r1=314469&r2=314470&view=diff
==
--- cfe/trunk/include/clang/AST/ASTContext.h (original)
+++ cfe/trunk/include/clang/AST/ASTContext.h Thu Sep 28 16:11:31 2017
@@ -1489,6 +1489,11 @@ public:
   /// . Pointer - pointer requires this (C99 6.5.6p9).
   QualType getPointerDiffType() const;
 
+  /// \brief Return the unique unsigned counterpart of "ptrdiff_t"
+  /// integer type. The standard (C11 7.21.6.1p7) refers to this type
+  /// in the definition of %tu format specifier.
+  QualType getUnsignedPointerDiffType() const;
+
   /// \brief Return the unique type for "pid_t" defined in
   /// . We need this to compute the correct type for vfork().
   QualType getProcessIDType() const;

Modified: cfe/trunk/include/clang/Basic/TargetInfo.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/TargetInfo.h?rev=314470&r1=314469&r2=314470&view=diff
==
--- cfe/trunk/include/clang/Basic/TargetInfo.h (original)
+++ cfe/trunk/include/clang/Basic/TargetInfo.h Thu Sep 28 16:11:31 2017
@@ -248,6 +248,9 @@ public:
   IntType getPtrDiffType(unsigned AddrSpace) const {
 return AddrSpace == 0 ? PtrDiffType : getPtrDiffTypeV(AddrSpace);
   }
+  IntType getUnsignedPtrDiffType(unsigned AddrSpace) const {
+return getCorrespondingUnsignedType(getPtrDiffType(AddrSpace));
+  }
   IntType getIntPtrType() const { return IntPtrType; }
   IntType getUIntPtrType() const {
 return getCorrespondingUnsignedType(IntPtrType);

Modified: cfe/trunk/lib/AST/ASTContext.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTContext.cpp?rev=314470&r1=314469&r2=314470&view=diff
==
--- cfe/trunk/lib/AST/ASTContext.cpp (original)
+++ cfe/trunk/lib/AST/ASTContext.cpp Thu Sep 28 16:11:31 2017
@@ -4571,6 +4571,13 @@ QualType ASTContext::getPointerDiffType(
   return getFromTargetType(Target->getPtrDiffType(0));
 }
 
+/// \brief Return the unique unsigned counterpart of "ptrdiff_t"
+/// integer type. The standard (C11 7.21.6.1p7) refers to this type
+/// in the definition of %tu format specifier.
+QualType ASTContext::getUnsignedPointerDiffType() const {
+  return getFromTargetType(Target->getUnsignedPtrDiffType(0));
+}
+
 /// \brief Return the unique type for "pid_t" defined in
 /// . We need this to compute the correct type for vfork().
 QualType ASTContext::getProcessIDType() const {

Modified: cfe/trunk/lib/Analysis/PrintfFormatString.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/PrintfFormatString.cpp?rev=314470&r1=314469&r2=314470&view=diff
==
--- cfe/trunk/lib/Analysis/PrintfFormatString.cpp (original)
+++ cfe/trunk/lib/Analysis/PrintfFormatString.cpp Thu Sep 28 16:11:31 2017
@@ -505,9 +505,7 @@ ArgType PrintfSpecifier::getArgType(ASTC
? ArgType(Ctx.UnsignedLongLongTy, "unsigned __int64")
: ArgType(Ctx.UnsignedIntTy, "unsigned __int32");
   case LengthModifier::AsPtrDiff:
-// FIXME: How to get the corresponding unsigned
-// version of ptrdiff_t?
-return ArgType();
+return ArgType(Ctx.getUnsignedPointerDiffType(), "unsigned ptrdiff_t");
   case LengthModifier::AsAllocate:
   case LengthModifier::AsMAllocate:
   case LengthModifier::AsWide:

Modified: cfe/trunk/lib/Analysis/ScanfFormatString.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/ScanfFormatString.cpp?rev=3144

r315665 - [clang] Enable clang build with LLVM_BUILD_INSTRUMENTED without setting LLVM_PROFTDATA

2017-10-12 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Thu Oct 12 20:21:39 2017
New Revision: 315665

URL: http://llvm.org/viewvc/llvm-project?rev=315665&view=rev
Log:
[clang] Enable clang build with LLVM_BUILD_INSTRUMENTED without setting 
LLVM_PROFTDATA

At the moment if LLVM_BUILD_INSTRUMENTED is set to True 
one has to set LLVM_PROFTDATA even if it's not really used 
(because of message(FATAL_ERROR ...)). 
Building the instrumented version of Clang can be useful even if 
one doesn't plan to build the target generate-profdata
(currently that target would only compile 
utils/perf-training/cxx/hello_world.cpp).
For example, one can run the instrumented version of Clang 
via a separate build system against a different codebase, 
collect/analyze the profiles and merge them by llvm-profdata later.

Differential revision: https://reviews.llvm.org/D38859

Modified:
cfe/trunk/utils/perf-training/CMakeLists.txt

Modified: cfe/trunk/utils/perf-training/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/perf-training/CMakeLists.txt?rev=315665&r1=315664&r2=315665&view=diff
==
--- cfe/trunk/utils/perf-training/CMakeLists.txt (original)
+++ cfe/trunk/utils/perf-training/CMakeLists.txt Thu Oct 12 20:21:39 2017
@@ -30,13 +30,13 @@ if(LLVM_BUILD_INSTRUMENTED)
   endif()
 
   if(NOT LLVM_PROFDATA)
-message(FATAL_ERROR "Must set LLVM_PROFDATA to point to llvm-profdata to 
use for merging PGO data")
+message(STATUS "To enable merging PGO data LLVM_PROFDATA has to point to 
llvm-profdata")
+  else()
+add_custom_target(generate-profdata
+  COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/perf-helper.py 
merge ${LLVM_PROFDATA} ${CMAKE_CURRENT_BINARY_DIR}/clang.profdata 
${CMAKE_CURRENT_BINARY_DIR}
+  COMMENT "Merging profdata"
+  DEPENDS generate-profraw)
   endif()
-
-  add_custom_target(generate-profdata
-COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/perf-helper.py 
merge ${LLVM_PROFDATA} ${CMAKE_CURRENT_BINARY_DIR}/clang.profdata 
${CMAKE_CURRENT_BINARY_DIR}
-COMMENT "Merging profdata"
-DEPENDS generate-profraw)
 endif()
 
 find_program(DTRACE dtrace)


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


r316399 - [analyzer] Fix handling of labels in getLValueElement

2017-10-23 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Oct 23 16:46:06 2017
New Revision: 316399

URL: http://llvm.org/viewvc/llvm-project?rev=316399&view=rev
Log:
[analyzer] Fix handling of labels in getLValueElement

In getLValueElement Base may represent the address of a label 
(as in the newly-added test case), in this case it's not a loc::MemRegionVal 
and Base.castAs() triggers an assert, this diff makes 
getLValueElement return UnknownVal instead.

Differential revision: https://reviews.llvm.org/D39174

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp
cfe/trunk/test/Analysis/ptr-arith.c

Modified: cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp?rev=316399&r1=316398&r2=316399&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp Mon Oct 23 16:46:06 2017
@@ -440,7 +440,10 @@ SVal StoreManager::getLValueElement(Qual
   //  value. See also the similar FIXME in getLValueFieldOrIvar().
   if (Base.isUnknownOrUndef() || Base.getAs())
 return Base;
-
+  
+  if (Base.getAs())
+return UnknownVal();
+  
   const SubRegion *BaseRegion =
   Base.castAs().getRegionAs();
 

Modified: cfe/trunk/test/Analysis/ptr-arith.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/ptr-arith.c?rev=316399&r1=316398&r2=316399&view=diff
==
--- cfe/trunk/test/Analysis/ptr-arith.c (original)
+++ cfe/trunk/test/Analysis/ptr-arith.c Mon Oct 23 16:46:06 2017
@@ -342,3 +342,8 @@ void negativeIndex(char *str) {
   clang_analyzer_eval(*ptr3 == 'a'); // expected-warning{{UNKNOWN}}
 }
 
+void test_no_crash_on_pointer_to_label() {
+  char *a = &&label;
+  a[0] = 0;
+label:;
+}


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


r305018 - [clang] Fix format specifiers fixits

2017-06-08 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Thu Jun  8 16:44:45 2017
New Revision: 305018

URL: http://llvm.org/viewvc/llvm-project?rev=305018&view=rev
Log:
[clang] Fix format specifiers fixits

This diff fixes printf "fixits" in the case when there is 
a wrapping macro and the format string needs multiple replacements. 
In the presence of a macro there is an extra logic in EditedSource.cpp
to handle multiple uses of the same macro argument 
(see the old comment inside EditedSource::canInsertInOffset)
which was mistriggerred when the argument was used only once 
but required multiple adjustments), as a result the "fixit" 
was breaking down the format string
by dropping the second format specifier, i.e. 
Log1("test 4: %s %s", getNSInteger(), getNSInteger()) 
was getting replaced with 
Log1("test 4: %ld ", (long)getNSInteger(), (long)getNSInteger()) 
(if one removed the macro and used printf directly it would work fine).
In this diff we track the location where the macro argument is used and 
(as it was before) the modifications originating from all the locations 
except the first one are rejected, but multiple changes are allowed.

Test plan: make check-all

Differential revision: https://reviews.llvm.org/D33976

Added:
cfe/trunk/test/FixIt/fixit-format-darwin.m
Modified:
cfe/trunk/include/clang/Edit/EditedSource.h
cfe/trunk/lib/Edit/EditedSource.cpp

Modified: cfe/trunk/include/clang/Edit/EditedSource.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Edit/EditedSource.h?rev=305018&r1=305017&r2=305018&view=diff
==
--- cfe/trunk/include/clang/Edit/EditedSource.h (original)
+++ cfe/trunk/include/clang/Edit/EditedSource.h Thu Jun  8 16:44:45 2017
@@ -41,9 +41,11 @@ class EditedSource {
   typedef std::map FileEditsTy;
   FileEditsTy FileEdits;
 
-  llvm::DenseMap>
+  // Location of argument use inside the macro body 
+  typedef std::pair MacroArgUse;
+  llvm::DenseMap>
 ExpansionToArgMap;
-  SmallVector, 2>
+  SmallVector, 2>
 CurrCommitMacroArgExps;
 
   IdentifierTable IdentTable;
@@ -84,7 +86,7 @@ private:
   FileEditsTy::iterator getActionForOffset(FileOffset Offs);
   void deconstructMacroArgLoc(SourceLocation Loc,
   SourceLocation &ExpansionLoc,
-  IdentifierInfo *&II);
+  MacroArgUse &ArgUse);
 
   void startingCommit();
   void finishedCommit();

Modified: cfe/trunk/lib/Edit/EditedSource.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Edit/EditedSource.cpp?rev=305018&r1=305017&r2=305018&view=diff
==
--- cfe/trunk/lib/Edit/EditedSource.cpp (original)
+++ cfe/trunk/lib/Edit/EditedSource.cpp Thu Jun  8 16:44:45 2017
@@ -25,17 +25,16 @@ void EditsReceiver::remove(CharSourceRan
 
 void EditedSource::deconstructMacroArgLoc(SourceLocation Loc,
   SourceLocation &ExpansionLoc,
-  IdentifierInfo *&II) {
+  MacroArgUse &ArgUse) {
   assert(SourceMgr.isMacroArgExpansion(Loc));
   SourceLocation DefArgLoc = SourceMgr.getImmediateExpansionRange(Loc).first;
   ExpansionLoc = SourceMgr.getImmediateExpansionRange(DefArgLoc).first;
   SmallString<20> Buf;
   StringRef ArgName = Lexer::getSpelling(SourceMgr.getSpellingLoc(DefArgLoc),
  Buf, SourceMgr, LangOpts);
-  II = nullptr;
-  if (!ArgName.empty()) {
-II = &IdentTable.get(ArgName);
-  }
+  ArgUse = {nullptr, SourceLocation()};
+  if (!ArgName.empty())
+ArgUse = {&IdentTable.get(ArgName), SourceMgr.getSpellingLoc(DefArgLoc)};
 }
 
 void EditedSource::startingCommit() {}
@@ -43,12 +42,11 @@ void EditedSource::startingCommit() {}
 void EditedSource::finishedCommit() {
   for (auto &ExpArg : CurrCommitMacroArgExps) {
 SourceLocation ExpLoc;
-IdentifierInfo *II;
-std::tie(ExpLoc, II) = ExpArg;
-auto &ArgNames = ExpansionToArgMap[ExpLoc.getRawEncoding()];
-if (std::find(ArgNames.begin(), ArgNames.end(), II) == ArgNames.end()) {
-  ArgNames.push_back(II);
-}
+MacroArgUse ArgUse;
+std::tie(ExpLoc, ArgUse) = ExpArg;
+auto &ArgUses = ExpansionToArgMap[ExpLoc.getRawEncoding()];
+if (std::find(ArgUses.begin(), ArgUses.end(), ArgUse) == ArgUses.end())
+  ArgUses.push_back(ArgUse);
   }
   CurrCommitMacroArgExps.clear();
 }
@@ -66,12 +64,15 @@ bool EditedSource::canInsertInOffset(Sou
   }
 
   if (SourceMgr.isMacroArgExpansion(OrigLoc)) {
-IdentifierInfo *II;
 SourceLocation ExpLoc;
-deconstructMacroArgLoc(OrigLoc, ExpLoc, II);
+MacroArgUse ArgUse;
+deconstructMacroArgLoc(OrigLoc, ExpLoc, ArgUse);
 auto I = ExpansionToArgMap.find(ExpLoc.getRawEncoding());
 if (I != ExpansionToArgMap.end() &&
-std::find(I->second.begin(), I->second.end(), II) != I->second.end()) {
+  

r305124 - [clang] Cleanup fixit.c

2017-06-09 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Fri Jun  9 17:20:52 2017
New Revision: 305124

URL: http://llvm.org/viewvc/llvm-project?rev=305124&view=rev
Log:
[clang] Cleanup fixit.c

This diff removes temporary file t2 in fixit.c and updates the test command 
accordingly.
NFC.

Test plan:
make check-all

Differential revision: https://reviews.llvm.org/D34066

Modified:
cfe/trunk/test/FixIt/fixit.c

Modified: cfe/trunk/test/FixIt/fixit.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/FixIt/fixit.c?rev=305124&r1=305123&r2=305124&view=diff
==
--- cfe/trunk/test/FixIt/fixit.c (original)
+++ cfe/trunk/test/FixIt/fixit.c Fri Jun  9 17:20:52 2017
@@ -1,9 +1,8 @@
 // RUN: %clang_cc1 -pedantic -Wunused-label -verify -x c %s
 // RUN: cp %s %t
 // RUN: not %clang_cc1 -pedantic -Wunused-label -fixit -x c %t
-// RUN: grep -v CHECK %t > %t2
 // RUN: %clang_cc1 -pedantic -Wunused-label -Werror -x c %t
-// RUN: FileCheck -input-file=%t2 %t
+// RUN: grep -v CHECK %t | FileCheck %t
 
 /* This is a test of the various code modification hints that are
provided as part of warning or extension diagnostics. All of the


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


r305845 - [clang] Fix format specifiers fixits for nested macros

2017-06-20 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Tue Jun 20 15:46:58 2017
New Revision: 305845

URL: http://llvm.org/viewvc/llvm-project?rev=305845&view=rev
Log:
[clang] Fix format specifiers fixits for nested macros

ExpansionLoc was previously calculated incorrectly in the case of 
nested macros expansions. In this diff we build the stack of expansions 
where the last one is the actual expansion which should be used 
for grouping together the edits. 
The definition of MacroArgUse is adjusted accordingly.

Test plan: make check-all

Differential revision: https://reviews.llvm.org/D34268

Modified:
cfe/trunk/include/clang/Edit/EditedSource.h
cfe/trunk/lib/Edit/EditedSource.cpp
cfe/trunk/test/FixIt/fixit-format-darwin.m

Modified: cfe/trunk/include/clang/Edit/EditedSource.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Edit/EditedSource.h?rev=305845&r1=305844&r2=305845&view=diff
==
--- cfe/trunk/include/clang/Edit/EditedSource.h (original)
+++ cfe/trunk/include/clang/Edit/EditedSource.h Tue Jun 20 15:46:58 2017
@@ -17,6 +17,7 @@
 #include "llvm/ADT/TinyPtrVector.h"
 #include "llvm/Support/Allocator.h"
 #include 
+#include 
 
 namespace clang {
   class LangOptions;
@@ -41,10 +42,20 @@ class EditedSource {
   typedef std::map FileEditsTy;
   FileEditsTy FileEdits;
 
-  // Location of argument use inside the macro body 
-  typedef std::pair MacroArgUse;
-  llvm::DenseMap>
-ExpansionToArgMap;
+  struct MacroArgUse {
+IdentifierInfo *Identifier;
+SourceLocation ImmediateExpansionLoc;
+// Location of argument use inside the top-level macro
+SourceLocation UseLoc;
+
+bool operator==(const MacroArgUse &Other) const {
+  return std::tie(Identifier, ImmediateExpansionLoc, UseLoc) ==
+ std::tie(Other.Identifier, Other.ImmediateExpansionLoc,
+  Other.UseLoc);
+}
+  };
+
+  llvm::DenseMap> ExpansionToArgMap;
   SmallVector, 2>
 CurrCommitMacroArgExps;
 

Modified: cfe/trunk/lib/Edit/EditedSource.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Edit/EditedSource.cpp?rev=305845&r1=305844&r2=305845&view=diff
==
--- cfe/trunk/lib/Edit/EditedSource.cpp (original)
+++ cfe/trunk/lib/Edit/EditedSource.cpp Tue Jun 20 15:46:58 2017
@@ -28,13 +28,18 @@ void EditedSource::deconstructMacroArgLo
   MacroArgUse &ArgUse) {
   assert(SourceMgr.isMacroArgExpansion(Loc));
   SourceLocation DefArgLoc = SourceMgr.getImmediateExpansionRange(Loc).first;
-  ExpansionLoc = SourceMgr.getImmediateExpansionRange(DefArgLoc).first;
+  SourceLocation ImmediateExpansionLoc =
+  SourceMgr.getImmediateExpansionRange(DefArgLoc).first;
+  ExpansionLoc = ImmediateExpansionLoc;
+  while (SourceMgr.isMacroBodyExpansion(ExpansionLoc))
+ExpansionLoc = SourceMgr.getImmediateExpansionRange(ExpansionLoc).first;
   SmallString<20> Buf;
   StringRef ArgName = Lexer::getSpelling(SourceMgr.getSpellingLoc(DefArgLoc),
  Buf, SourceMgr, LangOpts);
-  ArgUse = {nullptr, SourceLocation()};
+  ArgUse = MacroArgUse{nullptr, SourceLocation(), SourceLocation()};
   if (!ArgName.empty())
-ArgUse = {&IdentTable.get(ArgName), SourceMgr.getSpellingLoc(DefArgLoc)};
+ArgUse = {&IdentTable.get(ArgName), ImmediateExpansionLoc,
+  SourceMgr.getSpellingLoc(DefArgLoc)};
 }
 
 void EditedSource::startingCommit() {}
@@ -69,10 +74,11 @@ bool EditedSource::canInsertInOffset(Sou
 deconstructMacroArgLoc(OrigLoc, ExpLoc, ArgUse);
 auto I = ExpansionToArgMap.find(ExpLoc.getRawEncoding());
 if (I != ExpansionToArgMap.end() &&
-std::find_if(
-I->second.begin(), I->second.end(), [&](const MacroArgUse &U) {
-  return ArgUse.first == U.first && ArgUse.second != U.second;
-}) != I->second.end()) {
+find_if(I->second, [&](const MacroArgUse &U) {
+  return ArgUse.Identifier == U.Identifier &&
+ std::tie(ArgUse.ImmediateExpansionLoc, ArgUse.UseLoc) !=
+ std::tie(U.ImmediateExpansionLoc, U.UseLoc);
+}) != I->second.end()) {
   // Trying to write in a macro argument input that has already been
   // written by a previous commit for another expansion of the same macro
   // argument name. For example:
@@ -89,7 +95,6 @@ bool EditedSource::canInsertInOffset(Sou
   return false;
 }
   }
-
   return true;
 }
 
@@ -102,13 +107,13 @@ bool EditedSource::commitInsert(SourceLo
 return true;
 
   if (SourceMgr.isMacroArgExpansion(OrigLoc)) {
-SourceLocation ExpLoc;
 MacroArgUse ArgUse;
+SourceLocation ExpLoc;
 deconstructMacroArgLoc(OrigLoc, ExpLoc, ArgUse);
-if (ArgUse.first)
+if (ArgUse.Identifier)
   CurrCommitMacroArgExps.emplace_back(ExpLoc, ArgUse);
   }
-  
+
   FileEdit &FA = FileEdits[Offs];
   if (FA.T

r345558 - [analyzer] Allow padding checker to traverse simple class hierarchies

2018-10-29 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Oct 29 18:20:37 2018
New Revision: 345558

URL: http://llvm.org/viewvc/llvm-project?rev=345558&view=rev
Log:
[analyzer] Allow padding checker to traverse simple class hierarchies

The existing padding checker skips classes that have any base classes. 
This patch allows the checker to traverse very simple cases: 
classes that have no fields and have exactly one base class. 
This is important mostly in the case of array declarations.

Patch by Max Bernstein!

Test plan: make check-all

Differential revision: https://reviews.llvm.org/D53206

Added:
cfe/trunk/test/Analysis/padding_inherit.cpp
Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp?rev=345558&r1=345557&r2=345558&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp Mon Oct 29 
18:20:37 2018
@@ -75,6 +75,20 @@ public:
 if (shouldSkipDecl(RD))
   return;
 
+// TODO: Figure out why we are going through declarations and not only
+// definitions.
+if (!(RD = RD->getDefinition()))
+  return;
+
+// This is the simplest correct case: a class with no fields and one base
+// class. Other cases are more complicated because of how the base classes
+// & fields might interact, so we don't bother dealing with them.
+// TODO: Support other combinations of base classes and fields.
+if (auto *CXXRD = dyn_cast(RD))
+  if (CXXRD->field_empty() && CXXRD->getNumBases() == 1)
+return 
visitRecord(CXXRD->bases().begin()->getType()->getAsRecordDecl(),
+   PadMultiplier);
+
 auto &ASTContext = RD->getASTContext();
 const ASTRecordLayout &RL = ASTContext.getASTRecordLayout(RD);
 assert(llvm::isPowerOf2_64(RL.getAlignment().getQuantity()));
@@ -112,12 +126,15 @@ public:
 if (RT == nullptr)
   return;
 
-// TODO: Recurse into the fields and base classes to see if any
-// of those have excess padding.
+// TODO: Recurse into the fields to see if they have excess padding.
 visitRecord(RT->getDecl(), Elts);
   }
 
   bool shouldSkipDecl(const RecordDecl *RD) const {
+// TODO: Figure out why we are going through declarations and not only
+// definitions.
+if (!(RD = RD->getDefinition()))
+  return true;
 auto Location = RD->getLocation();
 // If the construct doesn't have a source file, then it's not something
 // we want to diagnose.
@@ -132,13 +149,14 @@ public:
 // Not going to attempt to optimize unions.
 if (RD->isUnion())
   return true;
-// How do you reorder fields if you haven't got any?
-if (RD->field_empty())
-  return true;
 if (auto *CXXRD = dyn_cast(RD)) {
   // Tail padding with base classes ends up being very complicated.
-  // We will skip objects with base classes for now.
-  if (CXXRD->getNumBases() != 0)
+  // We will skip objects with base classes for now, unless they do not
+  // have fields.
+  // TODO: Handle more base class scenarios.
+  if (!CXXRD->field_empty() && CXXRD->getNumBases() != 0)
+return true;
+  if (CXXRD->field_empty() && CXXRD->getNumBases() != 1)
 return true;
   // Virtual bases are complicated, skipping those for now.
   if (CXXRD->getNumVBases() != 0)
@@ -150,6 +168,10 @@ public:
   if (CXXRD->getTypeForDecl()->isInstantiationDependentType())
 return true;
 }
+// How do you reorder fields if you haven't got any?
+else if (RD->field_empty())
+  return true;
+
 auto IsTrickyField = [](const FieldDecl *FD) -> bool {
   // Bitfield layout is hard.
   if (FD->isBitField())
@@ -323,7 +345,7 @@ public:
 BR->emitReport(std::move(Report));
   }
 };
-}
+} // namespace
 
 void ento::registerPaddingChecker(CheckerManager &Mgr) {
   Mgr.registerChecker();

Added: cfe/trunk/test/Analysis/padding_inherit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/padding_inherit.cpp?rev=345558&view=auto
==
--- cfe/trunk/test/Analysis/padding_inherit.cpp (added)
+++ cfe/trunk/test/Analysis/padding_inherit.cpp Mon Oct 29 18:20:37 2018
@@ -0,0 +1,28 @@
+// RUN: %clang_analyze_cc1 -std=c++14 -analyzer-checker=optin.performance 
-analyzer-config optin.performance.Padding:AllowedPad=20 -verify %s
+
+// A class that has no fields and one base class should visit that base class
+// instead. Note that despite having excess padding of 2, this is flagged
+// because of its usage in an array of 100 elements below (`ais').
+// TODO: Add a note to the bug report with BugReport::addNote() to mention the
+// variable using the class and a

r311935 - [analyzer] Fix crash in modeling arithmetic

2017-08-28 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Aug 28 14:15:21 2017
New Revision: 311935

URL: http://llvm.org/viewvc/llvm-project?rev=311935&view=rev
Log:
[analyzer] Fix crash in modeling arithmetic

This diff fixes modeling of arithmetic 
expressions where pointers are treated as integers 
(i.e. via C-style / reinterpret casts).
For now we return UnknownVal unless the operation is a comparison.

Test plan: make check-all

Differential revision: https://reviews.llvm.org/D37120

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
cfe/trunk/test/Analysis/ptr-arith.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp?rev=311935&r1=311934&r2=311935&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp Mon Aug 28 14:15:21 
2017
@@ -360,10 +360,18 @@ SVal SimpleSValBuilder::evalBinOpNN(Prog
   Loc lhsL = lhs.castAs().getLoc();
   switch (rhs.getSubKind()) {
 case nonloc::LocAsIntegerKind:
+  // FIXME: at the moment the implementation 
+  // of modeling "pointers as integers" is not complete.
+  if (!BinaryOperator::isComparisonOp(op))
+return UnknownVal(); 
   return evalBinOpLL(state, op, lhsL,
  rhs.castAs().getLoc(),
  resultTy);
 case nonloc::ConcreteIntKind: {
+  // FIXME: at the moment the implementation 
+  // of modeling "pointers as integers" is not complete.
+  if (!BinaryOperator::isComparisonOp(op))
+return UnknownVal();
   // Transform the integer into a location and compare.
   // FIXME: This only makes sense for comparisons. If we want to, say,
   // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it,

Modified: cfe/trunk/test/Analysis/ptr-arith.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/ptr-arith.cpp?rev=311935&r1=311934&r2=311935&view=diff
==
--- cfe/trunk/test/Analysis/ptr-arith.cpp (original)
+++ cfe/trunk/test/Analysis/ptr-arith.cpp Mon Aug 28 14:15:21 2017
@@ -105,3 +105,9 @@ unsigned ptrSubtractionNoCrash(char *Beg
 return 0;
   return N;
 }
+
+// Bug 34309
+bool ptrAsIntegerSubtractionNoCrash(long x, char *p) {
+  long y = (long)p - 1;
+  return y == x;
+}


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


r311947 - [analyzer] Adjust ptr arithmetic test

2017-08-28 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Aug 28 15:58:54 2017
New Revision: 311947

URL: http://llvm.org/viewvc/llvm-project?rev=311947&view=rev
Log:
[analyzer] Adjust ptr arithmetic test

Replace "long" with __UINTPTR_TYPE__
to make the test added in rL311935 Windows-friendly.
Caught by the buildbot llvm-clang-x86_64-expensive-checks-win.

Modified:
cfe/trunk/test/Analysis/ptr-arith.cpp

Modified: cfe/trunk/test/Analysis/ptr-arith.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/ptr-arith.cpp?rev=311947&r1=311946&r2=311947&view=diff
==
--- cfe/trunk/test/Analysis/ptr-arith.cpp (original)
+++ cfe/trunk/test/Analysis/ptr-arith.cpp Mon Aug 28 15:58:54 2017
@@ -107,7 +107,7 @@ unsigned ptrSubtractionNoCrash(char *Beg
 }
 
 // Bug 34309
-bool ptrAsIntegerSubtractionNoCrash(long x, char *p) {
-  long y = (long)p - 1;
+bool ptrAsIntegerSubtractionNoCrash(__UINTPTR_TYPE__ x, char *p) {
+  __UINTPTR_TYPE__ y = (__UINTPTR_TYPE__)p - 1;
   return y == x;
 }


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


r314011 - [clang] Fix printf fixit for objc specific types

2017-09-22 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Fri Sep 22 11:36:06 2017
New Revision: 314011

URL: http://llvm.org/viewvc/llvm-project?rev=314011&view=rev
Log:
[clang] Fix printf fixit for objc specific types

For the triple thumbv7-apple-ios8.0.0 ssize_t is long and size_t is unsigned 
long,
while NSInteger is int and NSUinteger is unsigned int. Following 
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html
Clang catches it and insert a cast to long, for example
 printf("%zd", getNSInteger())
will be replaced with 
 printf("%zd", (long)getNSInteger())
but since the underlying type of ssize_t is long the specifier "%zd" is not 
getting replaced.
This diff changes this behavior to enable replacing the specifier "%zd" with 
the correct one.

Differential revision: https://reviews.llvm.org/D38159

Test plan: make check-all

Added:
cfe/trunk/test/FixIt/fixit-format-ios.m
Modified:
cfe/trunk/lib/Sema/SemaChecking.cpp

Modified: cfe/trunk/lib/Sema/SemaChecking.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=314011&r1=314010&r2=314011&view=diff
==
--- cfe/trunk/lib/Sema/SemaChecking.cpp (original)
+++ cfe/trunk/lib/Sema/SemaChecking.cpp Fri Sep 22 11:36:06 2017
@@ -6346,7 +6346,7 @@ CheckPrintfHandler::checkFormatExpr(cons
   CastFix << ")";
 
   SmallVector Hints;
-  if (!AT.matchesType(S.Context, IntendedTy))
+  if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 
 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
 
   if (const CStyleCastExpr *CCast = dyn_cast(E)) {

Added: cfe/trunk/test/FixIt/fixit-format-ios.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/FixIt/fixit-format-ios.m?rev=314011&view=auto
==
--- cfe/trunk/test/FixIt/fixit-format-ios.m (added)
+++ cfe/trunk/test/FixIt/fixit-format-ios.m Fri Sep 22 11:36:06 2017
@@ -0,0 +1,26 @@
+// RUN: cp %s %t
+// RUN: %clang_cc1 -triple thumbv7-apple-ios8.0.0 -fsyntax-only -Wformat 
-fixit %t
+// RUN: grep -v CHECK %t | FileCheck %s
+
+int printf(const char * restrict, ...);
+typedef unsigned int NSUInteger;
+typedef int NSInteger;
+NSUInteger getNSUInteger();
+NSInteger getNSInteger();
+
+void test() {
+  // For thumbv7-apple-ios8.0.0 the underlying type of ssize_t is long
+  // and the underlying type of size_t is unsigned long.
+
+  printf("test 1: %zu", getNSUInteger()); 
+  // CHECK: printf("test 1: %lu", (unsigned long)getNSUInteger());
+
+  printf("test 2: %zu %zu", getNSUInteger(), getNSUInteger());
+  // CHECK: printf("test 2: %lu %lu", (unsigned long)getNSUInteger(), 
(unsigned long)getNSUInteger());
+
+  printf("test 3: %zd", getNSInteger()); 
+  // CHECK: printf("test 3: %ld", (long)getNSInteger());
+
+  printf("test 4: %zd %zd", getNSInteger(), getNSInteger());
+  // CHECK: printf("test 4: %ld %ld", (long)getNSInteger(), 
(long)getNSInteger());
+}


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


r314022 - [clang] Fix isExternC matcher docs

2017-09-22 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Fri Sep 22 12:29:38 2017
New Revision: 314022

URL: http://llvm.org/viewvc/llvm-project?rev=314022&view=rev
Log:
[clang] Fix isExternC matcher docs

The wording in the documentation for the matcher isExternC 
appears to be misleading since this matcher 
is applicable to functions and variables as well. 
This diff changes the comment and regenerates the html file.

Differential revision: https://reviews.llvm.org/D38151

Modified:
cfe/trunk/docs/LibASTMatchersReference.html
cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h

Modified: cfe/trunk/docs/LibASTMatchersReference.html
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/LibASTMatchersReference.html?rev=314022&r1=314021&r2=314022&view=diff
==
--- cfe/trunk/docs/LibASTMatchersReference.html (original)
+++ cfe/trunk/docs/LibASTMatchersReference.html Fri Sep 22 12:29:38 2017
@@ -2741,19 +2741,22 @@ functionDecl(isExplicitTemplateSpecializ
 Usable as: MatcherFunctionDecl>,
 MatcherVarDecl>,
 MatcherCXXRecordDecl>
 
 
-
 MatcherFunctionDecl>isExternC
-Matches extern "C" 
function declarations.
+Matches extern "C" 
function or variable declarations.
 
 Given:
   extern "C" void f() {}
   extern "C" { void g() {} }
   void h() {}
+  extern "C" int x = 1;
+  extern "C" int y = 2;
+  int z = 3;
 functionDecl(isExternC())
-  matches the declaration of f and g, but not the declaration h
+  matches the declaration of f and g, but not the declaration of h.
+varDecl(isExternC())
+  matches the declaration of x and y, but not the declaration of z.
 
 
-
 MatcherFunctionDecl>isInline
 Matches function and 
namespace declarations that are marked with
 the inline keyword.
@@ -3680,19 +3683,22 @@ functionDecl(isExplicitTemplateSpecializ
 Usable as: MatcherFunctionDecl>,
 MatcherVarDecl>,
 MatcherCXXRecordDecl>
 
 
-
 MatcherVarDecl>isExternC
-Matches extern "C" 
function declarations.
+Matches extern "C" 
function or variable declarations.
 
 Given:
   extern "C" void f() {}
   extern "C" { void g() {} }
   void h() {}
+  extern "C" int x = 1;
+  extern "C" int y = 2;
+  int z = 3;
 functionDecl(isExternC())
-  matches the declaration of f and g, but not the declaration h
+  matches the declaration of f and g, but not the declaration of h.
+varDecl(isExternC())
+  matches the declaration of x and y, but not the declaration of z.
 
 
-
 MatcherVarDecl>isStaticStorageClass
 Matches 
variablefunction declarations that have "static" storage
 class specifier ("static" keyword) written in the source.

Modified: cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h?rev=314022&r1=314021&r2=314022&view=diff
==
--- cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h (original)
+++ cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h Fri Sep 22 12:29:38 2017
@@ -3533,16 +3533,21 @@ AST_MATCHER_P(FunctionDecl, returns,
   return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
 }
 
-/// \brief Matches extern "C" function declarations.
+/// \brief Matches extern "C" function or variable declarations.
 ///
 /// Given:
 /// \code
 ///   extern "C" void f() {}
 ///   extern "C" { void g() {} }
 ///   void h() {}
+///   extern "C" int x = 1;
+///   extern "C" int y = 2;
+///   int z = 3;
 /// \endcode
 /// functionDecl(isExternC())
-///   matches the declaration of f and g, but not the declaration h
+///   matches the declaration of f and g, but not the declaration of h.
+/// varDecl(isExternC())
+///   matches the declaration of x and y, but not the declaration of z.
 AST_POLYMORPHIC_MATCHER(isExternC, 
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
VarDecl)) {
   return Node.isExternC();


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


r337148 - [Sema] Add fixit for unused lambda captures

2018-07-16 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Jul 16 00:23:47 2018
New Revision: 337148

URL: http://llvm.org/viewvc/llvm-project?rev=337148&view=rev
Log:
[Sema] Add fixit for unused lambda captures

This diff adds a fixit to suggest removing unused lambda captures 
in the appropriate diagnostic.

Patch by Andrew Comminos!

Test plan: make check-all

Differential revision: https://reviews.llvm.org/D48845

Added:
cfe/trunk/test/FixIt/fixit-unused-lambda-capture.cpp
Modified:
cfe/trunk/include/clang/Sema/DeclSpec.h
cfe/trunk/include/clang/Sema/ScopeInfo.h
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Parse/ParseExprCXX.cpp
cfe/trunk/lib/Sema/SemaLambda.cpp

Modified: cfe/trunk/include/clang/Sema/DeclSpec.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/DeclSpec.h?rev=337148&r1=337147&r2=337148&view=diff
==
--- cfe/trunk/include/clang/Sema/DeclSpec.h (original)
+++ cfe/trunk/include/clang/Sema/DeclSpec.h Mon Jul 16 00:23:47 2018
@@ -2540,12 +2540,16 @@ struct LambdaIntroducer {
 LambdaCaptureInitKind InitKind;
 ExprResult Init;
 ParsedType InitCaptureType;
+SourceRange ExplicitRange;
+
 LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
   IdentifierInfo *Id, SourceLocation EllipsisLoc,
   LambdaCaptureInitKind InitKind, ExprResult Init,
-  ParsedType InitCaptureType)
+  ParsedType InitCaptureType,
+  SourceRange ExplicitRange)
 : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc),
-  InitKind(InitKind), Init(Init), InitCaptureType(InitCaptureType) {}
+  InitKind(InitKind), Init(Init), InitCaptureType(InitCaptureType),
+  ExplicitRange(ExplicitRange) {}
   };
 
   SourceRange Range;
@@ -2563,9 +2567,10 @@ struct LambdaIntroducer {
   SourceLocation EllipsisLoc,
   LambdaCaptureInitKind InitKind,
   ExprResult Init, 
-  ParsedType InitCaptureType) {
+  ParsedType InitCaptureType,
+  SourceRange ExplicitRange) {
 Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, InitKind, 
Init,
- InitCaptureType));
+ InitCaptureType, ExplicitRange));
   }
 };
 

Modified: cfe/trunk/include/clang/Sema/ScopeInfo.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/ScopeInfo.h?rev=337148&r1=337147&r2=337148&view=diff
==
--- cfe/trunk/include/clang/Sema/ScopeInfo.h (original)
+++ cfe/trunk/include/clang/Sema/ScopeInfo.h Mon Jul 16 00:23:47 2018
@@ -829,6 +829,9 @@ public:
   ///  if the enclosing full-expression is instantiation dependent).
   llvm::SmallSet NonODRUsedCapturingExprs;
 
+  /// A map of explicit capture indices to their introducer source ranges.
+  llvm::DenseMap ExplicitCaptureRanges;
+
   /// Contains all of the variables defined in this lambda that shadow 
variables
   /// that were defined in parent contexts. Used to avoid warnings when the
   /// shadowed variables are uncaptured by this lambda.

Modified: cfe/trunk/include/clang/Sema/Sema.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=337148&r1=337147&r2=337148&view=diff
==
--- cfe/trunk/include/clang/Sema/Sema.h (original)
+++ cfe/trunk/include/clang/Sema/Sema.h Mon Jul 16 00:23:47 2018
@@ -5602,8 +5602,10 @@ public:
   /// Does copying/destroying the captured variable have side effects?
   bool CaptureHasSideEffects(const sema::Capture &From);
 
-  /// Diagnose if an explicit lambda capture is unused.
-  void DiagnoseUnusedLambdaCapture(const sema::Capture &From);
+  /// Diagnose if an explicit lambda capture is unused. Returns true if a
+  /// diagnostic is emitted.
+  bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
+   const sema::Capture &From);
 
   /// Complete a lambda-expression having processed and attached the
   /// lambda body.

Modified: cfe/trunk/lib/Parse/ParseExprCXX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseExprCXX.cpp?rev=337148&r1=337147&r2=337148&view=diff
==
--- cfe/trunk/lib/Parse/ParseExprCXX.cpp (original)
+++ cfe/trunk/lib/Parse/ParseExprCXX.cpp Mon Jul 16 00:23:47 2018
@@ -808,6 +808,7 @@ Optional Parser::ParseLambdaIn
 IdentifierInfo *Id = nullptr;
 SourceLocation EllipsisLoc;
 ExprResult Init;
+SourceLocation LocStart = Tok.getLocation();
 
 if (Tok.is(tok::star)) {
   Loc = ConsumeToken(); 
@@ -981,8 +982,11 @@ Optional Parser::ParseLambdaIn
   Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
   Init = InitExpr;
 }

[clang-tools-extra] r281826 - [clang-rename] Fix handling of unchanged files

2016-09-17 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Sat Sep 17 12:08:47 2016
New Revision: 281826

URL: http://llvm.org/viewvc/llvm-project?rev=281826&view=rev
Log:
[clang-rename] Fix handling of unchanged files

Fix the output of clang-rename for the files without modifications.
Update the code in clang-reorder-fields/tool/ClangReorderFields.cpp 
to avoid inconsistency.

Example:
a.h:
struct A {};
a.cpp:
#include "a.h"
int main() { return 0; }

Before the changes the output looks like this:
clang-rename -qualified-name=A -new-name=B a.cpp


Test plan: make -j8 check-clang-tools

Differential revision: https://reviews.llvm.org/D24634

Added:
clang-tools-extra/trunk/test/clang-rename/IncludeHeaderWithSymbol.cpp
clang-tools-extra/trunk/test/clang-rename/Inputs/HeaderWithSymbol.h
Modified:
clang-tools-extra/trunk/clang-rename/tool/ClangRename.cpp
clang-tools-extra/trunk/clang-reorder-fields/tool/ClangReorderFields.cpp

Modified: clang-tools-extra/trunk/clang-rename/tool/ClangRename.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-rename/tool/ClangRename.cpp?rev=281826&r1=281825&r2=281826&view=diff
==
--- clang-tools-extra/trunk/clang-rename/tool/ClangRename.cpp (original)
+++ clang-tools-extra/trunk/clang-rename/tool/ClangRename.cpp Sat Sep 17 
12:08:47 2016
@@ -222,7 +222,7 @@ int main(int argc, const char **argv) {
 Tool.applyAllReplacements(Rewrite);
 for (const auto &File : Files) {
   const auto *Entry = FileMgr.getFile(File);
-  auto ID = Sources.translateFile(Entry);
+  const auto ID = Sources.getOrCreateFileID(Entry, SrcMgr::C_User);
   Rewrite.getEditBuffer(ID).write(outs());
 }
   }

Modified: 
clang-tools-extra/trunk/clang-reorder-fields/tool/ClangReorderFields.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-reorder-fields/tool/ClangReorderFields.cpp?rev=281826&r1=281825&r2=281826&view=diff
==
--- clang-tools-extra/trunk/clang-reorder-fields/tool/ClangReorderFields.cpp 
(original)
+++ clang-tools-extra/trunk/clang-reorder-fields/tool/ClangReorderFields.cpp 
Sat Sep 17 12:08:47 2016
@@ -80,13 +80,8 @@ int main(int argc, const char **argv) {
 
   for (const auto &File : Files) {
 const auto *Entry = FileMgr.getFile(File);
-const auto ID = Sources.translateFile(Entry);
-// The method Rewriter::getRewriteBufferFor returns nullptr if
-// the file has not been changed.
-if (const auto *RB = Rewrite.getRewriteBufferFor(ID))
-  RB->write(outs());
-else
-  outs() << Sources.getMemoryBufferForFile(Entry)->getBuffer();
+const auto ID = Sources.getOrCreateFileID(Entry, SrcMgr::C_User);
+Rewrite.getEditBuffer(ID).write(outs());
   }
 
   return ExitCode;

Added: clang-tools-extra/trunk/test/clang-rename/IncludeHeaderWithSymbol.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-rename/IncludeHeaderWithSymbol.cpp?rev=281826&view=auto
==
--- clang-tools-extra/trunk/test/clang-rename/IncludeHeaderWithSymbol.cpp 
(added)
+++ clang-tools-extra/trunk/test/clang-rename/IncludeHeaderWithSymbol.cpp Sat 
Sep 17 12:08:47 2016
@@ -0,0 +1,10 @@
+#include "Inputs/HeaderWithSymbol.h"
+
+int main() {
+  return 0; // CHECK: {{^  return 0;}}
+}
+
+// Test 1.
+// The file IncludeHeaderWithSymbol.cpp doesn't contain the symbol Foo
+// and is expected to be written to stdout without modifications
+// RUN: clang-rename -qualified-name=Foo -new-name=Bar %s -- | FileCheck %s

Added: clang-tools-extra/trunk/test/clang-rename/Inputs/HeaderWithSymbol.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-rename/Inputs/HeaderWithSymbol.h?rev=281826&view=auto
==
--- clang-tools-extra/trunk/test/clang-rename/Inputs/HeaderWithSymbol.h (added)
+++ clang-tools-extra/trunk/test/clang-rename/Inputs/HeaderWithSymbol.h Sat Sep 
17 12:08:47 2016
@@ -0,0 +1 @@
+struct Foo {};


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


Re: [PATCH] D23901: Minor cleanup of the class CallStackFrame

2016-09-19 Thread Alexander Shaposhnikov via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL281907: Remove excessive padding from the struct 
CallStackFrame (authored by alexshap).

Changed prior to commit:
  https://reviews.llvm.org/D23901?vs=69310&id=71838#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D23901

Files:
  cfe/trunk/lib/AST/ExprConstant.cpp

Index: cfe/trunk/lib/AST/ExprConstant.cpp
===
--- cfe/trunk/lib/AST/ExprConstant.cpp
+++ cfe/trunk/lib/AST/ExprConstant.cpp
@@ -310,15 +310,9 @@
 /// Parent - The caller of this stack frame.
 CallStackFrame *Caller;
 
-/// CallLoc - The location of the call expression for this call.
-SourceLocation CallLoc;
-
 /// Callee - The function which was called.
 const FunctionDecl *Callee;
 
-/// Index - The call index of this call.
-unsigned Index;
-
 /// This - The binding for the this pointer in this call, if any.
 const LValue *This;
 
@@ -333,6 +327,12 @@
 /// Temporaries - Temporary lvalues materialized within this stack frame.
 MapTy Temporaries;
 
+/// CallLoc - The location of the call expression for this call.
+SourceLocation CallLoc;
+
+/// Index - The call index of this call.
+unsigned Index;
+
 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
const FunctionDecl *Callee, const LValue *This,
APValue *Arguments);


Index: cfe/trunk/lib/AST/ExprConstant.cpp
===
--- cfe/trunk/lib/AST/ExprConstant.cpp
+++ cfe/trunk/lib/AST/ExprConstant.cpp
@@ -310,15 +310,9 @@
 /// Parent - The caller of this stack frame.
 CallStackFrame *Caller;
 
-/// CallLoc - The location of the call expression for this call.
-SourceLocation CallLoc;
-
 /// Callee - The function which was called.
 const FunctionDecl *Callee;
 
-/// Index - The call index of this call.
-unsigned Index;
-
 /// This - The binding for the this pointer in this call, if any.
 const LValue *This;
 
@@ -333,6 +327,12 @@
 /// Temporaries - Temporary lvalues materialized within this stack frame.
 MapTy Temporaries;
 
+/// CallLoc - The location of the call expression for this call.
+SourceLocation CallLoc;
+
+/// Index - The call index of this call.
+unsigned Index;
+
 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
const FunctionDecl *Callee, const LValue *This,
APValue *Arguments);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r281907 - Remove excessive padding from the struct CallStackFrame

2016-09-19 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Sep 19 10:57:29 2016
New Revision: 281907

URL: http://llvm.org/viewvc/llvm-project?rev=281907&view=rev
Log:
Remove excessive padding from the struct CallStackFrame

The struct CallStackFrame is in lib/AST/ExprConstant.cpp
inside anonymous namespace.
This diff reorders the fields and removes excessive padding.
Test plan: make -j8 check-clang

Differential revision: https://reviews.llvm.org/D23901

Modified:
cfe/trunk/lib/AST/ExprConstant.cpp

Modified: cfe/trunk/lib/AST/ExprConstant.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ExprConstant.cpp?rev=281907&r1=281906&r2=281907&view=diff
==
--- cfe/trunk/lib/AST/ExprConstant.cpp (original)
+++ cfe/trunk/lib/AST/ExprConstant.cpp Mon Sep 19 10:57:29 2016
@@ -310,15 +310,9 @@ namespace {
 /// Parent - The caller of this stack frame.
 CallStackFrame *Caller;
 
-/// CallLoc - The location of the call expression for this call.
-SourceLocation CallLoc;
-
 /// Callee - The function which was called.
 const FunctionDecl *Callee;
 
-/// Index - The call index of this call.
-unsigned Index;
-
 /// This - The binding for the this pointer in this call, if any.
 const LValue *This;
 
@@ -333,6 +327,12 @@ namespace {
 /// Temporaries - Temporary lvalues materialized within this stack frame.
 MapTy Temporaries;
 
+/// CallLoc - The location of the call expression for this call.
+SourceLocation CallLoc;
+
+/// Index - The call index of this call.
+unsigned Index;
+
 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
const FunctionDecl *Callee, const LValue *This,
APValue *Arguments);


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


[PATCH] D24751: [cleanup] Remove excessive padding from TextTokenRetokenizer::Position

2016-09-19 Thread Alexander Shaposhnikov via cfe-commits
alexshap created this revision.
alexshap added reviewers: gribozavr, craig.topper.
alexshap added a subscriber: cfe-commits.
alexshap set the repository for this revision to rL LLVM.
alexshap changed the visibility of this Differential Revision from "Public (No 
Login Required)" to "All Users".

Reorder the fields of the struct TextTokenRetokenizer::Position to remove 
excessive padding.
Test plan: make -j8 check-clang

Repository:
  rL LLVM

https://reviews.llvm.org/D24751

Files:
  lib/AST/CommentParser.cpp

Index: lib/AST/CommentParser.cpp
===
--- lib/AST/CommentParser.cpp
+++ lib/AST/CommentParser.cpp
@@ -40,11 +40,11 @@
 
   /// A position in \c Toks.
   struct Position {
-unsigned CurToken;
 const char *BufferStart;
 const char *BufferEnd;
 const char *BufferPtr;
 SourceLocation BufferStartLoc;
+unsigned CurToken;
   };
 
   /// Current position in Toks.


Index: lib/AST/CommentParser.cpp
===
--- lib/AST/CommentParser.cpp
+++ lib/AST/CommentParser.cpp
@@ -40,11 +40,11 @@
 
   /// A position in \c Toks.
   struct Position {
-unsigned CurToken;
 const char *BufferStart;
 const char *BufferEnd;
 const char *BufferPtr;
 SourceLocation BufferStartLoc;
+unsigned CurToken;
   };
 
   /// Current position in Toks.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D24751: [cleanup] Remove excessive padding from TextTokenRetokenizer::Position

2016-09-19 Thread Alexander Shaposhnikov via cfe-commits
alexshap added a comment.

F2434937: Screen Shot 2016-09-19 at 7.33.38 PM.png 

the order BufferStart, BufferEnd,BufferPtr,BufferStartLoc,CurToken works as well


Repository:
  rL LLVM

https://reviews.llvm.org/D24751



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


[PATCH] D24754: [cleanup] Remove excessive padding from RedeclarableResult

2016-09-20 Thread Alexander Shaposhnikov via cfe-commits
alexshap created this revision.
alexshap added reviewers: rtrieu, rsmith, bkramer, mehdi_amini.
alexshap added a subscriber: cfe-commits.
alexshap set the repository for this revision to rL LLVM.
alexshap changed the visibility of this Differential Revision from "Public (No 
Login Required)" to "All Users".

This diff reorders the fields of the class RedeclarableResult to remove 
excessive padding.
Test plan: make -j8 check-clang

Repository:
  rL LLVM

https://reviews.llvm.org/D24754

Files:
  lib/Serialization/ASTReaderDecl.cpp

Index: lib/Serialization/ASTReaderDecl.cpp
===
--- lib/Serialization/ASTReaderDecl.cpp
+++ lib/Serialization/ASTReaderDecl.cpp
@@ -146,13 +146,13 @@
 
 /// Results from loading a RedeclarableDecl.
 class RedeclarableResult {
-  GlobalDeclID FirstID;
   Decl *MergeWith;
+  GlobalDeclID FirstID;
   bool IsKeyDecl;
 
 public:
-  RedeclarableResult(GlobalDeclID FirstID, Decl *MergeWith, bool IsKeyDecl)
-  : FirstID(FirstID), MergeWith(MergeWith), IsKeyDecl(IsKeyDecl) {}
+  RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
+  : MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}
 
   /// \brief Retrieve the first ID.
   GlobalDeclID getFirstID() const { return FirstID; }
@@ -2311,7 +2311,7 @@
   if (IsFirstLocalDecl)
 Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
 
-  return RedeclarableResult(FirstDeclID, MergeWith, IsKeyDecl);
+  return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
 }
 
 /// \brief Attempts to merge the given declaration (D) with another declaration
@@ -2353,8 +2353,9 @@
  DeclID DsID, bool IsKeyDecl) {
   auto *DPattern = D->getTemplatedDecl();
   auto *ExistingPattern = Existing->getTemplatedDecl();
-  RedeclarableResult Result(DPattern->getCanonicalDecl()->getGlobalID(),
-/*MergeWith*/ ExistingPattern, IsKeyDecl);
+  RedeclarableResult Result(/*MergeWith*/ ExistingPattern,  
+DPattern->getCanonicalDecl()->getGlobalID(), 
+IsKeyDecl);
 
   if (auto *DClass = dyn_cast(DPattern)) {
 // Merge with any existing definition.


Index: lib/Serialization/ASTReaderDecl.cpp
===
--- lib/Serialization/ASTReaderDecl.cpp
+++ lib/Serialization/ASTReaderDecl.cpp
@@ -146,13 +146,13 @@
 
 /// Results from loading a RedeclarableDecl.
 class RedeclarableResult {
-  GlobalDeclID FirstID;
   Decl *MergeWith;
+  GlobalDeclID FirstID;
   bool IsKeyDecl;
 
 public:
-  RedeclarableResult(GlobalDeclID FirstID, Decl *MergeWith, bool IsKeyDecl)
-  : FirstID(FirstID), MergeWith(MergeWith), IsKeyDecl(IsKeyDecl) {}
+  RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
+  : MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}
 
   /// \brief Retrieve the first ID.
   GlobalDeclID getFirstID() const { return FirstID; }
@@ -2311,7 +2311,7 @@
   if (IsFirstLocalDecl)
 Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
 
-  return RedeclarableResult(FirstDeclID, MergeWith, IsKeyDecl);
+  return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
 }
 
 /// \brief Attempts to merge the given declaration (D) with another declaration
@@ -2353,8 +2353,9 @@
  DeclID DsID, bool IsKeyDecl) {
   auto *DPattern = D->getTemplatedDecl();
   auto *ExistingPattern = Existing->getTemplatedDecl();
-  RedeclarableResult Result(DPattern->getCanonicalDecl()->getGlobalID(),
-/*MergeWith*/ ExistingPattern, IsKeyDecl);
+  RedeclarableResult Result(/*MergeWith*/ ExistingPattern,  
+DPattern->getCanonicalDecl()->getGlobalID(), 
+IsKeyDecl);
 
   if (auto *DClass = dyn_cast(DPattern)) {
 // Merge with any existing definition.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D24754: [cleanup] Remove excessive padding from RedeclarableResult

2016-09-20 Thread Alexander Shaposhnikov via cfe-commits
alexshap added a comment.

F2435929: Screen Shot 2016-09-20 at 12.19.51 AM.png 



Repository:
  rL LLVM

https://reviews.llvm.org/D24754



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


r281995 - [cleanup] Remove excessive padding from TextTokenRetokenizer::Position

2016-09-20 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Tue Sep 20 13:32:48 2016
New Revision: 281995

URL: http://llvm.org/viewvc/llvm-project?rev=281995&view=rev
Log:
[cleanup] Remove excessive padding from TextTokenRetokenizer::Position

Reorder the fields of the struct TextTokenRetokenizer::Position to remove 
excessive padding.
Test plan: make -j8 check-clang

Differential revision: https://reviews.llvm.org/D24751

Modified:
cfe/trunk/lib/AST/CommentParser.cpp

Modified: cfe/trunk/lib/AST/CommentParser.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/CommentParser.cpp?rev=281995&r1=281994&r2=281995&view=diff
==
--- cfe/trunk/lib/AST/CommentParser.cpp (original)
+++ cfe/trunk/lib/AST/CommentParser.cpp Tue Sep 20 13:32:48 2016
@@ -40,11 +40,11 @@ class TextTokenRetokenizer {
 
   /// A position in \c Toks.
   struct Position {
-unsigned CurToken;
 const char *BufferStart;
 const char *BufferEnd;
 const char *BufferPtr;
 SourceLocation BufferStartLoc;
+unsigned CurToken;
   };
 
   /// Current position in Toks.


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


Re: [PATCH] D24751: [cleanup] Remove excessive padding from TextTokenRetokenizer::Position

2016-09-20 Thread Alexander Shaposhnikov via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL281995: [cleanup] Remove excessive padding from 
TextTokenRetokenizer::Position (authored by alexshap).

Changed prior to commit:
  https://reviews.llvm.org/D24751?vs=71897&id=71963#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D24751

Files:
  cfe/trunk/lib/AST/CommentParser.cpp

Index: cfe/trunk/lib/AST/CommentParser.cpp
===
--- cfe/trunk/lib/AST/CommentParser.cpp
+++ cfe/trunk/lib/AST/CommentParser.cpp
@@ -40,11 +40,11 @@
 
   /// A position in \c Toks.
   struct Position {
-unsigned CurToken;
 const char *BufferStart;
 const char *BufferEnd;
 const char *BufferPtr;
 SourceLocation BufferStartLoc;
+unsigned CurToken;
   };
 
   /// Current position in Toks.


Index: cfe/trunk/lib/AST/CommentParser.cpp
===
--- cfe/trunk/lib/AST/CommentParser.cpp
+++ cfe/trunk/lib/AST/CommentParser.cpp
@@ -40,11 +40,11 @@
 
   /// A position in \c Toks.
   struct Position {
-unsigned CurToken;
 const char *BufferStart;
 const char *BufferEnd;
 const char *BufferPtr;
 SourceLocation BufferStartLoc;
+unsigned CurToken;
   };
 
   /// Current position in Toks.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D24792: [analyzer] Fix crash in RetainCountChecker::checkEndFunction

2016-09-21 Thread Alexander Shaposhnikov via cfe-commits
alexshap added a comment.

Without the changes:
F2438373: Screen Shot 2016-09-21 at 12.38.22 AM.png 

With the patch the tests are green.


Repository:
  rL LLVM

https://reviews.llvm.org/D24792



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


Re: [PATCH] D24792: [analyzer] Fix crash in RetainCountChecker::checkEndFunction

2016-09-21 Thread Alexander Shaposhnikov via cfe-commits
alexshap added a comment.

> is that a problem for your codebase?


@zaks.anna  - yes it is.

> Another possible issue is that we will use the synthesized body if the 
> function name starts with "OSAtomicCompareAndSwap" since ?>we do not match 
> the full function name. If the function body is available, there is a higher 
> chance it is implementing something other >than the standard compare and 
> swap. We might want to start matching the full names of the functions are are 
> synthesizing.


yeah - i've just wanted to post a comment about it - btw - 
OSAtomicCompareAndSwap is not the only example (dispatch_sync, dispatch_async 
etc also create a problem). But in my case i ran into issue on the exact match 
(but on the other function).

I have not updated this patch yet because I have not found a good solution - 
still thinking (any suggestions appreciated). I probably understand the 
motivation behind the changes introduced in r264687 but yes, it causes several 
issues.


Repository:
  rL LLVM

https://reviews.llvm.org/D24792



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


Re: [PATCH] D24792: [analyzer] Fix crash in RetainCountChecker::checkEndFunction

2016-09-21 Thread Alexander Shaposhnikov via cfe-commits
alexshap added a comment.

@zaks.anna: it happens on one of the ports of libdispatch, but probably i also 
can reproduce this crash with OSAtomicCompareAndSwap.


Repository:
  rL LLVM

https://reviews.llvm.org/D24792



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


Re: [PATCH] D24792: [analyzer] Fix crash in RetainCountChecker::checkEndFunction

2016-09-21 Thread Alexander Shaposhnikov via cfe-commits
alexshap updated the summary for this revision.
alexshap updated this revision to Diff 72132.
alexshap added a comment.

Address the comments


Repository:
  rL LLVM

https://reviews.llvm.org/D24792

Files:
  lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
  lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
  test/Analysis/NSString.m

Index: test/Analysis/NSString.m
===
--- test/Analysis/NSString.m
+++ test/Analysis/NSString.m
@@ -289,7 +289,11 @@
 _Bool OSAtomicCompareAndSwapPtr( void *__oldValue, void *__newValue, void * 
volatile *__theValue ) {
   return opaque_OSAtomicCompareAndSwapPtr(__oldValue, __newValue, __theValue);
 }
-
+// Test that the analyzer doesn't crash when the farm model is used. 
+// The analyzer ignores the autosynthesized code.
+_Bool OSAtomicCompareAndSwapEmptyFunction( void *__oldValue, void *__newValue, 
void * volatile *__theValue ) {
+  return 0;
+}
 extern BOOL opaque_objc_atomicCompareAndSwapPtr(id predicate, id replacement, 
volatile id *objectLocation);
 extern BOOL objc_atomicCompareAndSwapPtr(id predicate, id replacement, 
volatile id *objectLocation) {
   return opaque_objc_atomicCompareAndSwapPtr(predicate, replacement, 
objectLocation);
@@ -441,4 +445,4 @@
 - (void)callValue {
   [self _value];
 }
-@end
\ No newline at end of file
+@end
Index: lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
===
--- lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
+++ lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
@@ -688,6 +688,10 @@
   if (!Mgr->getAnalysisDeclContext(D)->getAnalysis())
 return;
 
+  // Ignore autosynthesized code.
+  if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
+return;
+
   ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, 
&FunctionSummaries,IMode);
 
   // Set the graph auditor.
Index: lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
+++ lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
@@ -3863,7 +3863,7 @@
   // Don't process anything within synthesized bodies.
   const LocationContext *LCtx = Pred->getLocationContext();
   if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
-assert(LCtx->getParent());
+assert(!LCtx->inTopFrame()); 
 return;
   }
 


Index: test/Analysis/NSString.m
===
--- test/Analysis/NSString.m
+++ test/Analysis/NSString.m
@@ -289,7 +289,11 @@
 _Bool OSAtomicCompareAndSwapPtr( void *__oldValue, void *__newValue, void * volatile *__theValue ) {
   return opaque_OSAtomicCompareAndSwapPtr(__oldValue, __newValue, __theValue);
 }
-
+// Test that the analyzer doesn't crash when the farm model is used. 
+// The analyzer ignores the autosynthesized code.
+_Bool OSAtomicCompareAndSwapEmptyFunction( void *__oldValue, void *__newValue, void * volatile *__theValue ) {
+  return 0;
+}
 extern BOOL opaque_objc_atomicCompareAndSwapPtr(id predicate, id replacement, volatile id *objectLocation);
 extern BOOL objc_atomicCompareAndSwapPtr(id predicate, id replacement, volatile id *objectLocation) {
   return opaque_objc_atomicCompareAndSwapPtr(predicate, replacement, objectLocation);
@@ -441,4 +445,4 @@
 - (void)callValue {
   [self _value];
 }
-@end
\ No newline at end of file
+@end
Index: lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
===
--- lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
+++ lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
@@ -688,6 +688,10 @@
   if (!Mgr->getAnalysisDeclContext(D)->getAnalysis())
 return;
 
+  // Ignore autosynthesized code.
+  if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
+return;
+
   ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries,IMode);
 
   // Set the graph auditor.
Index: lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
+++ lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
@@ -3863,7 +3863,7 @@
   // Don't process anything within synthesized bodies.
   const LocationContext *LCtx = Pred->getLocationContext();
   if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
-assert(LCtx->getParent());
+assert(!LCtx->inTopFrame()); 
 return;
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D24754: [cleanup] Remove excessive padding from RedeclarableResult

2016-09-21 Thread Alexander Shaposhnikov via cfe-commits
alexshap added inline comments.


Comment at: lib/Serialization/ASTReaderDecl.cpp:154
@@ -153,3 +153,3 @@
 public:
-  RedeclarableResult(GlobalDeclID FirstID, Decl *MergeWith, bool IsKeyDecl)
-  : FirstID(FirstID), MergeWith(MergeWith), IsKeyDecl(IsKeyDecl) {}
+  RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
+  : MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}

vsk wrote:
> Why do you need to change the order of the parameters in the constructor?
To avoid inconsistency. Here the parameters match the fields and it seemed to 
me that it would be better to update the order. 


Repository:
  rL LLVM

https://reviews.llvm.org/D24754



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


Re: [PATCH] D24754: [cleanup] Remove excessive padding from RedeclarableResult

2016-09-22 Thread Alexander Shaposhnikov via cfe-commits
alexshap added inline comments.


Comment at: lib/Serialization/ASTReaderDecl.cpp:154
@@ -153,3 +153,3 @@
 public:
-  RedeclarableResult(GlobalDeclID FirstID, Decl *MergeWith, bool IsKeyDecl)
-  : FirstID(FirstID), MergeWith(MergeWith), IsKeyDecl(IsKeyDecl) {}
+  RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
+  : MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}

vsk wrote:
> alexshap wrote:
> > vsk wrote:
> > > Why do you need to change the order of the parameters in the constructor?
> > To avoid inconsistency. Here the parameters match the fields and it seemed 
> > to me that it would be better to update the order. 
> OK. But why not do the same thing for ObjCCategoriesVisitor?
The thing is that while the order of initializers needs to match the order of 
fields (and compilers catch it by generating a warning (and it's awesome), the 
order of ctor arguments doesn't need to match the order of fields (unless we 
are speaking about some readability concerns etc). The tool 
clang-reorder-fields handles correctly aggregate types & brace initializations 
(updates all the call sites) but doesn't change the order of ctor arguments 
(for now (v0)) - sometimes (for example when some fields use several arguments, 
or there is a non-trivial ctor body or there are other complications) it's not 
always easy to reason which order of ctor arguments is "natural" - and i try to 
preserve the old order (especially remembering about the compatible types and 
some call sites like emplace_back). 
Having said that - yea, the case of ObjCCategoriesVisitor is simple and i will 
update that diff as well (thanks for pointing out).


Repository:
  rL LLVM

https://reviews.llvm.org/D24754



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


Re: [PATCH] D24792: [analyzer] Fix crash in RetainCountChecker::checkEndFunction

2016-09-22 Thread Alexander Shaposhnikov via cfe-commits
alexshap updated this revision to Diff 72206.
alexshap added a comment.

Move the check to AnalysisConsumer::HandleCode.


Repository:
  rL LLVM

https://reviews.llvm.org/D24792

Files:
  lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
  lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
  test/Analysis/NSString.m

Index: test/Analysis/NSString.m
===
--- test/Analysis/NSString.m
+++ test/Analysis/NSString.m
@@ -289,7 +289,11 @@
 _Bool OSAtomicCompareAndSwapPtr( void *__oldValue, void *__newValue, void * 
volatile *__theValue ) {
   return opaque_OSAtomicCompareAndSwapPtr(__oldValue, __newValue, __theValue);
 }
-
+// Test that the analyzer doesn't crash when the farm model is used. 
+// The analyzer ignores the autosynthesized code.
+_Bool OSAtomicCompareAndSwapEmptyFunction( void *__oldValue, void *__newValue, 
void * volatile *__theValue ) {
+  return 0;
+}
 extern BOOL opaque_objc_atomicCompareAndSwapPtr(id predicate, id replacement, 
volatile id *objectLocation);
 extern BOOL objc_atomicCompareAndSwapPtr(id predicate, id replacement, 
volatile id *objectLocation) {
   return opaque_objc_atomicCompareAndSwapPtr(predicate, replacement, 
objectLocation);
@@ -441,4 +445,4 @@
 - (void)callValue {
   [self _value];
 }
-@end
\ No newline at end of file
+@end
Index: lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
===
--- lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
+++ lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
@@ -652,15 +652,19 @@
   if (Mode == AM_None)
 return;
 
+  // Clear the AnalysisManager of old AnalysisDeclContexts.
+  Mgr->ClearContexts();
+  // Ignore autosynthesized code.
+  if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
+return;
+
   DisplayFunction(D, Mode, IMode);
   CFG *DeclCFG = Mgr->getCFG(D);
   if (DeclCFG) {
 unsigned CFGSize = DeclCFG->size();
 MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize;
   }
 
-  // Clear the AnalysisManager of old AnalysisDeclContexts.
-  Mgr->ClearContexts();
   BugReporter BR(*Mgr);
 
   if (Mode & AM_Syntax)
Index: lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
+++ lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
@@ -3863,7 +3863,7 @@
   // Don't process anything within synthesized bodies.
   const LocationContext *LCtx = Pred->getLocationContext();
   if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
-assert(LCtx->getParent());
+assert(!LCtx->inTopFrame()); 
 return;
   }
 


Index: test/Analysis/NSString.m
===
--- test/Analysis/NSString.m
+++ test/Analysis/NSString.m
@@ -289,7 +289,11 @@
 _Bool OSAtomicCompareAndSwapPtr( void *__oldValue, void *__newValue, void * volatile *__theValue ) {
   return opaque_OSAtomicCompareAndSwapPtr(__oldValue, __newValue, __theValue);
 }
-
+// Test that the analyzer doesn't crash when the farm model is used. 
+// The analyzer ignores the autosynthesized code.
+_Bool OSAtomicCompareAndSwapEmptyFunction( void *__oldValue, void *__newValue, void * volatile *__theValue ) {
+  return 0;
+}
 extern BOOL opaque_objc_atomicCompareAndSwapPtr(id predicate, id replacement, volatile id *objectLocation);
 extern BOOL objc_atomicCompareAndSwapPtr(id predicate, id replacement, volatile id *objectLocation) {
   return opaque_objc_atomicCompareAndSwapPtr(predicate, replacement, objectLocation);
@@ -441,4 +445,4 @@
 - (void)callValue {
   [self _value];
 }
-@end
\ No newline at end of file
+@end
Index: lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
===
--- lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
+++ lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
@@ -652,15 +652,19 @@
   if (Mode == AM_None)
 return;
 
+  // Clear the AnalysisManager of old AnalysisDeclContexts.
+  Mgr->ClearContexts();
+  // Ignore autosynthesized code.
+  if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
+return;
+
   DisplayFunction(D, Mode, IMode);
   CFG *DeclCFG = Mgr->getCFG(D);
   if (DeclCFG) {
 unsigned CFGSize = DeclCFG->size();
 MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize;
   }
 
-  // Clear the AnalysisManager of old AnalysisDeclContexts.
-  Mgr->ClearContexts();
   BugReporter BR(*Mgr);
 
   if (Mode & AM_Syntax)
Index: lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
+++ lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
@@ -3863,7 +3863,7 @@
   // Don't process anything within synthesized bodies.
   const LocationContext *LCtx = Pred->getLocationContext();
   if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
-assert(LCt

Re: [PATCH] D24792: [analyzer] Fix crash in RetainCountChecker::checkEndFunction

2016-09-23 Thread Alexander Shaposhnikov via cfe-commits
alexshap added a comment.

Thanks, Chris has recently granted me commit access, i will rebase, rerun all 
the tests and then commit.


Repository:
  rL LLVM

https://reviews.llvm.org/D24792



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


r282293 - [analyzer] Fix crash in RetainCountChecker::checkEndFunction

2016-09-23 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Fri Sep 23 15:49:01 2016
New Revision: 282293

URL: http://llvm.org/viewvc/llvm-project?rev=282293&view=rev
Log:
[analyzer] Fix crash in RetainCountChecker::checkEndFunction

The class BodyFarm creates bodies for
OSAtomicCompareAndSwap*, objc_atomicCompareAndSwap*, dispatch_sync*, 
dispatch_once*
and for them the flag isBodyAutosynthesized is set to true.

This diff
1. makes AnalysisConsumer::HandleCode skip the autosynthesized code
2. replaces assert(LCtx->getParent()) in RetainCountChecker::checkEndFunction
by assert(!LCtx->inTopFrame()) (minor cleanup)

Test plan: make -j8 check-clang-analysis

Differential revision: https://reviews.llvm.org/D24792

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
cfe/trunk/test/Analysis/NSString.m

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp?rev=282293&r1=282292&r2=282293&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp Fri Sep 23 
15:49:01 2016
@@ -3863,7 +3863,7 @@ void RetainCountChecker::checkEndFunctio
   // Don't process anything within synthesized bodies.
   const LocationContext *LCtx = Pred->getLocationContext();
   if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
-assert(LCtx->getParent());
+assert(!LCtx->inTopFrame()); 
 return;
   }
 

Modified: cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp?rev=282293&r1=282292&r2=282293&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp Fri Sep 23 
15:49:01 2016
@@ -652,6 +652,12 @@ void AnalysisConsumer::HandleCode(Decl *
   if (Mode == AM_None)
 return;
 
+  // Clear the AnalysisManager of old AnalysisDeclContexts.
+  Mgr->ClearContexts();
+  // Ignore autosynthesized code.
+  if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
+return;
+
   DisplayFunction(D, Mode, IMode);
   CFG *DeclCFG = Mgr->getCFG(D);
   if (DeclCFG) {
@@ -659,8 +665,6 @@ void AnalysisConsumer::HandleCode(Decl *
 MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize;
   }
 
-  // Clear the AnalysisManager of old AnalysisDeclContexts.
-  Mgr->ClearContexts();
   BugReporter BR(*Mgr);
 
   if (Mode & AM_Syntax)

Modified: cfe/trunk/test/Analysis/NSString.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/NSString.m?rev=282293&r1=282292&r2=282293&view=diff
==
--- cfe/trunk/test/Analysis/NSString.m (original)
+++ cfe/trunk/test/Analysis/NSString.m Fri Sep 23 15:49:01 2016
@@ -289,7 +289,11 @@ _Bool opaque_OSAtomicCompareAndSwapPtr(
 _Bool OSAtomicCompareAndSwapPtr( void *__oldValue, void *__newValue, void * 
volatile *__theValue ) {
   return opaque_OSAtomicCompareAndSwapPtr(__oldValue, __newValue, __theValue);
 }
-
+// Test that the analyzer doesn't crash when the farm model is used. 
+// The analyzer ignores the autosynthesized code.
+_Bool OSAtomicCompareAndSwapEmptyFunction( void *__oldValue, void *__newValue, 
void * volatile *__theValue ) {
+  return 0;
+}
 extern BOOL opaque_objc_atomicCompareAndSwapPtr(id predicate, id replacement, 
volatile id *objectLocation);
 extern BOOL objc_atomicCompareAndSwapPtr(id predicate, id replacement, 
volatile id *objectLocation) {
   return opaque_objc_atomicCompareAndSwapPtr(predicate, replacement, 
objectLocation);
@@ -441,4 +445,4 @@ void testOSCompareAndSwapXXBarrier_param
 - (void)callValue {
   [self _value];
 }
-@end
\ No newline at end of file
+@end


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


Re: [PATCH] D24792: [analyzer] Fix crash in RetainCountChecker::checkEndFunction

2016-09-23 Thread Alexander Shaposhnikov via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL282293: [analyzer] Fix crash in 
RetainCountChecker::checkEndFunction (authored by alexshap).

Changed prior to commit:
  https://reviews.llvm.org/D24792?vs=72206&id=72354#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D24792

Files:
  cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
  cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
  cfe/trunk/test/Analysis/NSString.m

Index: cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
@@ -652,15 +652,19 @@
   if (Mode == AM_None)
 return;
 
+  // Clear the AnalysisManager of old AnalysisDeclContexts.
+  Mgr->ClearContexts();
+  // Ignore autosynthesized code.
+  if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
+return;
+
   DisplayFunction(D, Mode, IMode);
   CFG *DeclCFG = Mgr->getCFG(D);
   if (DeclCFG) {
 unsigned CFGSize = DeclCFG->size();
 MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize;
   }
 
-  // Clear the AnalysisManager of old AnalysisDeclContexts.
-  Mgr->ClearContexts();
   BugReporter BR(*Mgr);
 
   if (Mode & AM_Syntax)
Index: cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
@@ -3863,7 +3863,7 @@
   // Don't process anything within synthesized bodies.
   const LocationContext *LCtx = Pred->getLocationContext();
   if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
-assert(LCtx->getParent());
+assert(!LCtx->inTopFrame()); 
 return;
   }
 
Index: cfe/trunk/test/Analysis/NSString.m
===
--- cfe/trunk/test/Analysis/NSString.m
+++ cfe/trunk/test/Analysis/NSString.m
@@ -289,7 +289,11 @@
 _Bool OSAtomicCompareAndSwapPtr( void *__oldValue, void *__newValue, void * 
volatile *__theValue ) {
   return opaque_OSAtomicCompareAndSwapPtr(__oldValue, __newValue, __theValue);
 }
-
+// Test that the analyzer doesn't crash when the farm model is used. 
+// The analyzer ignores the autosynthesized code.
+_Bool OSAtomicCompareAndSwapEmptyFunction( void *__oldValue, void *__newValue, 
void * volatile *__theValue ) {
+  return 0;
+}
 extern BOOL opaque_objc_atomicCompareAndSwapPtr(id predicate, id replacement, 
volatile id *objectLocation);
 extern BOOL objc_atomicCompareAndSwapPtr(id predicate, id replacement, 
volatile id *objectLocation) {
   return opaque_objc_atomicCompareAndSwapPtr(predicate, replacement, 
objectLocation);
@@ -441,4 +445,4 @@
 - (void)callValue {
   [self _value];
 }
-@end
\ No newline at end of file
+@end


Index: cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
@@ -652,15 +652,19 @@
   if (Mode == AM_None)
 return;
 
+  // Clear the AnalysisManager of old AnalysisDeclContexts.
+  Mgr->ClearContexts();
+  // Ignore autosynthesized code.
+  if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
+return;
+
   DisplayFunction(D, Mode, IMode);
   CFG *DeclCFG = Mgr->getCFG(D);
   if (DeclCFG) {
 unsigned CFGSize = DeclCFG->size();
 MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize;
   }
 
-  // Clear the AnalysisManager of old AnalysisDeclContexts.
-  Mgr->ClearContexts();
   BugReporter BR(*Mgr);
 
   if (Mode & AM_Syntax)
Index: cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
@@ -3863,7 +3863,7 @@
   // Don't process anything within synthesized bodies.
   const LocationContext *LCtx = Pred->getLocationContext();
   if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
-assert(LCtx->getParent());
+assert(!LCtx->inTopFrame()); 
 return;
   }
 
Index: cfe/trunk/test/Analysis/NSString.m
===
--- cfe/trunk/test/Analysis/NSString.m
+++ cfe/trunk/test/Analysis/NSString.m
@@ -289,7 +289,11 @@
 _Bool OSAtomicCompareAndSwapPtr( void *__oldValue, void *__newValue, void * volatile *__theValue ) {
   return opaque_OSAtomicCompareAndSwapPtr(__oldValue, __newValue, __theValue);
 }
-
+// Test that the analyzer doesn't crash when the farm model is used. 
+// The analyzer ignores the autosynthesized code.
+_Bool OSAtomicCompareAndSwapEmptyFunction( void *__oldValue, void *__newValue, void * volatile *__t

r282318 - Remove excessive padding from ObjCCategoriesVisitor

2016-09-23 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Fri Sep 23 21:07:19 2016
New Revision: 282318

URL: http://llvm.org/viewvc/llvm-project?rev=282318&view=rev
Log:
Remove excessive padding from ObjCCategoriesVisitor

This diff reorders the fields of ObjCCategoriesVisitor 
to remove excessive padding. 

Test plan: make -j8 check-clang

Differential revision: https://reviews.llvm.org/D24753

Modified:
cfe/trunk/lib/Serialization/ASTReaderDecl.cpp

Modified: cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Serialization/ASTReaderDecl.cpp?rev=282318&r1=282317&r2=282318&view=diff
==
--- cfe/trunk/lib/Serialization/ASTReaderDecl.cpp (original)
+++ cfe/trunk/lib/Serialization/ASTReaderDecl.cpp Fri Sep 23 21:07:19 2016
@@ -3615,12 +3615,12 @@ namespace {
   /// interface all the categories for it.
   class ObjCCategoriesVisitor {
 ASTReader &Reader;
-serialization::GlobalDeclID InterfaceID;
 ObjCInterfaceDecl *Interface;
 llvm::SmallPtrSetImpl &Deserialized;
-unsigned PreviousGeneration;
 ObjCCategoryDecl *Tail;
 llvm::DenseMap NameCategoryMap;
+serialization::GlobalDeclID InterfaceID;
+unsigned PreviousGeneration;
 
 void add(ObjCCategoryDecl *Cat) {
   // Only process each category once.
@@ -3663,13 +3663,13 @@ namespace {
 
   public:
 ObjCCategoriesVisitor(ASTReader &Reader,
-  serialization::GlobalDeclID InterfaceID,
   ObjCInterfaceDecl *Interface,
-llvm::SmallPtrSetImpl 
&Deserialized,
+  llvm::SmallPtrSetImpl 
&Deserialized,
+  serialization::GlobalDeclID InterfaceID,
   unsigned PreviousGeneration)
-  : Reader(Reader), InterfaceID(InterfaceID), Interface(Interface),
-Deserialized(Deserialized), PreviousGeneration(PreviousGeneration),
-Tail(nullptr)
+  : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
+Tail(nullptr), InterfaceID(InterfaceID),
+PreviousGeneration(PreviousGeneration)
 {
   // Populate the name -> category map with the set of known categories.
   for (auto *Cat : Interface->known_categories()) {
@@ -3724,7 +3724,7 @@ namespace {
 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
ObjCInterfaceDecl *D,
unsigned PreviousGeneration) {
-  ObjCCategoriesVisitor Visitor(*this, ID, D, CategoriesDeserialized,
+  ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
 PreviousGeneration);
   ModuleMgr.visit(Visitor);
 }


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


r282322 - Remove excessive padding from RedeclarableResult

2016-09-23 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Fri Sep 23 23:21:53 2016
New Revision: 282322

URL: http://llvm.org/viewvc/llvm-project?rev=282322&view=rev
Log:
Remove excessive padding from RedeclarableResult

This diff reorders the fields of the class RedeclarableResult 
to remove excessive padding.

Test plan: make -j8 check-clang

Differential revision: https://reviews.llvm.org/D24754

Modified:
cfe/trunk/lib/Serialization/ASTReaderDecl.cpp

Modified: cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Serialization/ASTReaderDecl.cpp?rev=282322&r1=282321&r2=282322&view=diff
==
--- cfe/trunk/lib/Serialization/ASTReaderDecl.cpp (original)
+++ cfe/trunk/lib/Serialization/ASTReaderDecl.cpp Fri Sep 23 23:21:53 2016
@@ -146,13 +146,13 @@ namespace clang {
 
 /// Results from loading a RedeclarableDecl.
 class RedeclarableResult {
-  GlobalDeclID FirstID;
   Decl *MergeWith;
+  GlobalDeclID FirstID;
   bool IsKeyDecl;
 
 public:
-  RedeclarableResult(GlobalDeclID FirstID, Decl *MergeWith, bool IsKeyDecl)
-  : FirstID(FirstID), MergeWith(MergeWith), IsKeyDecl(IsKeyDecl) {}
+  RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
+: MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}
 
   /// \brief Retrieve the first ID.
   GlobalDeclID getFirstID() const { return FirstID; }
@@ -2311,7 +2311,7 @@ ASTDeclReader::VisitRedeclarable(Redecla
   if (IsFirstLocalDecl)
 Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
 
-  return RedeclarableResult(FirstDeclID, MergeWith, IsKeyDecl);
+  return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
 }
 
 /// \brief Attempts to merge the given declaration (D) with another declaration
@@ -2353,9 +2353,10 @@ void ASTDeclReader::mergeTemplatePattern
  DeclID DsID, bool IsKeyDecl) {
   auto *DPattern = D->getTemplatedDecl();
   auto *ExistingPattern = Existing->getTemplatedDecl();
-  RedeclarableResult Result(DPattern->getCanonicalDecl()->getGlobalID(),
-/*MergeWith*/ ExistingPattern, IsKeyDecl);
-
+  RedeclarableResult Result(/*MergeWith*/ ExistingPattern,  
+DPattern->getCanonicalDecl()->getGlobalID(), 
+IsKeyDecl);
+  
   if (auto *DClass = dyn_cast(DPattern)) {
 // Merge with any existing definition.
 // FIXME: This is duplicated in several places. Refactor.


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


Re: [PATCH] D24754: [cleanup] Remove excessive padding from RedeclarableResult

2016-09-23 Thread Alexander Shaposhnikov via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL282322: Remove excessive padding from RedeclarableResult 
(authored by alexshap).

Changed prior to commit:
  https://reviews.llvm.org/D24754?vs=71903&id=72388#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D24754

Files:
  cfe/trunk/lib/Serialization/ASTReaderDecl.cpp

Index: cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
===
--- cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
+++ cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
@@ -146,13 +146,13 @@
 
 /// Results from loading a RedeclarableDecl.
 class RedeclarableResult {
-  GlobalDeclID FirstID;
   Decl *MergeWith;
+  GlobalDeclID FirstID;
   bool IsKeyDecl;
 
 public:
-  RedeclarableResult(GlobalDeclID FirstID, Decl *MergeWith, bool IsKeyDecl)
-  : FirstID(FirstID), MergeWith(MergeWith), IsKeyDecl(IsKeyDecl) {}
+  RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
+: MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}
 
   /// \brief Retrieve the first ID.
   GlobalDeclID getFirstID() const { return FirstID; }
@@ -2311,7 +2311,7 @@
   if (IsFirstLocalDecl)
 Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
 
-  return RedeclarableResult(FirstDeclID, MergeWith, IsKeyDecl);
+  return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
 }
 
 /// \brief Attempts to merge the given declaration (D) with another declaration
@@ -2353,9 +2353,10 @@
  DeclID DsID, bool IsKeyDecl) {
   auto *DPattern = D->getTemplatedDecl();
   auto *ExistingPattern = Existing->getTemplatedDecl();
-  RedeclarableResult Result(DPattern->getCanonicalDecl()->getGlobalID(),
-/*MergeWith*/ ExistingPattern, IsKeyDecl);
-
+  RedeclarableResult Result(/*MergeWith*/ ExistingPattern,  
+DPattern->getCanonicalDecl()->getGlobalID(), 
+IsKeyDecl);
+  
   if (auto *DClass = dyn_cast(DPattern)) {
 // Merge with any existing definition.
 // FIXME: This is duplicated in several places. Refactor.


Index: cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
===
--- cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
+++ cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
@@ -146,13 +146,13 @@
 
 /// Results from loading a RedeclarableDecl.
 class RedeclarableResult {
-  GlobalDeclID FirstID;
   Decl *MergeWith;
+  GlobalDeclID FirstID;
   bool IsKeyDecl;
 
 public:
-  RedeclarableResult(GlobalDeclID FirstID, Decl *MergeWith, bool IsKeyDecl)
-  : FirstID(FirstID), MergeWith(MergeWith), IsKeyDecl(IsKeyDecl) {}
+  RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
+: MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}
 
   /// \brief Retrieve the first ID.
   GlobalDeclID getFirstID() const { return FirstID; }
@@ -2311,7 +2311,7 @@
   if (IsFirstLocalDecl)
 Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
 
-  return RedeclarableResult(FirstDeclID, MergeWith, IsKeyDecl);
+  return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
 }
 
 /// \brief Attempts to merge the given declaration (D) with another declaration
@@ -2353,9 +2353,10 @@
  DeclID DsID, bool IsKeyDecl) {
   auto *DPattern = D->getTemplatedDecl();
   auto *ExistingPattern = Existing->getTemplatedDecl();
-  RedeclarableResult Result(DPattern->getCanonicalDecl()->getGlobalID(),
-/*MergeWith*/ ExistingPattern, IsKeyDecl);
-
+  RedeclarableResult Result(/*MergeWith*/ ExistingPattern,  
+DPattern->getCanonicalDecl()->getGlobalID(), 
+IsKeyDecl);
+  
   if (auto *DClass = dyn_cast(DPattern)) {
 // Merge with any existing definition.
 // FIXME: This is duplicated in several places. Refactor.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D24914: [clang-rename] Do not print out error message upon encountering multiple replacements in the same SourceLocation.

2016-09-27 Thread Alexander Shaposhnikov via cfe-commits
alexshap added a subscriber: alexshap.


Comment at: clang-rename/RenamingAction.cpp:74
@@ +73,3 @@
+  // FIXME: As for clang-rename, adding a replacement fails IFF either the
+  // AST node has been matched multiple times (which shouldn't happen in
+  // reality, need to fix that). For now, just ignore the error as it

Let's consider the following example:
src/include/Point.h:
   struct Point {};
src/a.cpp: 
   include 
src/b.cpp:
   include 
clang-rename -qualified-name Point -new-name Point2 srcs/a.cpp srcs/b.cpp
Renaming failed in /Users/Alexshap/PlayRename/srcs/./include/Point.h! New 
replacement:
/Users/Alexshap/PlayRename/srcs/./include/Point.h: 7:+5:"Point2"
conflicts with existing replacement:
/Users/Alexshap/PlayRename/srcs/./include/Point.h: 7:+5:"Point2"

The thing is that clang-rename is trying to modify the same code twice (as in 
the example) and the return value (Error) of the method Replacements::add 
doesn't allow us to distinguish two cases: A. conflict (trying to apply 
different modifications to the same source code) B. (still conflict, but 
different) (trying to apply the same modification twice). 
In the past when Replacements was a typedef on std::set and clang-rename was 
using insert(...) the case B wasn't an issue. 
P.S. However (imo) the new (FIXME) comment seems to be a little bit misleading.


https://reviews.llvm.org/D24914



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


Re: [PATCH] D24914: [clang-rename] Do not print out error message upon encountering multiple replacements in the same SourceLocation.

2016-09-27 Thread Alexander Shaposhnikov via cfe-commits
alexshap added inline comments.


Comment at: clang-rename/RenamingAction.cpp:74
@@ +73,3 @@
+  // FIXME: As for clang-rename, adding a replacement fails IFF either the
+  // AST node has been matched multiple times (which shouldn't happen in
+  // reality, need to fix that). For now, just ignore the error as it

omtcyfz wrote:
> alexshap wrote:
> > Let's consider the following example:
> > src/include/Point.h:
> >struct Point {};
> > src/a.cpp: 
> >include 
> > src/b.cpp:
> >include 
> > clang-rename -qualified-name Point -new-name Point2 srcs/a.cpp srcs/b.cpp
> > Renaming failed in /Users/Alexshap/PlayRename/srcs/./include/Point.h! New 
> > replacement:
> > /Users/Alexshap/PlayRename/srcs/./include/Point.h: 7:+5:"Point2"
> > conflicts with existing replacement:
> > /Users/Alexshap/PlayRename/srcs/./include/Point.h: 7:+5:"Point2"
> > 
> > The thing is that clang-rename is trying to modify the same code twice (as 
> > in the example) and the return value (Error) of the method 
> > Replacements::add doesn't allow us to distinguish two cases: A. conflict 
> > (trying to apply different modifications to the same source code) B. (still 
> > conflict, but different) (trying to apply the same modification twice). 
> > In the past when Replacements was a typedef on std::set and clang-rename 
> > was using insert(...) the case B wasn't an issue. 
> > P.S. However (imo) the new (FIXME) comment seems to be a little bit 
> > misleading.
> But the thing is that it's never the A. case. Unlike other refactorings, 
> clang-rename doesn't introduce any name conflicts, it will only sometimes try 
> to rename something multiple times.
Yup


https://reviews.llvm.org/D24914



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


Re: [PATCH] D24914: [clang-rename] Do not print out error message upon encountering multiple replacements in the same SourceLocation.

2016-09-27 Thread Alexander Shaposhnikov via cfe-commits
alexshap added inline comments.


Comment at: clang-rename/RenamingAction.cpp:74
@@ +73,3 @@
+  // FIXME: An error might happen here if USRLocFinder finds the symbol
+  // twice or if the symbol happens to be in a header included multiple
+  // times independently. Such error doesn't mean clang-rename failure and

My concerns were about wording, the new version looks good to me.
I think the long-term fix would be to improve the interface of the class 
Replacements,
but it's clearly not in the scope of this patch (the other tools have the same 
issue), 
so to me your diff is OK.


https://reviews.llvm.org/D24914



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


Re: [PATCH] D24800: Merge conflicting replacements when they are order-independent.

2016-09-28 Thread Alexander Shaposhnikov via cfe-commits
alexshap added a subscriber: alexshap.


Comment at: cfe/trunk/lib/Tooling/Core/Replacement.cpp:182
@@ +181,3 @@
+llvm::Expected
+Replacements::mergeIfOrderIndependent(const Replacement &R) const {
+  Replacements Rs(R);

sorry, probably i am late to the party,
however i'd like to ask how this method is supposed to be used by the customers 
of this code.
If i'm not mistaken we have some  concrete examples in clang-extra-tools: for 
instance @omtcyfz  referred  to this diff on https://reviews.llvm.org/D24914. 
Basically after this diff the class Replacements contains several methods (add, 
mergeIfOrderIndependent etc), but mergeIfOrderIndependent potentially will copy 
a lot of replacements (i don't know if the perf is a real issue here, but at 
least it looks a bit strange to me).
Another question - how are the customers of this code supposed to use the 
method add ? still suppress the error (like what was happening on 
https://reviews.llvm.org/D24914) ?
Am i missing smth ?
cc: @klimek, @djasper.



Repository:
  rL LLVM

https://reviews.llvm.org/D24800



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


Re: [PATCH] D24800: Merge conflicting replacements when they are order-independent.

2016-09-28 Thread Alexander Shaposhnikov via cfe-commits
alexshap added inline comments.


Comment at: cfe/trunk/lib/Tooling/Core/Replacement.cpp:182
@@ +181,3 @@
+llvm::Expected
+Replacements::mergeIfOrderIndependent(const Replacement &R) const {
+  Replacements Rs(R);

ioeric wrote:
> alexshap wrote:
> > sorry, probably i am late to the party,
> > however i'd like to ask how this method is supposed to be used by the 
> > customers of this code.
> > If i'm not mistaken we have some  concrete examples in clang-extra-tools: 
> > for instance @omtcyfz  referred  to this diff on 
> > https://reviews.llvm.org/D24914. 
> > Basically after this diff the class Replacements contains several methods 
> > (add, mergeIfOrderIndependent etc), but mergeIfOrderIndependent potentially 
> > will copy a lot of replacements (i don't know if the perf is a real issue 
> > here, but at least it looks a bit strange to me).
> > Another question - how are the customers of this code supposed to use the 
> > method add ? still suppress the error (like what was happening on 
> > https://reviews.llvm.org/D24914) ?
> > Am i missing smth ?
> > cc: @klimek, @djasper.
> > 
> First of all, this diff doesn't introduce new interfaces - they are just 
> private helper functions, which are mostly called on conflicting replacements 
> set with relatively small size.
> 
> Secondly, `add` now supports merging order-independent replacements, so it 
> handles deduplication to some extend, i.e. identical non-insertion 
> replacements can be deduplicated, which happens to solve the issue with 
> clang-rename as mentioned in D24914.
> 
i see,  thank you for the explanation.


Repository:
  rL LLVM

https://reviews.llvm.org/D24800



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


[PATCH] D25049: Add missing std::move in Replacements::add

2016-09-28 Thread Alexander Shaposhnikov via cfe-commits
alexshap created this revision.
alexshap added reviewers: djasper, klimek, ioeric.
alexshap added a subscriber: cfe-commits.
alexshap set the repository for this revision to rL LLVM.
alexshap changed the visibility of this Differential Revision from "Public (No 
Login Required)" to "All Users".
Herald added a subscriber: klimek.

This diff adds std::move to avoid copying of the Replacement NewR in the method 
Replacements::add.

The class Replacement has a move constructor:
clang-query> set output print
clang-query> match cxxConstructorDecl(ofClass(hasName("Replacement")), 
isMoveConstructor(), isDefinition()).bind("id")
Match #1:
Binding for "id":
inline Replacement(clang::tooling::Replacement &&) noexcept : 
FilePath(static_cast().FilePath), 
ReplacementRange(static_cast().ReplacementRange), 
ReplacementText(static_cast().ReplacementText) {
} 

Test plan: make -j8 check-all

Repository:
  rL LLVM

https://reviews.llvm.org/D25049

Files:
  lib/Tooling/Core/Replacement.cpp

Index: lib/Tooling/Core/Replacement.cpp
===
--- lib/Tooling/Core/Replacement.cpp
+++ lib/Tooling/Core/Replacement.cpp
@@ -245,7 +245,7 @@
   R.getFilePath(), R.getOffset(), 0,
   (R.getReplacementText() + I->getReplacementText()).str());
   Replaces.erase(I);
-  Replaces.insert(NewR);
+  Replaces.insert(std::move(NewR));
   return llvm::Error::success();
 }
 // Insertion `R` is adjacent to a non-insertion replacement `I`, so they


Index: lib/Tooling/Core/Replacement.cpp
===
--- lib/Tooling/Core/Replacement.cpp
+++ lib/Tooling/Core/Replacement.cpp
@@ -245,7 +245,7 @@
   R.getFilePath(), R.getOffset(), 0,
   (R.getReplacementText() + I->getReplacementText()).str());
   Replaces.erase(I);
-  Replaces.insert(NewR);
+  Replaces.insert(std::move(NewR));
   return llvm::Error::success();
 }
 // Insertion `R` is adjacent to a non-insertion replacement `I`, so they
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] [Changed Subscribers] D25074: [clang-tidy] Improve rename_check.py

2016-09-30 Thread Alexander Shaposhnikov via cfe-commits
alexshap added inline comments.


> rename_check.py:81
> +args = parser.parse_args()
> +print(args)
> +

the script always prints the args, is it intentional ?

https://reviews.llvm.org/D25074



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


r282949 - Add missing std::move in Replacements::add

2016-09-30 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Fri Sep 30 16:05:45 2016
New Revision: 282949

URL: http://llvm.org/viewvc/llvm-project?rev=282949&view=rev
Log:
Add missing std::move in Replacements::add

This diff adds std::move to avoid copying of 
the Replacement NewR in the method Replacements::add.

Test plan: make -j8 check-all

Differential revision: https://reviews.llvm.org/D25049

Modified:
cfe/trunk/lib/Tooling/Core/Replacement.cpp

Modified: cfe/trunk/lib/Tooling/Core/Replacement.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/Core/Replacement.cpp?rev=282949&r1=282948&r2=282949&view=diff
==
--- cfe/trunk/lib/Tooling/Core/Replacement.cpp (original)
+++ cfe/trunk/lib/Tooling/Core/Replacement.cpp Fri Sep 30 16:05:45 2016
@@ -245,7 +245,7 @@ llvm::Error Replacements::add(const Repl
   R.getFilePath(), R.getOffset(), 0,
   (R.getReplacementText() + I->getReplacementText()).str());
   Replaces.erase(I);
-  Replaces.insert(NewR);
+  Replaces.insert(std::move(NewR));
   return llvm::Error::success();
 }
 // Insertion `R` is adjacent to a non-insertion replacement `I`, so they


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


[PATCH] D25049: Add missing std::move in Replacements::add

2016-09-30 Thread Alexander Shaposhnikov via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL282949: Add missing std::move in Replacements::add (authored 
by alexshap).

Changed prior to commit:
  https://reviews.llvm.org/D25049?vs=72902&id=73140#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D25049

Files:
  cfe/trunk/lib/Tooling/Core/Replacement.cpp


Index: cfe/trunk/lib/Tooling/Core/Replacement.cpp
===
--- cfe/trunk/lib/Tooling/Core/Replacement.cpp
+++ cfe/trunk/lib/Tooling/Core/Replacement.cpp
@@ -245,7 +245,7 @@
   R.getFilePath(), R.getOffset(), 0,
   (R.getReplacementText() + I->getReplacementText()).str());
   Replaces.erase(I);
-  Replaces.insert(NewR);
+  Replaces.insert(std::move(NewR));
   return llvm::Error::success();
 }
 // Insertion `R` is adjacent to a non-insertion replacement `I`, so they


Index: cfe/trunk/lib/Tooling/Core/Replacement.cpp
===
--- cfe/trunk/lib/Tooling/Core/Replacement.cpp
+++ cfe/trunk/lib/Tooling/Core/Replacement.cpp
@@ -245,7 +245,7 @@
   R.getFilePath(), R.getOffset(), 0,
   (R.getReplacementText() + I->getReplacementText()).str());
   Replaces.erase(I);
-  Replaces.insert(NewR);
+  Replaces.insert(std::move(NewR));
   return llvm::Error::success();
 }
 // Insertion `R` is adjacent to a non-insertion replacement `I`, so they
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D25503: [analyzer] Remove superquadratic behaviour from DataflowWorklist

2016-10-12 Thread Alexander Shaposhnikov via cfe-commits
alexshap created this revision.
alexshap added reviewers: NoQ, zaks.anna.
alexshap added a subscriber: cfe-commits.
alexshap set the repository for this revision to rL LLVM.

The class DataflowWorklist internally maintains a sorted list of pointers to 
CFGBlock and
the method enqueuePredecessors has to call sortWorklist to maintain the 
invariant.
The implementation based on vector + sort works well for small sizes but gets 
infeasible
for relatively large sizes. In particular the issue takes place for some 
cryptographic libraries which use code generation.
This diff replaces vector + sort with set.
The slowdown for small sizes (measured on the current tests) is negligeable (I 
was looking at the reported "Testing Time" for check-clang-analysis and the 
difference was less then 0.01s (the total time is 3.93s)).


Repository:
  rL LLVM

https://reviews.llvm.org/D25503

Files:
  lib/Analysis/LiveVariables.cpp


Index: lib/Analysis/LiveVariables.cpp
===
--- lib/Analysis/LiveVariables.cpp
+++ lib/Analysis/LiveVariables.cpp
@@ -21,59 +21,51 @@
 #include "llvm/ADT/PostOrderIterator.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
+#include 
 #include 
 
 using namespace clang;
 
 namespace {
 
 class DataflowWorklist {
-  SmallVector worklist;
   llvm::BitVector enqueuedBlocks;
   PostOrderCFGView *POV;
+  std::multiset 
worklist;
 public:
   DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx)
 : enqueuedBlocks(cfg.getNumBlockIDs()),
-  POV(Ctx.getAnalysis()) {}
+  POV(Ctx.getAnalysis()),
+  worklist(POV->getComparator()) {}
   
   void enqueueBlock(const CFGBlock *block);
   void enqueuePredecessors(const CFGBlock *block);
 
   const CFGBlock *dequeue();
-
-  void sortWorklist();
 };
 
 }
 
 void DataflowWorklist::enqueueBlock(const clang::CFGBlock *block) {
   if (block && !enqueuedBlocks[block->getBlockID()]) {
 enqueuedBlocks[block->getBlockID()] = true;
-worklist.push_back(block);
+worklist.insert(block);
   }
 }
 
 void DataflowWorklist::enqueuePredecessors(const clang::CFGBlock *block) {
-  const unsigned OldWorklistSize = worklist.size();
   for (CFGBlock::const_pred_iterator I = block->pred_begin(),
E = block->pred_end(); I != E; ++I) {
 enqueueBlock(*I);
   }
-  
-  if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
-return;
-
-  sortWorklist();
-}
-
-void DataflowWorklist::sortWorklist() {
-  std::sort(worklist.begin(), worklist.end(), POV->getComparator());
 }
 
 const CFGBlock *DataflowWorklist::dequeue() {
   if (worklist.empty())
 return nullptr;
-  const CFGBlock *b = worklist.pop_back_val();
+  const auto I = --worklist.end();
+  const CFGBlock *b = *I;
+  worklist.erase(I);
   enqueuedBlocks[b->getBlockID()] = false;
   return b;
 }
@@ -528,8 +520,6 @@
   }
   }
   
-  worklist.sortWorklist();
-  
   while (const CFGBlock *block = worklist.dequeue()) {
 // Determine if the block's end value has changed.  If not, we
 // have nothing left to do for this block.


Index: lib/Analysis/LiveVariables.cpp
===
--- lib/Analysis/LiveVariables.cpp
+++ lib/Analysis/LiveVariables.cpp
@@ -21,59 +21,51 @@
 #include "llvm/ADT/PostOrderIterator.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
+#include 
 #include 
 
 using namespace clang;
 
 namespace {
 
 class DataflowWorklist {
-  SmallVector worklist;
   llvm::BitVector enqueuedBlocks;
   PostOrderCFGView *POV;
+  std::multiset worklist;
 public:
   DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx)
 : enqueuedBlocks(cfg.getNumBlockIDs()),
-  POV(Ctx.getAnalysis()) {}
+  POV(Ctx.getAnalysis()),
+  worklist(POV->getComparator()) {}
   
   void enqueueBlock(const CFGBlock *block);
   void enqueuePredecessors(const CFGBlock *block);
 
   const CFGBlock *dequeue();
-
-  void sortWorklist();
 };
 
 }
 
 void DataflowWorklist::enqueueBlock(const clang::CFGBlock *block) {
   if (block && !enqueuedBlocks[block->getBlockID()]) {
 enqueuedBlocks[block->getBlockID()] = true;
-worklist.push_back(block);
+worklist.insert(block);
   }
 }
 
 void DataflowWorklist::enqueuePredecessors(const clang::CFGBlock *block) {
-  const unsigned OldWorklistSize = worklist.size();
   for (CFGBlock::const_pred_iterator I = block->pred_begin(),
E = block->pred_end(); I != E; ++I) {
 enqueueBlock(*I);
   }
-  
-  if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
-return;
-
-  sortWorklist();
-}
-
-void DataflowWorklist::sortWorklist() {
-  std::sort(worklist.begin(), worklist.end(), POV->getComparator());
 }
 
 const CFGBlock *DataflowWorklist::dequeue() {
   if (worklist.empty())
 return nullptr;
-  const CFGBlock *b = worklist.pop_back_val();
+  const auto I = --worklist.end();
+  const CFGBlock *b = *I;
+  worklist.erase(I);
   enqueuedBlocks[b->getBlockID()] = false;
   return b;
 }
@@ -528,8 +520,6 @@

[PATCH] D25503: [analyzer] Remove superquadratic behaviour from DataflowWorklist

2016-10-12 Thread Alexander Shaposhnikov via cfe-commits
alexshap added inline comments.



Comment at: lib/Analysis/LiveVariables.cpp:66
 return nullptr;
-  const CFGBlock *b = worklist.pop_back_val();
+  const auto I = --worklist.end();
+  const CFGBlock *b = *I;

zaks.anna wrote:
> '--wroklist.end()' -> 'worklist.rbegin()'?
1. rbegin - OK - will update the diff
2. regarding http://llvm.org/docs/doxygen/html/classllvm_1_1SparseSet.html and 
http://llvm.org/docs/ProgrammersManual.html#set-like-containers-std-set-smallset-setvector-etc
(i took a look at it before) - the problem is that i don't see any containers 
which take a custom comparator & provide "ordered set"-like functionality there.
3. regarding the performance - i can run static analyzer against LLVM and 
measure the time (compare the old version with this one). Will post the results 
here.  


Repository:
  rL LLVM

https://reviews.llvm.org/D25503



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


[PATCH] D25503: [analyzer] Remove superquadratic behaviour from DataflowWorklist

2016-10-12 Thread Alexander Shaposhnikov via cfe-commits
alexshap added inline comments.



Comment at: lib/Analysis/LiveVariables.cpp:66
 return nullptr;
-  const CFGBlock *b = worklist.pop_back_val();
+  const auto I = --worklist.end();
+  const CFGBlock *b = *I;

alexshap wrote:
> zaks.anna wrote:
> > '--wroklist.end()' -> 'worklist.rbegin()'?
> 1. rbegin - OK - will update the diff
> 2. regarding http://llvm.org/docs/doxygen/html/classllvm_1_1SparseSet.html 
> and 
> http://llvm.org/docs/ProgrammersManual.html#set-like-containers-std-set-smallset-setvector-etc
> (i took a look at it before) - the problem is that i don't see any containers 
> which take a custom comparator & provide "ordered set"-like functionality 
> there.
> 3. regarding the performance - i can run static analyzer against LLVM and 
> measure the time (compare the old version with this one). Will post the 
> results here.  
4. Will test the approach suggested by @NoQ as well.


Repository:
  rL LLVM

https://reviews.llvm.org/D25503



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


[PATCH] D25503: [analyzer] Remove superquadratic behaviour from DataflowWorklist

2016-10-12 Thread Alexander Shaposhnikov via cfe-commits
alexshap added inline comments.



Comment at: lib/Analysis/LiveVariables.cpp:66
 return nullptr;
-  const CFGBlock *b = worklist.pop_back_val();
+  const auto I = --worklist.end();
+  const CFGBlock *b = *I;

alexshap wrote:
> alexshap wrote:
> > zaks.anna wrote:
> > > '--wroklist.end()' -> 'worklist.rbegin()'?
> > 1. rbegin - OK - will update the diff
> > 2. regarding http://llvm.org/docs/doxygen/html/classllvm_1_1SparseSet.html 
> > and 
> > http://llvm.org/docs/ProgrammersManual.html#set-like-containers-std-set-smallset-setvector-etc
> > (i took a look at it before) - the problem is that i don't see any 
> > containers which take a custom comparator & provide "ordered set"-like 
> > functionality there.
> > 3. regarding the performance - i can run static analyzer against LLVM and 
> > measure the time (compare the old version with this one). Will post the 
> > results here.  
> 4. Will test the approach suggested by @NoQ as well.
actually it looks like llvm::PriorityQueue might work here - will check.


Repository:
  rL LLVM

https://reviews.llvm.org/D25503



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


[PATCH] D25503: [analyzer] Remove superquadratic behaviour from DataflowWorklist

2016-10-12 Thread Alexander Shaposhnikov via cfe-commits
alexshap updated the summary for this revision.
alexshap updated this revision to Diff 74437.
alexshap added a comment.

Switch to priority queue.
I have rerun the tests - they are all green.
I will post the numbers about the perf a bit later.


Repository:
  rL LLVM

https://reviews.llvm.org/D25503

Files:
  lib/Analysis/LiveVariables.cpp


Index: lib/Analysis/LiveVariables.cpp
===
--- lib/Analysis/LiveVariables.cpp
+++ lib/Analysis/LiveVariables.cpp
@@ -19,6 +19,7 @@
 #include "clang/Analysis/CFG.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/PostOrderIterator.h"
+#include "llvm/ADT/PriorityQueue.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -28,52 +29,44 @@
 namespace {
 
 class DataflowWorklist {
-  SmallVector worklist;
   llvm::BitVector enqueuedBlocks;
   PostOrderCFGView *POV;
+  llvm::PriorityQueue,
+  PostOrderCFGView::BlockOrderCompare> worklist;
+
 public:
   DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx)
 : enqueuedBlocks(cfg.getNumBlockIDs()),
-  POV(Ctx.getAnalysis()) {}
+  POV(Ctx.getAnalysis()),
+  worklist(POV->getComparator()) {}
   
   void enqueueBlock(const CFGBlock *block);
   void enqueuePredecessors(const CFGBlock *block);
 
   const CFGBlock *dequeue();
-
-  void sortWorklist();
 };
 
 }
 
 void DataflowWorklist::enqueueBlock(const clang::CFGBlock *block) {
   if (block && !enqueuedBlocks[block->getBlockID()]) {
 enqueuedBlocks[block->getBlockID()] = true;
-worklist.push_back(block);
+worklist.push(block);
   }
 }
 
 void DataflowWorklist::enqueuePredecessors(const clang::CFGBlock *block) {
-  const unsigned OldWorklistSize = worklist.size();
   for (CFGBlock::const_pred_iterator I = block->pred_begin(),
E = block->pred_end(); I != E; ++I) {
 enqueueBlock(*I);
   }
-  
-  if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
-return;
-
-  sortWorklist();
-}
-
-void DataflowWorklist::sortWorklist() {
-  std::sort(worklist.begin(), worklist.end(), POV->getComparator());
 }
 
 const CFGBlock *DataflowWorklist::dequeue() {
   if (worklist.empty())
 return nullptr;
-  const CFGBlock *b = worklist.pop_back_val();
+  const CFGBlock *b = worklist.top();
+  worklist.pop();
   enqueuedBlocks[b->getBlockID()] = false;
   return b;
 }
@@ -528,8 +521,6 @@
   }
   }
   
-  worklist.sortWorklist();
-  
   while (const CFGBlock *block = worklist.dequeue()) {
 // Determine if the block's end value has changed.  If not, we
 // have nothing left to do for this block.


Index: lib/Analysis/LiveVariables.cpp
===
--- lib/Analysis/LiveVariables.cpp
+++ lib/Analysis/LiveVariables.cpp
@@ -19,6 +19,7 @@
 #include "clang/Analysis/CFG.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/PostOrderIterator.h"
+#include "llvm/ADT/PriorityQueue.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -28,52 +29,44 @@
 namespace {
 
 class DataflowWorklist {
-  SmallVector worklist;
   llvm::BitVector enqueuedBlocks;
   PostOrderCFGView *POV;
+  llvm::PriorityQueue,
+  PostOrderCFGView::BlockOrderCompare> worklist;
+
 public:
   DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx)
 : enqueuedBlocks(cfg.getNumBlockIDs()),
-  POV(Ctx.getAnalysis()) {}
+  POV(Ctx.getAnalysis()),
+  worklist(POV->getComparator()) {}
   
   void enqueueBlock(const CFGBlock *block);
   void enqueuePredecessors(const CFGBlock *block);
 
   const CFGBlock *dequeue();
-
-  void sortWorklist();
 };
 
 }
 
 void DataflowWorklist::enqueueBlock(const clang::CFGBlock *block) {
   if (block && !enqueuedBlocks[block->getBlockID()]) {
 enqueuedBlocks[block->getBlockID()] = true;
-worklist.push_back(block);
+worklist.push(block);
   }
 }
 
 void DataflowWorklist::enqueuePredecessors(const clang::CFGBlock *block) {
-  const unsigned OldWorklistSize = worklist.size();
   for (CFGBlock::const_pred_iterator I = block->pred_begin(),
E = block->pred_end(); I != E; ++I) {
 enqueueBlock(*I);
   }
-  
-  if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
-return;
-
-  sortWorklist();
-}
-
-void DataflowWorklist::sortWorklist() {
-  std::sort(worklist.begin(), worklist.end(), POV->getComparator());
 }
 
 const CFGBlock *DataflowWorklist::dequeue() {
   if (worklist.empty())
 return nullptr;
-  const CFGBlock *b = worklist.pop_back_val();
+  const CFGBlock *b = worklist.top();
+  worklist.pop();
   enqueuedBlocks[b->getBlockID()] = false;
   return b;
 }
@@ -528,8 +521,6 @@
   }
   }
   
-  worklist.sortWorklist();
-  
   while (const CFGBlock *block = worklist.dequeue()) {
 // Determine if the block's end value has changed.  If not, we
 // have nothing left to do for this block.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm

[PATCH] D25503: [analyzer] Remove superquadratic behaviour from DataflowWorklist

2016-10-12 Thread Alexander Shaposhnikov via cfe-commits
alexshap added a comment.

I've just run scan-build against LLVM & clang & clang-extra-tools - the new 
version (with PriorityQueue) is a bit faster - i was running the build on OSX & 
-j8 and the total time for the new version is 88 minutes vs 92 minutes for the 
old one. Certainly i think that this measurement is not 100% proof but i don't 
see any regressions.


Repository:
  rL LLVM

https://reviews.llvm.org/D25503



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


r284166 - [analyzer] Remove superquadratic behaviour from DataflowWorklist

2016-10-13 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Thu Oct 13 16:31:46 2016
New Revision: 284166

URL: http://llvm.org/viewvc/llvm-project?rev=284166&view=rev
Log:
[analyzer] Remove superquadratic behaviour from DataflowWorklist

The class DataflowWorklist internally maintains a sorted list of pointers to 
CFGBlock
and the method enqueuePredecessors has to call sortWorklist to maintain the 
invariant. 
The implementation based on vector + sort works well for small sizes 
but gets infeasible for relatively large sizes. In particular the issue takes 
place 
for some cryptographic libraries which use code generation. 
The diff replaces vector + sort with priority queue.
For one of the implementations of AES this patch reduces 
the time for analysis from 204 seconds to 8 seconds.

Test plan: make -j8 check-clang

Differential revision: https://reviews.llvm.org/D25503

Modified:
cfe/trunk/lib/Analysis/LiveVariables.cpp

Modified: cfe/trunk/lib/Analysis/LiveVariables.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/LiveVariables.cpp?rev=284166&r1=284165&r2=284166&view=diff
==
--- cfe/trunk/lib/Analysis/LiveVariables.cpp (original)
+++ cfe/trunk/lib/Analysis/LiveVariables.cpp Thu Oct 13 16:31:46 2016
@@ -19,6 +19,7 @@
 #include "clang/Analysis/CFG.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/PostOrderIterator.h"
+#include "llvm/ADT/PriorityQueue.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -28,20 +29,21 @@ using namespace clang;
 namespace {
 
 class DataflowWorklist {
-  SmallVector worklist;
   llvm::BitVector enqueuedBlocks;
   PostOrderCFGView *POV;
+  llvm::PriorityQueue,
+  PostOrderCFGView::BlockOrderCompare> worklist;
+
 public:
   DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx)
 : enqueuedBlocks(cfg.getNumBlockIDs()),
-  POV(Ctx.getAnalysis()) {}
+  POV(Ctx.getAnalysis()),
+  worklist(POV->getComparator()) {}
   
   void enqueueBlock(const CFGBlock *block);
   void enqueuePredecessors(const CFGBlock *block);
 
   const CFGBlock *dequeue();
-
-  void sortWorklist();
 };
 
 }
@@ -49,31 +51,22 @@ public:
 void DataflowWorklist::enqueueBlock(const clang::CFGBlock *block) {
   if (block && !enqueuedBlocks[block->getBlockID()]) {
 enqueuedBlocks[block->getBlockID()] = true;
-worklist.push_back(block);
+worklist.push(block);
   }
 }
 
 void DataflowWorklist::enqueuePredecessors(const clang::CFGBlock *block) {
-  const unsigned OldWorklistSize = worklist.size();
   for (CFGBlock::const_pred_iterator I = block->pred_begin(),
E = block->pred_end(); I != E; ++I) {
 enqueueBlock(*I);
   }
-  
-  if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
-return;
-
-  sortWorklist();
-}
-
-void DataflowWorklist::sortWorklist() {
-  std::sort(worklist.begin(), worklist.end(), POV->getComparator());
 }
 
 const CFGBlock *DataflowWorklist::dequeue() {
   if (worklist.empty())
 return nullptr;
-  const CFGBlock *b = worklist.pop_back_val();
+  const CFGBlock *b = worklist.top();
+  worklist.pop();
   enqueuedBlocks[b->getBlockID()] = false;
   return b;
 }
@@ -528,8 +521,6 @@ LiveVariables::computeLiveness(AnalysisD
   }
   }
   
-  worklist.sortWorklist();
-  
   while (const CFGBlock *block = worklist.dequeue()) {
 // Determine if the block's end value has changed.  If not, we
 // have nothing left to do for this block.


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


[PATCH] D25503: [analyzer] Remove superquadratic behaviour from DataflowWorklist

2016-10-13 Thread Alexander Shaposhnikov via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL284166: [analyzer] Remove superquadratic behaviour from 
DataflowWorklist (authored by alexshap).

Changed prior to commit:
  https://reviews.llvm.org/D25503?vs=74437&id=74585#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D25503

Files:
  cfe/trunk/lib/Analysis/LiveVariables.cpp


Index: cfe/trunk/lib/Analysis/LiveVariables.cpp
===
--- cfe/trunk/lib/Analysis/LiveVariables.cpp
+++ cfe/trunk/lib/Analysis/LiveVariables.cpp
@@ -19,6 +19,7 @@
 #include "clang/Analysis/CFG.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/PostOrderIterator.h"
+#include "llvm/ADT/PriorityQueue.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -28,52 +29,44 @@
 namespace {
 
 class DataflowWorklist {
-  SmallVector worklist;
   llvm::BitVector enqueuedBlocks;
   PostOrderCFGView *POV;
+  llvm::PriorityQueue,
+  PostOrderCFGView::BlockOrderCompare> worklist;
+
 public:
   DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx)
 : enqueuedBlocks(cfg.getNumBlockIDs()),
-  POV(Ctx.getAnalysis()) {}
+  POV(Ctx.getAnalysis()),
+  worklist(POV->getComparator()) {}
   
   void enqueueBlock(const CFGBlock *block);
   void enqueuePredecessors(const CFGBlock *block);
 
   const CFGBlock *dequeue();
-
-  void sortWorklist();
 };
 
 }
 
 void DataflowWorklist::enqueueBlock(const clang::CFGBlock *block) {
   if (block && !enqueuedBlocks[block->getBlockID()]) {
 enqueuedBlocks[block->getBlockID()] = true;
-worklist.push_back(block);
+worklist.push(block);
   }
 }
 
 void DataflowWorklist::enqueuePredecessors(const clang::CFGBlock *block) {
-  const unsigned OldWorklistSize = worklist.size();
   for (CFGBlock::const_pred_iterator I = block->pred_begin(),
E = block->pred_end(); I != E; ++I) {
 enqueueBlock(*I);
   }
-  
-  if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
-return;
-
-  sortWorklist();
-}
-
-void DataflowWorklist::sortWorklist() {
-  std::sort(worklist.begin(), worklist.end(), POV->getComparator());
 }
 
 const CFGBlock *DataflowWorklist::dequeue() {
   if (worklist.empty())
 return nullptr;
-  const CFGBlock *b = worklist.pop_back_val();
+  const CFGBlock *b = worklist.top();
+  worklist.pop();
   enqueuedBlocks[b->getBlockID()] = false;
   return b;
 }
@@ -528,8 +521,6 @@
   }
   }
   
-  worklist.sortWorklist();
-  
   while (const CFGBlock *block = worklist.dequeue()) {
 // Determine if the block's end value has changed.  If not, we
 // have nothing left to do for this block.


Index: cfe/trunk/lib/Analysis/LiveVariables.cpp
===
--- cfe/trunk/lib/Analysis/LiveVariables.cpp
+++ cfe/trunk/lib/Analysis/LiveVariables.cpp
@@ -19,6 +19,7 @@
 #include "clang/Analysis/CFG.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/PostOrderIterator.h"
+#include "llvm/ADT/PriorityQueue.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -28,52 +29,44 @@
 namespace {
 
 class DataflowWorklist {
-  SmallVector worklist;
   llvm::BitVector enqueuedBlocks;
   PostOrderCFGView *POV;
+  llvm::PriorityQueue,
+  PostOrderCFGView::BlockOrderCompare> worklist;
+
 public:
   DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx)
 : enqueuedBlocks(cfg.getNumBlockIDs()),
-  POV(Ctx.getAnalysis()) {}
+  POV(Ctx.getAnalysis()),
+  worklist(POV->getComparator()) {}
   
   void enqueueBlock(const CFGBlock *block);
   void enqueuePredecessors(const CFGBlock *block);
 
   const CFGBlock *dequeue();
-
-  void sortWorklist();
 };
 
 }
 
 void DataflowWorklist::enqueueBlock(const clang::CFGBlock *block) {
   if (block && !enqueuedBlocks[block->getBlockID()]) {
 enqueuedBlocks[block->getBlockID()] = true;
-worklist.push_back(block);
+worklist.push(block);
   }
 }
 
 void DataflowWorklist::enqueuePredecessors(const clang::CFGBlock *block) {
-  const unsigned OldWorklistSize = worklist.size();
   for (CFGBlock::const_pred_iterator I = block->pred_begin(),
E = block->pred_end(); I != E; ++I) {
 enqueueBlock(*I);
   }
-  
-  if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
-return;
-
-  sortWorklist();
-}
-
-void DataflowWorklist::sortWorklist() {
-  std::sort(worklist.begin(), worklist.end(), POV->getComparator());
 }
 
 const CFGBlock *DataflowWorklist::dequeue() {
   if (worklist.empty())
 return nullptr;
-  const CFGBlock *b = worklist.pop_back_val();
+  const CFGBlock *b = worklist.top();
+  worklist.pop();
   enqueuedBlocks[b->getBlockID()] = false;
   return b;
 }
@@ -528,8 +521,6 @@
   }
   }
   
-  worklist.sortWorklist();
-  
   while (const CFGBlock *block = worklist.dequeue()) {
 // Determine if the block's end value has changed.  If not, we
 // have nothing left to do for this block.
___

[PATCH] D25586: [clang-move] Use cl::list and cl::CommaSeparated for the list of names.

2016-10-13 Thread Alexander Shaposhnikov via cfe-commits
alexshap created this revision.
alexshap added reviewers: ioeric, klimek.
alexshap added a subscriber: cfe-commits.
alexshap set the repository for this revision to rL LLVM.

This diff replaces manual parsing of the comma-separated list of names with 
cl::list and cl::CommaSeparated.

Test plan: make -j8 check-clang-tools


Repository:
  rL LLVM

https://reviews.llvm.org/D25586

Files:
  clang-move/ClangMove.cpp
  clang-move/ClangMove.h
  clang-move/tool/ClangMoveMain.cpp
  unittests/clang-move/ClangMoveTests.cpp

Index: unittests/clang-move/ClangMoveTests.cpp
===
--- unittests/clang-move/ClangMoveTests.cpp
+++ unittests/clang-move/ClangMoveTests.cpp
@@ -210,7 +210,7 @@
 
 TEST(ClangMove, MoveHeaderAndCC) {
   move::ClangMoveTool::MoveDefinitionSpec Spec;
-  Spec.Names = "a::b::Foo";
+  Spec.Names = { "a::b::Foo" };
   Spec.OldHeader = "foo.h";
   Spec.OldCC = "foo.cc";
   Spec.NewHeader = "new_foo.h";
@@ -225,7 +225,7 @@
 
 TEST(ClangMove, MoveHeaderOnly) {
   move::ClangMoveTool::MoveDefinitionSpec Spec;
-  Spec.Names = "a::b::Foo";
+  Spec.Names = { "a::b::Foo" };
   Spec.OldHeader = "foo.h";
   Spec.NewHeader = "new_foo.h";
   auto Results = runClangMoveOnCode(Spec);
@@ -236,7 +236,7 @@
 
 TEST(ClangMove, MoveCCOnly) {
   move::ClangMoveTool::MoveDefinitionSpec Spec;
-  Spec.Names = "a::b::Foo";
+  Spec.Names = { "a::b::Foo" };
   Spec.OldCC = "foo.cc";
   Spec.NewCC = "new_foo.cc";
   std::string ExpectedHeader = "#include \"foo.h\"\n\n";
@@ -248,7 +248,7 @@
 
 TEST(ClangMove, MoveNonExistClass) {
   move::ClangMoveTool::MoveDefinitionSpec Spec;
-  Spec.Names = "NonExistFoo";
+  Spec.Names = { "NonExistFoo" };
   Spec.OldHeader = "foo.h";
   Spec.OldCC = "foo.cc";
   Spec.NewHeader = "new_foo.h";
Index: clang-move/tool/ClangMoveMain.cpp
===
--- clang-move/tool/ClangMoveMain.cpp
+++ clang-move/tool/ClangMoveMain.cpp
@@ -38,10 +38,10 @@
 
 cl::OptionCategory ClangMoveCategory("clang-move options");
 
-cl::opt
-Names("names", cl::desc("A comma-separated list of the names of classes "
-"being moved, e.g. \"Foo\", \"a::Foo, b::Foo\"."),
-  cl::cat(ClangMoveCategory));
+cl::list Names("names", cl::CommaSeparated, cl::OneOrMore,
+cl::desc("The list of the names of classes being "
+ "moved, e.g. \"Foo,a::Foo,b::Foo\"."),
+cl::cat(ClangMoveCategory));
 
 cl::opt
 OldHeader("old_header",
@@ -90,7 +90,8 @@
   tooling::RefactoringTool Tool(OptionsParser.getCompilations(),
 OptionsParser.getSourcePathList());
   move::ClangMoveTool::MoveDefinitionSpec Spec;
-  Spec.Names = Names;
+  Spec.Names = { Names.begin(), Names.end() };
+  
   Spec.OldHeader = OldHeader;
   Spec.NewHeader = NewHeader;
   Spec.OldCC = OldCC;
Index: clang-move/ClangMove.h
===
--- clang-move/ClangMove.h
+++ clang-move/ClangMove.h
@@ -37,9 +37,8 @@
   };
 
   struct MoveDefinitionSpec {
-// A comma-separated list of fully qualified names, e.g. "Foo",
-// "a::Foo, b::Foo".
-std::string Names;
+// The list of fully qualified names, e.g. Foo, a::Foo, b::Foo.
+llvm::SmallVector Names;
 // The file path of old header, can be relative path and absolute path.
 std::string OldHeader;
 // The file path of old cc, can be relative path and absolute path.
Index: clang-move/ClangMove.cpp
===
--- clang-move/ClangMove.cpp
+++ clang-move/ClangMove.cpp
@@ -328,10 +328,8 @@
 }
 
 void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
-  SmallVector ClassNames;
-  llvm::StringRef(Spec.Names).split(ClassNames, ',');
   Optional> InMovedClassNames;
-  for (StringRef ClassName : ClassNames) {
+  for (StringRef ClassName : Spec.Names) {
 llvm::StringRef GlobalClassName = ClassName.trim().ltrim(':');
 const auto HasName = hasName(("::" + GlobalClassName).str());
 InMovedClassNames =
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r284291 - [clang-move] Use cl::list for the list of names

2016-10-14 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Fri Oct 14 18:16:25 2016
New Revision: 284291

URL: http://llvm.org/viewvc/llvm-project?rev=284291&view=rev
Log:
[clang-move] Use cl::list for the list of names

This diff replaces manual parsing of the comma-separated list of names with 
cl::list and cl::CommaSeparated.
Test plan: make -j8 check-clang-tools

Differential revision: https://reviews.llvm.org/D25586

Modified:
clang-tools-extra/trunk/clang-move/ClangMove.cpp
clang-tools-extra/trunk/clang-move/ClangMove.h
clang-tools-extra/trunk/clang-move/tool/ClangMoveMain.cpp
clang-tools-extra/trunk/unittests/clang-move/ClangMoveTests.cpp

Modified: clang-tools-extra/trunk/clang-move/ClangMove.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-move/ClangMove.cpp?rev=284291&r1=284290&r2=284291&view=diff
==
--- clang-tools-extra/trunk/clang-move/ClangMove.cpp (original)
+++ clang-tools-extra/trunk/clang-move/ClangMove.cpp Fri Oct 14 18:16:25 2016
@@ -311,10 +311,8 @@ ClangMoveTool::ClangMoveTool(
 }
 
 void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
-  SmallVector ClassNames;
-  llvm::StringRef(Spec.Names).split(ClassNames, ',');
   Optional> InMovedClassNames;
-  for (StringRef ClassName : ClassNames) {
+  for (StringRef ClassName : Spec.Names) {
 llvm::StringRef GlobalClassName = ClassName.trim().ltrim(':');
 const auto HasName = hasName(("::" + GlobalClassName).str());
 InMovedClassNames =

Modified: clang-tools-extra/trunk/clang-move/ClangMove.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-move/ClangMove.h?rev=284291&r1=284290&r2=284291&view=diff
==
--- clang-tools-extra/trunk/clang-move/ClangMove.h (original)
+++ clang-tools-extra/trunk/clang-move/ClangMove.h Fri Oct 14 18:16:25 2016
@@ -37,9 +37,8 @@ public:
   };
 
   struct MoveDefinitionSpec {
-// A comma-separated list of fully qualified names, e.g. "Foo",
-// "a::Foo, b::Foo".
-std::string Names;
+// The list of fully qualified names, e.g. Foo, a::Foo, b::Foo.
+SmallVector Names;
 // The file path of old header, can be relative path and absolute path.
 std::string OldHeader;
 // The file path of old cc, can be relative path and absolute path.

Modified: clang-tools-extra/trunk/clang-move/tool/ClangMoveMain.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-move/tool/ClangMoveMain.cpp?rev=284291&r1=284290&r2=284291&view=diff
==
--- clang-tools-extra/trunk/clang-move/tool/ClangMoveMain.cpp (original)
+++ clang-tools-extra/trunk/clang-move/tool/ClangMoveMain.cpp Fri Oct 14 
18:16:25 2016
@@ -38,10 +38,10 @@ std::error_code CreateNewFile(const llvm
 
 cl::OptionCategory ClangMoveCategory("clang-move options");
 
-cl::opt
-Names("names", cl::desc("A comma-separated list of the names of classes "
-"being moved, e.g. \"Foo\", \"a::Foo, b::Foo\"."),
-  cl::cat(ClangMoveCategory));
+cl::list Names("names", cl::CommaSeparated, cl::OneOrMore,
+cl::desc("The list of the names of classes being "
+ "moved, e.g. \"Foo,a::Foo,b::Foo\"."),
+cl::cat(ClangMoveCategory));
 
 cl::opt
 OldHeader("old_header",
@@ -90,7 +90,7 @@ int main(int argc, const char **argv) {
   tooling::RefactoringTool Tool(OptionsParser.getCompilations(),
 OptionsParser.getSourcePathList());
   move::ClangMoveTool::MoveDefinitionSpec Spec;
-  Spec.Names = Names;
+  Spec.Names = { Names.begin(), Names.end() };
   Spec.OldHeader = OldHeader;
   Spec.NewHeader = NewHeader;
   Spec.OldCC = OldCC;

Modified: clang-tools-extra/trunk/unittests/clang-move/ClangMoveTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clang-move/ClangMoveTests.cpp?rev=284291&r1=284290&r2=284291&view=diff
==
--- clang-tools-extra/trunk/unittests/clang-move/ClangMoveTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clang-move/ClangMoveTests.cpp Fri Oct 14 
18:16:25 2016
@@ -213,7 +213,7 @@ runClangMoveOnCode(const move::ClangMove
 
 TEST(ClangMove, MoveHeaderAndCC) {
   move::ClangMoveTool::MoveDefinitionSpec Spec;
-  Spec.Names = "a::b::Foo";
+  Spec.Names = { "a::b::Foo" };
   Spec.OldHeader = "foo.h";
   Spec.OldCC = "foo.cc";
   Spec.NewHeader = "new_foo.h";
@@ -228,7 +228,7 @@ TEST(ClangMove, MoveHeaderAndCC) {
 
 TEST(ClangMove, MoveHeaderOnly) {
   move::ClangMoveTool::MoveDefinitionSpec Spec;
-  Spec.Names = "a::b::Foo";
+  Spec.Names = { "a::b::Foo" };
   Spec.OldHeader = "foo.h";
   Spec.NewHeader = "new_foo.h";
   auto Results = runClangMoveOnCode(Spec);
@@ -239,7 +239,7 @@ T

[PATCH] D25586: [clang-move] Use cl::list and cl::CommaSeparated for the list of names.

2016-10-14 Thread Alexander Shaposhnikov via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL284291: [clang-move] Use cl::list for the list of names 
(authored by alexshap).

Changed prior to commit:
  https://reviews.llvm.org/D25586?vs=74599&id=74749#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D25586

Files:
  clang-tools-extra/trunk/clang-move/ClangMove.cpp
  clang-tools-extra/trunk/clang-move/ClangMove.h
  clang-tools-extra/trunk/clang-move/tool/ClangMoveMain.cpp
  clang-tools-extra/trunk/unittests/clang-move/ClangMoveTests.cpp


Index: clang-tools-extra/trunk/unittests/clang-move/ClangMoveTests.cpp
===
--- clang-tools-extra/trunk/unittests/clang-move/ClangMoveTests.cpp
+++ clang-tools-extra/trunk/unittests/clang-move/ClangMoveTests.cpp
@@ -213,7 +213,7 @@
 
 TEST(ClangMove, MoveHeaderAndCC) {
   move::ClangMoveTool::MoveDefinitionSpec Spec;
-  Spec.Names = "a::b::Foo";
+  Spec.Names = { "a::b::Foo" };
   Spec.OldHeader = "foo.h";
   Spec.OldCC = "foo.cc";
   Spec.NewHeader = "new_foo.h";
@@ -228,7 +228,7 @@
 
 TEST(ClangMove, MoveHeaderOnly) {
   move::ClangMoveTool::MoveDefinitionSpec Spec;
-  Spec.Names = "a::b::Foo";
+  Spec.Names = { "a::b::Foo" };
   Spec.OldHeader = "foo.h";
   Spec.NewHeader = "new_foo.h";
   auto Results = runClangMoveOnCode(Spec);
@@ -239,7 +239,7 @@
 
 TEST(ClangMove, MoveCCOnly) {
   move::ClangMoveTool::MoveDefinitionSpec Spec;
-  Spec.Names = "a::b::Foo";
+  Spec.Names = { "a::b::Foo" };
   Spec.OldCC = "foo.cc";
   Spec.NewCC = "new_foo.cc";
   std::string ExpectedHeader = "#include \"foo.h\"\n\n";
@@ -251,7 +251,7 @@
 
 TEST(ClangMove, MoveNonExistClass) {
   move::ClangMoveTool::MoveDefinitionSpec Spec;
-  Spec.Names = "NonExistFoo";
+  Spec.Names = { "NonExistFoo" };
   Spec.OldHeader = "foo.h";
   Spec.OldCC = "foo.cc";
   Spec.NewHeader = "new_foo.h";
Index: clang-tools-extra/trunk/clang-move/tool/ClangMoveMain.cpp
===
--- clang-tools-extra/trunk/clang-move/tool/ClangMoveMain.cpp
+++ clang-tools-extra/trunk/clang-move/tool/ClangMoveMain.cpp
@@ -38,10 +38,10 @@
 
 cl::OptionCategory ClangMoveCategory("clang-move options");
 
-cl::opt
-Names("names", cl::desc("A comma-separated list of the names of classes "
-"being moved, e.g. \"Foo\", \"a::Foo, b::Foo\"."),
-  cl::cat(ClangMoveCategory));
+cl::list Names("names", cl::CommaSeparated, cl::OneOrMore,
+cl::desc("The list of the names of classes being "
+ "moved, e.g. \"Foo,a::Foo,b::Foo\"."),
+cl::cat(ClangMoveCategory));
 
 cl::opt
 OldHeader("old_header",
@@ -90,7 +90,7 @@
   tooling::RefactoringTool Tool(OptionsParser.getCompilations(),
 OptionsParser.getSourcePathList());
   move::ClangMoveTool::MoveDefinitionSpec Spec;
-  Spec.Names = Names;
+  Spec.Names = { Names.begin(), Names.end() };
   Spec.OldHeader = OldHeader;
   Spec.NewHeader = NewHeader;
   Spec.OldCC = OldCC;
Index: clang-tools-extra/trunk/clang-move/ClangMove.cpp
===
--- clang-tools-extra/trunk/clang-move/ClangMove.cpp
+++ clang-tools-extra/trunk/clang-move/ClangMove.cpp
@@ -311,10 +311,8 @@
 }
 
 void ClangMoveTool::registerMatchers(ast_matchers::MatchFinder *Finder) {
-  SmallVector ClassNames;
-  llvm::StringRef(Spec.Names).split(ClassNames, ',');
   Optional> InMovedClassNames;
-  for (StringRef ClassName : ClassNames) {
+  for (StringRef ClassName : Spec.Names) {
 llvm::StringRef GlobalClassName = ClassName.trim().ltrim(':');
 const auto HasName = hasName(("::" + GlobalClassName).str());
 InMovedClassNames =
Index: clang-tools-extra/trunk/clang-move/ClangMove.h
===
--- clang-tools-extra/trunk/clang-move/ClangMove.h
+++ clang-tools-extra/trunk/clang-move/ClangMove.h
@@ -37,9 +37,8 @@
   };
 
   struct MoveDefinitionSpec {
-// A comma-separated list of fully qualified names, e.g. "Foo",
-// "a::Foo, b::Foo".
-std::string Names;
+// The list of fully qualified names, e.g. Foo, a::Foo, b::Foo.
+SmallVector Names;
 // The file path of old header, can be relative path and absolute path.
 std::string OldHeader;
 // The file path of old cc, can be relative path and absolute path.


Index: clang-tools-extra/trunk/unittests/clang-move/ClangMoveTests.cpp
===
--- clang-tools-extra/trunk/unittests/clang-move/ClangMoveTests.cpp
+++ clang-tools-extra/trunk/unittests/clang-move/ClangMoveTests.cpp
@@ -213,7 +213,7 @@
 
 TEST(ClangMove, MoveHeaderAndCC) {
   move::ClangMoveTool::MoveDefinitionSpec Spec;
-  Spec.Names = "a::b::Foo";
+  Spec.Names = { "a::b::Foo" };
   Spec.OldHeader = "foo.h";
   Spec.OldCC = "foo.cc";
   Spec.NewHeade

[clang-tools-extra] 47dbacb - [clang-tidy] Restrict use-equals-default to c++11-or-later

2022-09-02 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-09-02T22:19:11Z
New Revision: 47dbacbc8ae2c13f970096814de8f677d80859af

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

LOG: [clang-tidy] Restrict use-equals-default to c++11-or-later

Restrict use-equals-default to c++11-or-later.

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D132998

Added: 

clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx98.cpp

Modified: 
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h
clang-tools-extra/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h 
b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h
index a992177522f75..4ffed8c406481 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h
+++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h
@@ -38,7 +38,7 @@ class UseEqualsDefaultCheck : public ClangTidyCheck {
 public:
   UseEqualsDefaultCheck(StringRef Name, ClangTidyContext *Context);
   bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
-return LangOpts.CPlusPlus;
+return LangOpts.CPlusPlus11;
   }
   void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 55c8c341bff3a..e0907b23c84c7 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -145,7 +145,7 @@ Changes in existing checks
   check.
 
   The check now skips unions since in this case a default constructor with 
empty body
-  is not equivalent to the explicitly defaulted one.
+  is not equivalent to the explicitly defaulted one. The check is restricted 
to c++11-or-later.
 
 Removed checks
 ^^

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx98.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx98.cpp
new file mode 100644
index 0..d43c1e58c2606
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx98.cpp
@@ -0,0 +1,8 @@
+// RUN: %check_clang_tidy -std=c++98 %s modernize-use-equals-default %t
+
+struct S {
+  S() {}
+  // CHECK-FIXES: S() {}
+  ~S() {}
+  // CHECK-FIXES: ~S() {}
+};



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


[clang-tools-extra] a7395b8 - [clang-tidy] Skip copy assignment operators with nonstandard return types

2022-09-02 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-09-02T22:43:39Z
New Revision: a7395b860bc247c9e4e917bf5786c04d4cccf1d7

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

LOG: [clang-tidy] Skip copy assignment operators with nonstandard return types

Skip copy assignment operators with nonstandard return types
since they cannot be defaulted.

Test plan: ninja check-clang-tools

Differential revision: https://reviews.llvm.org/D133006

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
index f321c0b2e693..2de677d2735f 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
@@ -8,6 +8,7 @@
 
 #include "UseEqualsDefaultCheck.h"
 #include "../utils/LexerUtils.h"
+#include "../utils/Matchers.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Lex/Lexer.h"
@@ -247,7 +248,12 @@ void UseEqualsDefaultCheck::registerMatchers(MatchFinder 
*Finder) {
 // isCopyAssignmentOperator() allows the parameter to be
 // passed by value, and in this case it cannot be
 // defaulted.
-hasParameter(0, hasType(lValueReferenceType(
+hasParameter(0, hasType(lValueReferenceType())),
+// isCopyAssignmentOperator() allows non lvalue reference
+// return types, and in this case it cannot be defaulted.
+returns(qualType(hasCanonicalType(
+allOf(lValueReferenceType(pointee(type())),
+  unless(matchers::isReferenceToConst()))
   .bind(SpecialFunction),
   this);
 }

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index e0907b23c84c..7c91ea00dca8 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -145,7 +145,8 @@ Changes in existing checks
   check.
 
   The check now skips unions since in this case a default constructor with 
empty body
-  is not equivalent to the explicitly defaulted one. The check is restricted 
to c++11-or-later.
+  is not equivalent to the explicitly defaulted one. The check also skips copy 
assignment
+  operators with nonstandard return types. The check is restricted to 
c++11-or-later.
 
 Removed checks
 ^^

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
index 78a03f02eed5..70fc521ebb7a 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
@@ -444,6 +444,13 @@ IL &WRT::operator=(const WRT &Other) {
   return *this;
 }
 
+// Wrong return type.
+struct WRTConstRef {
+  const WRTConstRef &operator = (const WRTConstRef &) {
+return *this;
+  }
+};
+
 // Try-catch.
 struct ITC {
   ITC(const ITC &Other)



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


[clang-tools-extra] 4450348 - [clang-tidy] Skip union-like classes in use-equals-default

2022-09-06 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-09-06T20:19:47Z
New Revision: 44503482e0af189d3a7fc57b80238ea4151992b9

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

LOG: [clang-tidy] Skip union-like classes in use-equals-default

Skip unions/union-like classes since in this case constructors
with empty bodies behave differently in comparison with regular
structs/classes.

Test plan: ninja check-clang-tools

Differential revision: https://reviews.llvm.org/D132713

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
index 2de677d2735fe..d5c402c4bdeb7 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
@@ -218,17 +218,20 @@ void 
UseEqualsDefaultCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
 }
 
 void UseEqualsDefaultCheck::registerMatchers(MatchFinder *Finder) {
-  // Skip unions since constructors with empty bodies behave 
diff erently
-  // in comparison with structs/classes.
+  // Skip unions/union-like classes since their constructors behave 
diff erently
+  // when defaulted vs. empty.
+  auto IsUnionLikeClass = recordDecl(
+  anyOf(isUnion(),
+has(fieldDecl(isImplicit(), hasType(cxxRecordDecl(isUnion()));
 
   // Destructor.
-  
Finder->addMatcher(cxxDestructorDecl(unless(hasParent(recordDecl(isUnion(,
-   isDefinition())
- .bind(SpecialFunction),
- this);
+  Finder->addMatcher(
+  cxxDestructorDecl(unless(hasParent(IsUnionLikeClass)), isDefinition())
+  .bind(SpecialFunction),
+  this);
   Finder->addMatcher(
   cxxConstructorDecl(
-  unless(hasParent(recordDecl(isUnion(, isDefinition(),
+  unless(hasParent(IsUnionLikeClass)), isDefinition(),
   anyOf(
   // Default constructor.
   allOf(unless(hasAnyConstructorInitializer(isWritten())),
@@ -243,7 +246,7 @@ void UseEqualsDefaultCheck::registerMatchers(MatchFinder 
*Finder) {
   this);
   // Copy-assignment operator.
   Finder->addMatcher(
-  cxxMethodDecl(unless(hasParent(recordDecl(isUnion(, isDefinition(),
+  cxxMethodDecl(unless(hasParent(IsUnionLikeClass)), isDefinition(),
 isCopyAssignmentOperator(),
 // isCopyAssignmentOperator() allows the parameter to be
 // passed by value, and in this case it cannot be

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 7c91ea00dca84..89dd7e746e587 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -144,9 +144,10 @@ Changes in existing checks
 - Improved :doc:`modernize-use-equals-default 
`
   check.
 
-  The check now skips unions since in this case a default constructor with 
empty body
-  is not equivalent to the explicitly defaulted one. The check also skips copy 
assignment
-  operators with nonstandard return types. The check is restricted to 
c++11-or-later.
+  The check now skips unions/union-like classes since in this case a default 
constructor
+  with empty body is not equivalent to the explicitly defaulted one. The check 
also skips
+  copy assignment operators with nonstandard return types. The check is 
restricted to
+  c++11-or-later.
 
 Removed checks
 ^^

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
index 70fc521ebb7ae..eaa600ad86438 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
@@ -44,6 +44,20 @@ union NU {
   IL Field;
 };
 
+// Skip structs/classes containing anonymous unions.
+struct SU {
+  SU(const SU &Other) : Field(Other.Field) {}
+  // CHECK-FIXES: SU(const SU &Other) :
+  SU &operator=(const SU &Other) {
+Field = Other.Field;
+return *this;
+  }
+  // CHECK-FIXES: SU &operator=(const SU &Other) {
+  union {
+IL Field;
+  };
+};
+
 // Wrong type.
 struct WT {
   WT(const IL &Other) {}

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp 
b/clang-tools-extra/test/clang-tidy/

[clang] b6965f7 - [IR] Add alignment for llvm.threadlocal.address

2022-09-13 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-09-13T23:10:55Z
New Revision: b6965f7246bba1b399755f56d8ae34893e815198

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

LOG: [IR] Add alignment for llvm.threadlocal.address

This diff sets the alignment attribute for the return value
and the argument of llvm.threadlocal.address.

(https://github.com/llvm/llvm-project/issues/57438)

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D133741

Added: 


Modified: 
clang/test/CodeGenCXX/cxx11-thread-local-instantiated.cpp
clang/test/CodeGenCXX/cxx11-thread-local-reference.cpp
clang/test/CodeGenCXX/cxx11-thread-local.cpp
clang/test/CodeGenCXX/cxx1y-variable-template.cpp
clang/test/CodeGenCXX/cxx2a-thread-local-constinit.cpp
clang/test/CodeGenCXX/microsoft-abi-thread-safe-statics.cpp
clang/test/CodeGenCXX/pr18635.cpp
clang/test/CodeGenCXX/threadlocal_address.cpp
clang/test/Modules/initializers.cpp
clang/test/OpenMP/parallel_copyin_codegen.cpp
clang/test/OpenMP/parallel_copyin_combined_codegen.c
clang/test/OpenMP/parallel_master_codegen.cpp
clang/test/OpenMP/teams_distribute_parallel_for_copyin_codegen.cpp
clang/test/OpenMP/threadprivate_codegen.cpp
llvm/lib/IR/IRBuilder.cpp

Removed: 




diff  --git a/clang/test/CodeGenCXX/cxx11-thread-local-instantiated.cpp 
b/clang/test/CodeGenCXX/cxx11-thread-local-instantiated.cpp
index 46c16bdd94e39..fc3514a8b17da 100644
--- a/clang/test/CodeGenCXX/cxx11-thread-local-instantiated.cpp
+++ b/clang/test/CodeGenCXX/cxx11-thread-local-instantiated.cpp
@@ -17,7 +17,7 @@ S *current() { return TLS::mData; };
 
 // CHECK-LABEL: define weak_odr hidden {{.*}} @_ZTWN3TLSI1SE5mDataE() {{.*}} 
comdat {
 // CHECK: call void @_ZTHN3TLSI1SE5mDataE()
-// CHECK: [[TLSmData_ADDR:%[^ ]+]] = call ptr @llvm.threadlocal.address.p0(ptr 
@_ZN3TLSI1SE5mDataE)
+// CHECK: [[TLSmData_ADDR:%[^ ]+]] = call align 8 ptr 
@llvm.threadlocal.address.p0(ptr align 8 @_ZN3TLSI1SE5mDataE)
 // CHECK: ret {{.*}} [[TLSmData_ADDR]]
 
 // Unlike for a global, the global initialization function must not be in a

diff  --git a/clang/test/CodeGenCXX/cxx11-thread-local-reference.cpp 
b/clang/test/CodeGenCXX/cxx11-thread-local-reference.cpp
index 3fc960f1eefc4..1d5143f1d3510 100644
--- a/clang/test/CodeGenCXX/cxx11-thread-local-reference.cpp
+++ b/clang/test/CodeGenCXX/cxx11-thread-local-reference.cpp
@@ -15,7 +15,7 @@ int &g() { return r; }
 
 // CHECK: define {{.*}} @[[R_INIT:.*]]()
 // CHECK: call noundef nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) 
i32* @_Z1fv()
-// CHECK: %[[R_ADDR:.+]] = call i32** @llvm.threadlocal.address.p0p0i32(i32** 
@r)
+// CHECK: %[[R_ADDR:.+]] = call align 8 i32** 
@llvm.threadlocal.address.p0p0i32(i32** align 8 @r)
 // CHECK: store i32* %{{.*}}, i32** %[[R_ADDR]], align 8
 
 // CHECK-LABEL: define{{.*}} nonnull align {{[0-9]+}} 
dereferenceable({{[0-9]+}}) i32* @_Z1gv()
@@ -27,7 +27,7 @@ int &g() { return r; }
 // DARWIN: define cxx_fast_tlscc noundef i32* @_ZTW1r() [[ATTR1:#[0-9]+]] {
 // LINUX_AIX: call void @_ZTH1r()
 // DARWIN: call cxx_fast_tlscc void @_ZTH1r()
-// CHECK: %[[R_ADDR2:.+]] = call i32** @llvm.threadlocal.address.p0p0i32(i32** 
@r)
+// CHECK: %[[R_ADDR2:.+]] = call align 8 i32** 
@llvm.threadlocal.address.p0p0i32(i32** align 8 @r)
 // CHECK: load i32*, i32** %[[R_ADDR2]], align 8
 // CHECK: ret i32* %{{.*}}
 

diff  --git a/clang/test/CodeGenCXX/cxx11-thread-local.cpp 
b/clang/test/CodeGenCXX/cxx11-thread-local.cpp
index 4023daa8192ab..7b53211e9ceb0 100644
--- a/clang/test/CodeGenCXX/cxx11-thread-local.cpp
+++ b/clang/test/CodeGenCXX/cxx11-thread-local.cpp
@@ -108,7 +108,7 @@ void *e2 = V::m + W::m + &X::m;
 
 // CHECK: define {{.*}} @[[A_INIT:.*]]()
 // CHECK: call{{.*}} i32 @_Z1fv()
-// CHECK: [[A_ADDR:%.+]] = call i32* @llvm.threadlocal.address.p0i32(i32* @a)
+// CHECK: [[A_ADDR:%.+]] = call align 4 i32* 
@llvm.threadlocal.address.p0i32(i32* align 4 @a)
 // CHECK-NEXT: store i32 {{.*}}, i32* [[A_ADDR]], align 4
 
 // CHECK-LABEL: define{{.*}} i32 @_Z1fv()
@@ -118,13 +118,13 @@ int f() {
   // CHECK: br i1 %[[NEED_INIT]]{{.*}}
 
   // CHECK: %[[CALL:.*]] = call{{.*}} i32 @_Z1gv()
-  // CHECK: [[N_ADDR:%.+]] = call i32* @llvm.threadlocal.address.p0i32(i32* 
@_ZZ1fvE1n)
+  // CHECK: [[N_ADDR:%.+]] = call align 4 i32* 
@llvm.threadlocal.address.p0i32(i32* align 4 @_ZZ1fvE1n)
   // CHECK: store i32 %[[CALL]], i32* [[N_ADDR]], align 4
   // CHECK: store i8 1, i8* @_ZGVZ1fvE1n
   // CHECK: br label
   static thread_local int n = g();
-  
-  // CHECK: [[N_ADDR2:%.+]] = call i32* @llvm.threadlocal.address.p0i32(i32* 
@_ZZ1fvE1n)
+
+  // CHECK: [[N_ADDR2:%.+]] = call align 4 i32* 
@llvm.threadlocal.address.p0i32(i32* align 4 @_ZZ1fvE1n)
   // CHECK: load i32, i32* [[N_ADD

[clang] [clang-tools-extra] [llvm] [ConstraintElim] Add facts implied by llvm.abs (PR #73189)

2023-12-03 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov updated 
https://github.com/llvm/llvm-project/pull/73189

>From a9e76a878edc8bc9cb81b8aa169bbbc467d32026 Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Thu, 23 Nov 2023 00:37:08 +
Subject: [PATCH] [ConstraintElim] Add a fact implied by llvm.abs

---
 .../Scalar/ConstraintElimination.cpp  | 10 +++
 .../Transforms/ConstraintElimination/abs.ll   | 26 +++
 2 files changed, 36 insertions(+)
 create mode 100644 llvm/test/Transforms/ConstraintElimination/abs.ll

diff --git a/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp 
b/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp
index 7aadd810c1da3..59aaa677ccbf9 100644
--- a/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp
+++ b/llvm/lib/Transforms/Scalar/ConstraintElimination.cpp
@@ -995,6 +995,11 @@ void State::addInfoFor(BasicBlock &BB) {
   continue;
 }
 
+if (match(&I, m_Intrinsic())) {
+  WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), &I));
+  continue;
+}
+
 Value *A, *B;
 CmpInst::Predicate Pred;
 // For now, just handle assumes with a single compare as condition.
@@ -1629,6 +1634,11 @@ static bool eliminateConstraints(Function &F, 
DominatorTree &DT, LoopInfo &LI,
 
 ICmpInst::Predicate Pred;
 if (!CB.isConditionFact()) {
+  if (Value *X; match(CB.Inst, m_Intrinsic(m_Value(X {
+AddFact(CmpInst::ICMP_SGE, CB.Inst, X);
+continue;
+  }
+
   if (auto *MinMax = dyn_cast(CB.Inst)) {
 Pred = ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
 AddFact(Pred, MinMax, MinMax->getLHS());
diff --git a/llvm/test/Transforms/ConstraintElimination/abs.ll 
b/llvm/test/Transforms/ConstraintElimination/abs.ll
new file mode 100644
index 0..1cf56c6e37a8c
--- /dev/null
+++ b/llvm/test/Transforms/ConstraintElimination/abs.ll
@@ -0,0 +1,26 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py 
UTC_ARGS: --version 4
+; RUN: opt -passes=constraint-elimination -S %s | FileCheck %s
+
+define i1 @abs_false(i32 %arg) {
+; CHECK-LABEL: define i1 @abs_false(
+; CHECK-SAME: i32 [[ARG:%.*]]) {
+; CHECK-NEXT:[[ABS:%.*]] = tail call i32 @llvm.abs.i32(i32 [[ARG]], i1 
false)
+; CHECK-NEXT:ret i1 true
+;
+  %abs = tail call i32 @llvm.abs.i32(i32 %arg, i1 false)
+  %cmp = icmp sge i32 %abs, %arg
+  ret i1 %cmp
+}
+
+define i1 @abs_true(i32 %arg) {
+; CHECK-LABEL: define i1 @abs_true(
+; CHECK-SAME: i32 [[ARG:%.*]]) {
+; CHECK-NEXT:[[ABS:%.*]] = tail call i32 @llvm.abs.i32(i32 [[ARG]], i1 
true)
+; CHECK-NEXT:ret i1 true
+;
+  %abs = tail call i32 @llvm.abs.i32(i32 %arg, i1 true)
+  %cmp = icmp sge i32 %abs, %arg
+  ret i1 %cmp
+}
+
+declare i32 @llvm.abs.i32(i32, i1 immarg)

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


[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-20 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov edited 
https://github.com/llvm/llvm-project/pull/85916
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-20 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov edited 
https://github.com/llvm/llvm-project/pull/85916
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-26 Thread Alexander Shaposhnikov via cfe-commits

alexander-shaposhnikov wrote:

@vitalybuka , @arsenm - thanks a lot, yeah, sure, I can split the patch.
P.S. will update/address comments soon.

https://github.com/llvm/llvm-project/pull/85916
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D35961: [llvm] Update MachOObjectFile::exports interface

2017-07-28 Thread Alexander Shaposhnikov via cfe-commits
Hi,
many thanks for looking at the diff.
(i started working on this because this interface change broke some
out-of-tree code, but that's expected and not a big issue, i just wanted to
clean it up a bit).

I assume I might be missing smth,
however my diff doesn't change the static method
/// For use examining a trie not in a MachOObjectFile.
static iterator_range exports(Error &Err,
 ArrayRef Trie,
 const MachOObjectFile *O =

nullptr);

It changes only the regular method
/// For use iterating over all exported symbols.
iterator_range exports(Error &Err, const MachOObjectFile *O)
const;
because I didn't like syntax Obj->exports(Err, Obj).
LLD builds successfully with my patch - so I am wondering if this change
looks reasonable/safe to you.

Thanks,
Alex Shaposhnikov



On Fri, Jul 28, 2017 at 10:30 AM, David Blaikie  wrote:

>
>
> On Fri, Jul 28, 2017 at 10:24 AM Kevin Enderby  wrote:
>
>> On Jul 27, 2017, at 9:50 PM, Saleem Abdulrasool via Phabricator <
>> revi...@reviews.llvm.org> wrote:
>>
>> compnerd added a comment.
>>
>> Does anyone use the overload with the `O` for `exports` with `nullptr`
>> instead of `this`?  If not, we could just inline `this` throughout.
>>
>>
>> This will break lld as it needs the default nullptr.  See r308691.
>>
>> The reason that O was added was so that this check from r308690 could be
>> added.
>>
>
> When O is specified is it always == this, though? That seems to be implied
> by the original post.
>
> If that's the case, then the ability to pass null is really only passing
> the on/off state for the diagnostic? Is that necessary, or would it be good
> to just always produce the Error, even in lld?
>
>
>>
>> +  if (O != nullptr) {
>> +if (State.Other > O->getLibraryCount()) {
>> +  *E = malformedError("bad library ordinal: " +
>> Twine((int)State.Other)
>> +   + " (max " + Twine((int)O->getLibraryCount()) + ") in
>> export "
>> +   "trie data at node: 0x" + utohexstr(offset));
>> +  moveToEnd();
>> +  return;
>> +}
>>
>> This is needed for the test case:
>>
>> +RUN: not llvm-objdump -macho -exports-trie 
>> %p/Inputs/macho-trie-bad-library-ordinal
>> 2>&1 | FileCheck -check-prefix BAD_LIBRARY_ORDINAL %s
>> +BAD_LIBRARY_ORDINAL: macho-trie-bad-library-ordinal': truncated or
>> malformed object (bad library ordinal: 69 (max 3) in export trie data at
>> node: 0x33)
>>
>>
>>
>>
>> 
>> Comment at: tools/llvm-nm/llvm-nm.cpp:1230
>>   Error Err = Error::success();
>> -  for (const llvm::object::ExportEntry &Entry : MachO->exports(Err,
>> -   MachO))
>> {
>> +  for (const llvm::object::ExportEntry &Entry : MachO->exports(Err))
>> {
>> bool found = false;
>> 
>> I think that using `auto` here instead of `llvm::object:ExportEntry` is
>> better for readability.
>>
>>
>> 
>> Comment at: tools/llvm-objdump/MachODump.cpp:9406
>>   Error Err = Error::success();
>> -  for (const llvm::object::ExportEntry &Entry : Obj->exports(Err, Obj)) {
>> +  for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
>> uint64_t Flags = Entry.flags();
>> 
>> Similar.
>>
>>
>> Repository:
>>  rL LLVM
>>
>> https://reviews.llvm.org/D35961
>>
>>
>>
>>
>>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r309505 - [clang-reorder-fields] Emit warning when reordering breaks member init list dependencies

2017-07-29 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Sat Jul 29 23:43:03 2017
New Revision: 309505

URL: http://llvm.org/viewvc/llvm-project?rev=309505&view=rev
Log:
[clang-reorder-fields] Emit warning when reordering breaks member init list 
dependencies

This diff adds a warning emitted by clang-reorder-fields 
when reordering breaks dependencies in the initializer list.

Patch by Sam Conrad!

Differential revision: https://reviews.llvm.org/D35972

Added:
clang-tools-extra/trunk/test/clang-reorder-fields/ClassDerived.cpp
clang-tools-extra/trunk/test/clang-reorder-fields/FieldDependencyWarning.cpp

clang-tools-extra/trunk/test/clang-reorder-fields/FieldDependencyWarningDerived.cpp
Modified:
clang-tools-extra/trunk/clang-reorder-fields/ReorderFieldsAction.cpp

Modified: clang-tools-extra/trunk/clang-reorder-fields/ReorderFieldsAction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-reorder-fields/ReorderFieldsAction.cpp?rev=309505&r1=309504&r2=309505&view=diff
==
--- clang-tools-extra/trunk/clang-reorder-fields/ReorderFieldsAction.cpp 
(original)
+++ clang-tools-extra/trunk/clang-reorder-fields/ReorderFieldsAction.cpp Sat 
Jul 29 23:43:03 2017
@@ -22,21 +22,23 @@
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Refactoring.h"
+#include "llvm/ADT/SetVector.h"
 #include 
 #include 
 
 namespace clang {
 namespace reorder_fields {
 using namespace clang::ast_matchers;
+using llvm::SmallSetVector;
 
 /// \brief Finds the definition of a record by name.
 ///
 /// \returns nullptr if the name is ambiguous or not found.
 static const RecordDecl *findDefinition(StringRef RecordName,
 ASTContext &Context) {
-  auto Results = match(
-  recordDecl(hasName(RecordName), isDefinition()).bind("recordDecl"),
-  Context);
+  auto Results =
+  match(recordDecl(hasName(RecordName), isDefinition()).bind("recordDecl"),
+Context);
   if (Results.empty()) {
 llvm::errs() << "Definition of " << RecordName << "  not found\n";
 return nullptr;
@@ -91,6 +93,28 @@ addReplacement(SourceRange Old, SourceRa
   consumeError(Replacements[R.getFilePath()].add(R));
 }
 
+/// \brief Find all member fields used in the given init-list initializer expr
+/// that belong to the same record
+///
+/// \returns a set of field declarations, empty if none were present
+static SmallSetVector
+findMembersUsedInInitExpr(const CXXCtorInitializer *Initializer,
+  ASTContext &Context) {
+  SmallSetVector Results;
+  // Note that this does not pick up member fields of base classes since
+  // for those accesses Sema::PerformObjectMemberConversion always inserts an
+  // UncheckedDerivedToBase ImplicitCastExpr between the this expr and the
+  // object expression
+  auto FoundExprs =
+  match(findAll(memberExpr(hasObjectExpression(cxxThisExpr())).bind("ME")),
+*Initializer->getInit(), Context);
+  for (BoundNodes &BN : FoundExprs)
+if (auto *MemExpr = BN.getNodeAs("ME"))
+  if (auto *FD = dyn_cast(MemExpr->getMemberDecl()))
+Results.insert(FD);
+  return Results;
+}
+
 /// \brief Reorders fields in the definition of a struct/class.
 ///
 /// At the moment reodering of fields with
@@ -129,11 +153,12 @@ static bool reorderFieldsInDefinition(
 
 /// \brief Reorders initializers in a C++ struct/class constructor.
 ///
-/// A constructor can have initializers for an arbitrary subset of the class's 
fields.
-/// Thus, we need to ensure that we reorder just the initializers that are 
present.
+/// A constructor can have initializers for an arbitrary subset of the class's
+/// fields. Thus, we need to ensure that we reorder just the initializers that
+/// are present.
 static void reorderFieldsInConstructor(
 const CXXConstructorDecl *CtorDecl, ArrayRef NewFieldsOrder,
-const ASTContext &Context,
+ASTContext &Context,
 std::map &Replacements) {
   assert(CtorDecl && "Constructor declaration is null");
   if (CtorDecl->isImplicit() || CtorDecl->getNumCtorInitializers() <= 1)
@@ -151,8 +176,26 @@ static void reorderFieldsInConstructor(
   SmallVector OldWrittenInitializersOrder;
   SmallVector NewWrittenInitializersOrder;
   for (const auto *Initializer : CtorDecl->inits()) {
-if (!Initializer->isWritten())
+if (!Initializer->isMemberInitializer() || !Initializer->isWritten())
   continue;
+
+// Warn if this reordering violates initialization expr dependencies.
+const FieldDecl *ThisM = Initializer->getMember();
+const auto UsedMembers = findMembersUsedInInitExpr(Initializer, Context);
+for (const FieldDecl *UM : UsedMembers) {
+  if (NewFieldsPositions[UM->getFieldIndex()] >
+  NewFieldsPositions[ThisM->getFieldIndex()]) {
+DiagnosticsEngine &DiagEngine = Context.getDiagnostics();
+auto Description = ("reordering field " + UM->getNa

r310887 - [analyzer] Fix SimpleSValBuilder::simplifySVal

2017-08-14 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Aug 14 14:23:08 2017
New Revision: 310887

URL: http://llvm.org/viewvc/llvm-project?rev=310887&view=rev
Log:
[analyzer] Fix SimpleSValBuilder::simplifySVal

This diff fixes a crash (triggered assert) on the newly added test case.
In the method Simplifier::VisitSymbolData we check the type of S and return
Loc/NonLoc accordingly.

Differential revision: https://reviews.llvm.org/D36564

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
cfe/trunk/test/Analysis/ptr-arith.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp?rev=310887&r1=310886&r2=310887&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp Mon Aug 14 14:23:08 
2017
@@ -1016,7 +1016,8 @@ SVal SimpleSValBuilder::simplifySVal(Pro
   SVB.getKnownValue(State, nonloc::SymbolVal(S)))
 return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I)
 : (SVal)SVB.makeIntVal(*I);
-  return nonloc::SymbolVal(S);
+  return Loc::isLocType(S->getType()) ? (SVal)SVB.makeLoc(S) 
+  : nonloc::SymbolVal(S);
 }
 
 // TODO: Support SymbolCast. Support IntSymExpr when/if we actually

Modified: cfe/trunk/test/Analysis/ptr-arith.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/ptr-arith.cpp?rev=310887&r1=310886&r2=310887&view=diff
==
--- cfe/trunk/test/Analysis/ptr-arith.cpp (original)
+++ cfe/trunk/test/Analysis/ptr-arith.cpp Mon Aug 14 14:23:08 2017
@@ -98,3 +98,10 @@ void checkMultiDimansionalArray() {
   int a[5][5];
*(*(a+1)+2) = 2;
 }
+
+unsigned ptrSubtractionNoCrash(char *Begin, char *End) {
+  auto N = End - Begin;
+  if (Begin)
+return 0;
+  return N;
+}


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


r310948 - [clang] Code cleanup in clang/tooling

2017-08-15 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Tue Aug 15 12:23:54 2017
New Revision: 310948

URL: http://llvm.org/viewvc/llvm-project?rev=310948&view=rev
Log:
[clang] Code cleanup in clang/tooling

1. Add missing explicit for SymbolName constructor.
2. Add missing std::move in createRenameReplacements.

Differential revision: https://reviews.llvm.org/D36715

Modified:
cfe/trunk/include/clang/Tooling/Refactoring/Rename/SymbolName.h
cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp

Modified: cfe/trunk/include/clang/Tooling/Refactoring/Rename/SymbolName.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/Refactoring/Rename/SymbolName.h?rev=310948&r1=310947&r2=310948&view=diff
==
--- cfe/trunk/include/clang/Tooling/Refactoring/Rename/SymbolName.h (original)
+++ cfe/trunk/include/clang/Tooling/Refactoring/Rename/SymbolName.h Tue Aug 15 
12:23:54 2017
@@ -29,7 +29,7 @@ namespace tooling {
 /// \endcode
 class SymbolName {
 public:
-  SymbolName(StringRef Name) {
+  explicit SymbolName(StringRef Name) {
 // While empty symbol names are valid (Objective-C selectors can have empty
 // name pieces), occurrences Objective-C selectors are created using an
 // array of strings instead of just one string.

Modified: cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp?rev=310948&r1=310947&r2=310948&view=diff
==
--- cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp (original)
+++ cfe/trunk/lib/Tooling/Refactoring/Rename/RenamingAction.cpp Tue Aug 15 
12:23:54 2017
@@ -53,7 +53,7 @@ createRenameReplacements(const SymbolOcc
 }
 Changes.push_back(std::move(Change));
   }
-  return Changes;
+  return std::move(Changes);
 }
 
 /// Takes each atomic change and inserts its replacements into the set of


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


r311182 - [analyzer] Fix modeling of constructors

2017-08-18 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Fri Aug 18 11:20:43 2017
New Revision: 311182

URL: http://llvm.org/viewvc/llvm-project?rev=311182&view=rev
Log:
[analyzer] Fix modeling of constructors

This diff fixes analyzer's crash (triggered assert) on the newly added test 
case.
The assert being discussed is assert(!B.lookup(R, BindingKey::Direct))
in lib/StaticAnalyzer/Core/RegionStore.cpp, however the root cause is different.
For classes with empty bases the offsets might be tricky.
For example, let's assume we have
 struct S: NonEmptyBase, EmptyBase {
 ...
 };
In this case Clang applies empty base class optimization and 
the offset of EmptyBase will be 0, it can be verified via
clang -cc1 -x c++ -v -fdump-record-layouts main.cpp -emit-llvm -o /dev/null.
When the analyzer tries to perform zero initialization of EmptyBase
it will hit the assert because that region
has already been "written" by the constructor of NonEmptyBase.

Test plan:
make check-all

Differential revision: https://reviews.llvm.org/D36851

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
cfe/trunk/test/Analysis/ctor.mm

Modified: cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp?rev=311182&r1=311181&r2=311182&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp Fri Aug 18 11:20:43 2017
@@ -409,6 +409,19 @@ public: // Part of public interface to c
 
   // BindDefault is only used to initialize a region with a default value.
   StoreRef BindDefault(Store store, const MemRegion *R, SVal V) override {
+// FIXME: The offsets of empty bases can be tricky because of
+// of the so called "empty base class optimization".
+// If a base class has been optimized out
+// we should not try to create a binding, otherwise we should.
+// Unfortunately, at the moment ASTRecordLayout doesn't expose
+// the actual sizes of the empty bases
+// and trying to infer them from offsets/alignments
+// seems to be error-prone and non-trivial because of the trailing padding.
+// As a temporary mitigation we don't create bindings for empty bases.
+if (R->getKind() == MemRegion::CXXBaseObjectRegionKind &&
+cast(R)->getDecl()->isEmpty())
+  return StoreRef(store, *this);
+
 RegionBindingsRef B = getRegionBindings(store);
 assert(!B.lookup(R, BindingKey::Direct));
 

Modified: cfe/trunk/test/Analysis/ctor.mm
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/ctor.mm?rev=311182&r1=311181&r2=311182&view=diff
==
--- cfe/trunk/test/Analysis/ctor.mm (original)
+++ cfe/trunk/test/Analysis/ctor.mm Fri Aug 18 11:20:43 2017
@@ -704,3 +704,20 @@ namespace PR19579 {
 };
   }
 }
+
+namespace NoCrashOnEmptyBaseOptimization {
+  struct NonEmptyBase {
+int X;
+explicit NonEmptyBase(int X) : X(X) {}
+  };
+
+  struct EmptyBase {};
+
+  struct S : NonEmptyBase, EmptyBase {
+S() : NonEmptyBase(0), EmptyBase() {}
+  };
+
+  void testSCtorNoCrash() {
+S s;
+  }
+}


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


Re: r311182 - [analyzer] Fix modeling of constructors

2017-08-21 Thread Alexander Shaposhnikov via cfe-commits
Thanks!

On Mon, Aug 21, 2017 at 1:28 PM, Hans Wennborg via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Merged in r311378.
>
> Thanks,
> Hans
>
> On Mon, Aug 21, 2017 at 1:12 PM, Anna Zaks  wrote:
> > I approve.Thanks Hans!
> > Anna
> >> On Aug 21, 2017, at 1:05 PM, Hans Wennborg  wrote:
> >>
> >> I'm ok with it if Anna approves.
> >>
> >> On Mon, Aug 21, 2017 at 9:06 AM, Artem Dergachev 
> wrote:
> >>> Hello,
> >>>
> >>> Do we have time to merge this change into release 5.0.0? It's an
> assertion
> >>> failure fix, which shows up on C++ code involving double-inheritance
> with
> >>> empty base classes.
> >>>
> >>> Artem.
> >>>
> >>>
> >>> On 8/18/17 9:20 PM, Alexander Shaposhnikov via cfe-commits wrote:
> >>>>
> >>>> Author: alexshap
> >>>> Date: Fri Aug 18 11:20:43 2017
> >>>> New Revision: 311182
> >>>>
> >>>> URL:http://llvm.org/viewvc/llvm-project?rev=311182&view=rev
> >>>> Log:
> >>>> [analyzer] Fix modeling of constructors
> >>>>
> >>>> This diff fixes analyzer's crash (triggered assert) on the newly added
> >>>> test case.
> >>>> The assert being discussed is assert(!B.lookup(R, BindingKey::Direct))
> >>>> in lib/StaticAnalyzer/Core/RegionStore.cpp, however the root cause is
> >>>> different.
> >>>> For classes with empty bases the offsets might be tricky.
> >>>> For example, let's assume we have
> >>>>  struct S: NonEmptyBase, EmptyBase {
> >>>>  ...
> >>>>  };
> >>>> In this case Clang applies empty base class optimization and
> >>>> the offset of EmptyBase will be 0, it can be verified via
> >>>> clang -cc1 -x c++ -v -fdump-record-layouts main.cpp -emit-llvm -o
> >>>> /dev/null.
> >>>> When the analyzer tries to perform zero initialization of EmptyBase
> >>>> it will hit the assert because that region
> >>>> has already been "written" by the constructor of NonEmptyBase.
> >>>>
> >>>> Test plan:
> >>>> make check-all
> >>>>
> >>>> Differential revision:https://reviews.llvm.org/D36851
> >>>>
> >>>> Modified:
> >>>> cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
> >>>> cfe/trunk/test/Analysis/ctor.mm
> >>>>
> >>>> Modified: cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
> >>>>
> >>>> URL:http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/
> StaticAnalyzer/Core/RegionStore.cpp?rev=311182&r1=
> 311181&r2=311182&view=diff
> >>>>
> >>>> 
> ==
> >>>> --- cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp (original)
> >>>> +++ cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp Fri Aug 18
> 11:20:43
> >>>> 2017
> >>>> @@ -409,6 +409,19 @@ public: // Part of public interface to c
> >>>>  // BindDefault is only used to initialize a region with a default
> >>>> value.
> >>>>StoreRef BindDefault(Store store, const MemRegion *R, SVal V)
> override
> >>>> {
> >>>> +// FIXME: The offsets of empty bases can be tricky because of
> >>>> +// of the so called "empty base class optimization".
> >>>> +// If a base class has been optimized out
> >>>> +// we should not try to create a binding, otherwise we should.
> >>>> +// Unfortunately, at the moment ASTRecordLayout doesn't expose
> >>>> +// the actual sizes of the empty bases
> >>>> +// and trying to infer them from offsets/alignments
> >>>> +// seems to be error-prone and non-trivial because of the
> trailing
> >>>> padding.
> >>>> +// As a temporary mitigation we don't create bindings for empty
> >>>> bases.
> >>>> +if (R->getKind() == MemRegion::CXXBaseObjectRegionKind &&
> >>>> +cast(R)->getDecl()->isEmpty())
> >>>> +  return StoreRef(store, *this);
> >>>> +
> >>>>  RegionBindingsRef B = getRegionBindings(store);
> >>>>

[clang-tools-extra] 90d42b1 - [clang-tidy] Skip private default ctors in modernize-use-equals-default

2022-10-20 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-10-20T22:04:33Z
New Revision: 90d42b1cab04b76e9e934f1e5076f014d1195e72

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

LOG: [clang-tidy] Skip private default ctors in modernize-use-equals-default

For c++17 (i.e. before c++20) making a private default ctor explicitly defaulted
might expose the previously intentionally disallowed initializations, e.g.
class Tag { Tag() {} friend class Widget; }; is not equivalent to
class Tag { Tag() = default; friend class Widget; };
since in the latter case Tag is treated as an aggregate despite having a 
declaration
of the default constructor. This diff makes modernize-use-equals-default skip
in-class empty nonpublic default ctors to avoid code breakages.

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D136224

Added: 

clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx17.cpp

clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx20.cpp

Modified: 
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
index 165840b72e7aa..e72ea76114783 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
@@ -217,6 +217,10 @@ void 
UseEqualsDefaultCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
   Options.store(Opts, "IgnoreMacros", IgnoreMacros);
 }
 
+namespace {
+AST_MATCHER(CXXMethodDecl, isOutOfLine) { return Node.isOutOfLine(); }
+} // namespace
+
 void UseEqualsDefaultCheck::registerMatchers(MatchFinder *Finder) {
   // Skip unions/union-like classes since their constructors behave 
diff erently
   // when defaulted vs. empty.
@@ -224,6 +228,12 @@ void UseEqualsDefaultCheck::registerMatchers(MatchFinder 
*Finder) {
   anyOf(isUnion(),
 has(fieldDecl(isImplicit(), hasType(cxxRecordDecl(isUnion()));
 
+  const LangOptions &LangOpts = getLangOpts();
+  auto IsPublicOrOutOfLineUntilCPP20 =
+  LangOpts.CPlusPlus20
+  ? cxxConstructorDecl()
+  : cxxConstructorDecl(anyOf(isOutOfLine(), isPublic()));
+
   // Destructor.
   Finder->addMatcher(
   cxxDestructorDecl(unless(hasParent(IsUnionLikeClass)), isDefinition())
@@ -235,7 +245,8 @@ void UseEqualsDefaultCheck::registerMatchers(MatchFinder 
*Finder) {
   anyOf(
   // Default constructor.
   allOf(unless(hasAnyConstructorInitializer(isWritten())),
-unless(isVariadic()), parameterCountIs(0)),
+unless(isVariadic()), parameterCountIs(0),
+IsPublicOrOutOfLineUntilCPP20),
   // Copy constructor.
   allOf(isCopyConstructor(),
 // Discard constructors that can be used as a copy

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 735fedbce5496..68995a9d3f190 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -158,7 +158,8 @@ Changes in existing checks
   The check now skips unions/union-like classes since in this case a default 
constructor
   with empty body is not equivalent to the explicitly defaulted one, variadic 
constructors
   since they cannot be explicitly defaulted. The check also skips copy 
assignment operators
-  with nonstandard return types. The check is restricted to c++11-or-later.
+  with nonstandard return types, private/protected default constructors for 
C++17 or earlier.
+  The check is restricted to C++11 or later.
 
 - Change the default behavior of :doc:`readability-avoid-const-params-in-decls
   ` to not

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx17.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx17.cpp
new file mode 100644
index 0..3bbc6296816b1
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx17.cpp
@@ -0,0 +1,17 @@
+// RUN: %check_clang_tidy -std=c++17 %s modernize-use-equals-default %t -- -- 
-fno-delayed-template-parsing -fexceptions
+
+// Private constructor/destructor.
+class Priv {
+  Priv() {}
+  ~Priv() {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use '= default'
+  // CHECK-FIXES: ~Priv() = default;
+};
+
+class PrivOutOfLine {
+  PrivOutOfLine();
+};
+
+PrivOutOfLine::PrivOutOfLine() {}
+// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: use '= defau

[clang-tools-extra] 6c07bda - [clang-tidy] Avoid adding unnecessary semicolon in modernize-use-equals-default

2022-10-21 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-10-22T00:42:50Z
New Revision: 6c07bda7a75c68aa14a1e5f1ca0eac9ba6220cbb

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

LOG: [clang-tidy] Avoid adding unnecessary semicolon in 
modernize-use-equals-default

Adjust the automatic fixit to avoid adding superfluous semicolon.

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D136399

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
index e72ea76114783..60e0f80da2878 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
@@ -337,10 +337,13 @@ void UseEqualsDefaultCheck::check(const 
MatchFinder::MatchResult &Result) {
   Diag << MemberType;
 
   if (ApplyFix) {
+SourceLocation UnifiedEnd = utils::lexer::getUnifiedEndLoc(
+*Body, Result.Context->getSourceManager(),
+Result.Context->getLangOpts());
 // Skipping comments, check for a semicolon after Body->getSourceRange()
 Optional Token = utils::lexer::findNextTokenSkippingComments(
-Body->getSourceRange().getEnd().getLocWithOffset(1),
-Result.Context->getSourceManager(), Result.Context->getLangOpts());
+UnifiedEnd, Result.Context->getSourceManager(),
+Result.Context->getLangOpts());
 StringRef Replacement =
 Token && Token->is(tok::semi) ? "= default" : "= default;";
 Diag << FixItHint::CreateReplacement(Body->getSourceRange(), Replacement)

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 68995a9d3f190..d7ae8dfdcf364 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -159,6 +159,7 @@ Changes in existing checks
   with empty body is not equivalent to the explicitly defaulted one, variadic 
constructors
   since they cannot be explicitly defaulted. The check also skips copy 
assignment operators
   with nonstandard return types, private/protected default constructors for 
C++17 or earlier.
+  The automatic fixit has been adjusted to avoid adding superfluous semicolon.
   The check is restricted to C++11 or later.
 
 - Change the default behavior of :doc:`readability-avoid-const-params-in-decls

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
index 6482c3a82241e..7a21ebe439cc1 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
@@ -91,7 +91,7 @@ class CM {
 // Private constructor/destructor.
 class Priv {
   Priv();
-  ~Priv() {};
+  ~Priv() {}
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use '= default'
   // CHECK-FIXES: ~Priv() = default;
 };
@@ -100,14 +100,28 @@ Priv::Priv() {}
 // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use '= default'
 // CHECK-FIXES: Priv::Priv() = default;
 
+struct SemiColon {
+  SemiColon() {};
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use '= default'
+  // CHECK-FIXES: SemiColon() = default;{{$}}
+};
+
+struct SemiColonOutOfLine {
+  SemiColonOutOfLine();
+};
+
+SemiColonOutOfLine::SemiColonOutOfLine() {};
+// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: use '= default'
+// CHECK-FIXES: SemiColonOutOfLine::SemiColonOutOfLine() = default;{{$}}
+
 // struct.
 struct ST {
   ST() {}
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use '= default'
-  // CHECK-FIXES: ST() = default;
+  // CHECK-FIXES: ST() = default;{{$}}
   ~ST() {}
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use '= default'
-  // CHECK-FIXES: ST() = default;
+  // CHECK-FIXES: ST() = default;{{$}}
 };
 
 // Deleted constructor/destructor.
@@ -200,7 +214,13 @@ struct DC : KW {
   DC() : KW() {}
   ~DC() override {}
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use '= default'
-  // CHECK-FIXES: ~DC() override = default;
+  // CHECK-FIXES: ~DC() override = default;{{$}}
+};
+
+struct OverrideWithSemiColon : KW {
+  ~OverrideWithSemiColon() override {};
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use '= default'
+  // CHECK-FIXES: ~OverrideWithSemiColon() override = default;{{$}}
 };
 
 struct Comments {



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


[clang-tools-extra] 29e4606 - [clang-tidy] Skip template ctors in modernize-use-equals-default

2022-10-27 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-10-28T05:30:19Z
New Revision: 29e4606ced7284c87a88fdcd34a6d179a1350fe9

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

LOG: [clang-tidy] Skip template ctors in modernize-use-equals-default

Skip template ctors in modernize-use-equals-default,
such constructors may be enabled/disabled via SFINAE,
it is not safe to make them "= default".

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D136797

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
index 60e0f80da2878..a545fae26a3bb 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
@@ -241,7 +241,9 @@ void UseEqualsDefaultCheck::registerMatchers(MatchFinder 
*Finder) {
   this);
   Finder->addMatcher(
   cxxConstructorDecl(
-  unless(hasParent(IsUnionLikeClass)), isDefinition(),
+  unless(
+  hasParent(decl(anyOf(IsUnionLikeClass, 
functionTemplateDecl(),
+  isDefinition(),
   anyOf(
   // Default constructor.
   allOf(unless(hasAnyConstructorInitializer(isWritten())),
@@ -257,8 +259,9 @@ void UseEqualsDefaultCheck::registerMatchers(MatchFinder 
*Finder) {
   this);
   // Copy-assignment operator.
   Finder->addMatcher(
-  cxxMethodDecl(unless(hasParent(IsUnionLikeClass)), isDefinition(),
-isCopyAssignmentOperator(),
+  cxxMethodDecl(unless(hasParent(
+decl(anyOf(IsUnionLikeClass, 
functionTemplateDecl(),
+isDefinition(), isCopyAssignmentOperator(),
 // isCopyAssignmentOperator() allows the parameter to be
 // passed by value, and in this case it cannot be
 // defaulted.

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index d7ae8dfdcf364..c5cc967259afe 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -158,9 +158,9 @@ Changes in existing checks
   The check now skips unions/union-like classes since in this case a default 
constructor
   with empty body is not equivalent to the explicitly defaulted one, variadic 
constructors
   since they cannot be explicitly defaulted. The check also skips copy 
assignment operators
-  with nonstandard return types, private/protected default constructors for 
C++17 or earlier.
-  The automatic fixit has been adjusted to avoid adding superfluous semicolon.
-  The check is restricted to C++11 or later.
+  with nonstandard return types, template constructors, private/protected 
default constructors
+  for C++17 or earlier. The automatic fixit has been adjusted to avoid adding 
superfluous
+  semicolon. The check is restricted to C++11 or later.
 
 - Change the default behavior of :doc:`readability-avoid-const-params-in-decls
   ` to not

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
index 7a21ebe439cc1..cc5d379b3c3de 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
@@ -58,6 +58,18 @@ struct VA {
   VA(...) {}
 };
 
+// Skip template constructors.
+struct TC {
+  template 
+  TC() {}
+
+  template 
+  TC(const TC &) {}
+
+  template 
+  TC& operator = (const TC &) { return *this; }
+};
+
 // Initializer or arguments.
 class IA {
 public:



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


[clang] d68ba43 - [Intrinsics] Add initial support for NonNull attribute

2022-08-16 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-08-16T21:28:23Z
New Revision: d68ba43ad24791181280fdb0f34b6be380db7a32

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

LOG: [Intrinsics] Add initial support for NonNull attribute

Add initial support for NonNull attribute.
(https://github.com/llvm/llvm-project/issues/57113)

Test plan:

verify that for
__thread int x;
int main() {

int* y = &x;
return *y;
}
(with this patch) clang -O -fsanitize=null -S -emit-llvm -o -
doesn't emit a null-pointer check

Differential revision: https://reviews.llvm.org/D131872

Added: 


Modified: 
clang/test/CodeGenCXX/threadlocal_address.cpp
llvm/include/llvm/IR/Intrinsics.td
llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86.mir
llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86_64.mir
llvm/test/CodeGen/X86/threadlocal_address.ll
llvm/utils/TableGen/CodeGenIntrinsics.h
llvm/utils/TableGen/CodeGenTarget.cpp
llvm/utils/TableGen/IntrinsicEmitter.cpp

Removed: 




diff  --git a/clang/test/CodeGenCXX/threadlocal_address.cpp 
b/clang/test/CodeGenCXX/threadlocal_address.cpp
index a55b1ee6e08de..625db30dd0e7b 100644
--- a/clang/test/CodeGenCXX/threadlocal_address.cpp
+++ b/clang/test/CodeGenCXX/threadlocal_address.cpp
@@ -20,11 +20,11 @@ int g() {
 // CHECK-NEXT: %[[RET:.+]] = load i32, ptr %[[IA2]], align 4
 // CHECK-NEXT: ret i32 %[[RET]]
 //
-// CHECK: declare ptr @llvm.threadlocal.address.p0(ptr) #[[ATTR_NUM:.+]]
+// CHECK: declare nonnull ptr @llvm.threadlocal.address.p0(ptr nonnull) 
#[[ATTR_NUM:.+]]
 //
 // CHECK-O1-LABEL: @_Z1gv
 // CHECK-O1-NEXT: entry:
-// CHECK-O1-NEXT:   %[[I_ADDR:.+]] = {{.*}}call ptr 
@llvm.threadlocal.address.p0(ptr nonnull @i)
+// CHECK-O1-NEXT:   %[[I_ADDR:.+]] = {{.*}}call ptr 
@llvm.threadlocal.address.p0(ptr @i)
 // CHECK-O1-NEXT:   %[[VAL:.+]] = load i32, ptr %[[I_ADDR]]
 // CHECK-O1-NEXT:   %[[INC:.+]] = add nsw i32 %[[VAL]], 1
 // CHECK-O1-NEXT:   store i32 %[[INC]], ptr %[[I_ADDR]]
@@ -56,7 +56,7 @@ int f() {
 //
 // CHECK-O1-LABEL: @_Z1fv
 // CHECK-O1-NEXT: entry:
-// CHECK-O1-NEXT:   %[[J_ADDR:.+]] = {{.*}}call ptr 
@llvm.threadlocal.address.p0(ptr nonnull @_ZZ1fvE1j)
+// CHECK-O1-NEXT:   %[[J_ADDR:.+]] = {{.*}}call ptr 
@llvm.threadlocal.address.p0(ptr @_ZZ1fvE1j)
 // CHECK-O1-NEXT:   %[[VAL:.+]] = load i32, ptr %[[J_ADDR]]
 // CHECK-O1-NEXT:   %[[INC:.+]] = add nsw i32 %[[VAL]], 1
 // CHECK-O1-NEXT:   store i32 %[[INC]], ptr %[[J_ADDR]]

diff  --git a/llvm/include/llvm/IR/Intrinsics.td 
b/llvm/include/llvm/IR/Intrinsics.td
index 2fb29a4f3eb9d..8a04c495edb11 100644
--- a/llvm/include/llvm/IR/Intrinsics.td
+++ b/llvm/include/llvm/IR/Intrinsics.td
@@ -84,6 +84,11 @@ class NoUndef : IntrinsicProperty {
   int ArgNo = idx.Value;
 }
 
+// NonNull - The specified argument is not null.
+class NonNull : IntrinsicProperty {
+  int ArgNo = idx.Value;
+}
+
 class Align : IntrinsicProperty {
   int ArgNo = idx.Value;
   int Align = align;
@@ -1407,7 +1412,8 @@ def int_ptrmask: DefaultAttrsIntrinsic<[llvm_anyptr_ty], 
[LLVMMatchType<0>, llvm
 
 // Intrinsic to wrap a thread local variable.
 def int_threadlocal_address : DefaultAttrsIntrinsic<[llvm_anyptr_ty], 
[LLVMMatchType<0>],
-   [IntrNoMem, IntrSpeculatable, IntrWillReturn]>;
+[NonNull, 
NonNull>,
+ IntrNoMem, 
IntrSpeculatable, IntrWillReturn]>;
 
 def int_experimental_stepvector : DefaultAttrsIntrinsic<[llvm_anyvector_ty],
 [], [IntrNoMem]>;

diff  --git a/llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86.mir 
b/llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86.mir
index 8d03401df9cfd..6dce371138e94 100644
--- a/llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86.mir
+++ b/llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86.mir
@@ -33,7 +33,7 @@
   }
 
   ; Function Attrs: nocallback nofree nosync nounwind readnone speculatable 
willreturn
-  declare ptr @llvm.threadlocal.address.p0(ptr) #0
+  declare nonnull ptr @llvm.threadlocal.address.p0(ptr nonnull) #0
 
   attributes #0 = { nocallback nofree nosync nounwind readnone speculatable 
willreturn }
 

diff  --git a/llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86_64.mir 
b/llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86_64.mir
index dadd1be16c5b9..afc9ff5374de5 100644
--- a/llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86_64.mir
+++ b/llvm/test/CodeGen/X86/peephole-nofold-tpoff-x86_64.mir
@@ -23,7 +23,7 @@
   }
 
   ; Function Attrs: nocallback nofree nosync nounwind readnone speculatable 
willreturn
-  declare ptr @llvm.threadlocal.address.p0(ptr) #0
+  declare nonnull ptr @llvm.threadlocal.address.p0(ptr nonnull) #0
 
   attributes #0 = { nocallback nofree nosync nounwind readnone

[clang-tools-extra] 083e3a1 - [clang-tidy] Skip unions in use-equals-default

2022-08-23 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-08-23T20:09:47Z
New Revision: 083e3a173d9e9d71733e0445e6f4a93e7f918dfa

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

LOG: [clang-tidy] Skip unions in use-equals-default

For unions constructors with empty bodies behave differently
(in comparison with structs/classes) and clang-tidy's fix
might break the code. This diff adjusts the check to skip unions
for now (it seems to be a relatively rare case).

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D132290

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
index c3e3759af32fd..f321c0b2e693d 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
@@ -217,12 +217,17 @@ void 
UseEqualsDefaultCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
 }
 
 void UseEqualsDefaultCheck::registerMatchers(MatchFinder *Finder) {
+  // Skip unions since constructors with empty bodies behave 
diff erently
+  // in comparison with structs/classes.
+
   // Destructor.
-  Finder->addMatcher(cxxDestructorDecl(isDefinition()).bind(SpecialFunction),
+  
Finder->addMatcher(cxxDestructorDecl(unless(hasParent(recordDecl(isUnion(,
+   isDefinition())
+ .bind(SpecialFunction),
  this);
   Finder->addMatcher(
   cxxConstructorDecl(
-  isDefinition(),
+  unless(hasParent(recordDecl(isUnion(, isDefinition(),
   anyOf(
   // Default constructor.
   allOf(unless(hasAnyConstructorInitializer(isWritten())),
@@ -237,7 +242,8 @@ void UseEqualsDefaultCheck::registerMatchers(MatchFinder 
*Finder) {
   this);
   // Copy-assignment operator.
   Finder->addMatcher(
-  cxxMethodDecl(isDefinition(), isCopyAssignmentOperator(),
+  cxxMethodDecl(unless(hasParent(recordDecl(isUnion(, isDefinition(),
+isCopyAssignmentOperator(),
 // isCopyAssignmentOperator() allows the parameter to be
 // passed by value, and in this case it cannot be
 // defaulted.

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 9e5e176336468..fbe47316d23ae 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -127,6 +127,11 @@ Changes in existing checks
   ``push_front`` on STL-style containers and replacing them with ``emplace``
   or ``emplace_front``.
 
+- Improved `modernize-use-equals-default 
`_ check.
+
+  The check now skips unions since in this case a default constructor with 
empty body
+  is not equivalent to the explicitly defaulted one.
+
 Removed checks
 ^^
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
index 429e72497b1b4..78a03f02eed52 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
@@ -32,6 +32,18 @@ struct IL {
   int Field;
 };
 
+// Skip unions.
+union NU {
+  NU(const NU &Other) : Field(Other.Field) {}
+  // CHECK-FIXES: NU(const NU &Other) :
+  NU &operator=(const NU &Other) {
+Field = Other.Field;
+return *this;
+  }
+  // CHECK-FIXES: NU &operator=(const NU &Other) {
+  IL Field;
+};
+
 // Wrong type.
 struct WT {
   WT(const IL &Other) {}

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
index 40311a1435dd4..1de4957ceb1b9 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
@@ -33,6 +33,15 @@ class NE {
   ~NE() { f(); }
 };
 
+// Skip unions.
+union NU {
+  NU() {}
+  // CHECK-FIXES: NU() {}
+  ~NU() {}
+  // CHECK-FIXES: ~NU() {}
+  NE Field;
+};
+
 // Initializer or arguments.
 class IA {
 public:



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

[clang-tools-extra] d4e8109 - [clang-tidy] Skip variadic ctors in modernize-use-equals-default

2022-09-30 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-09-30T22:16:28Z
New Revision: d4e81097ea3daf37b5480281a17ad5b20cd7ee8d

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

LOG: [clang-tidy] Skip variadic ctors in modernize-use-equals-default

Skip variadic constructors in modernize-use-equals-default
(such constructors cannot be explicitly defaulted).

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D134929

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
index d5c402c4bdeb7..165840b72e7aa 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
@@ -235,7 +235,7 @@ void UseEqualsDefaultCheck::registerMatchers(MatchFinder 
*Finder) {
   anyOf(
   // Default constructor.
   allOf(unless(hasAnyConstructorInitializer(isWritten())),
-parameterCountIs(0)),
+unless(isVariadic()), parameterCountIs(0)),
   // Copy constructor.
   allOf(isCopyConstructor(),
 // Discard constructors that can be used as a copy

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 9447cbfba73e0..8e65ed214a21d 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -145,9 +145,9 @@ Changes in existing checks
   check.
 
   The check now skips unions/union-like classes since in this case a default 
constructor
-  with empty body is not equivalent to the explicitly defaulted one. The check 
also skips
-  copy assignment operators with nonstandard return types. The check is 
restricted to
-  c++11-or-later.
+  with empty body is not equivalent to the explicitly defaulted one, variadic 
constructors
+  since they cannot be explicitly defaulted. The check also skips copy 
assignment operators
+  with nonstandard return types. The check is restricted to c++11-or-later.
 
 - Change the default behavior of :doc:`readability-avoid-const-params-in-decls
   ` to not

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
index ba252792cf3a6..493cfa21a8371 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default.cpp
@@ -53,6 +53,11 @@ struct SU {
   };
 };
 
+// Skip variadic constructors.
+struct VA {
+  VA(...) {}
+};
+
 // Initializer or arguments.
 class IA {
 public:



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


[clang] ef9e624 - [opt][clang] Enable using -module-summary/-flto=thin with -S/-emit-llvm

2022-11-14 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-11-14T21:11:07Z
New Revision: ef9e624694c0f125c53f7d0d3472fd486bada57d

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

LOG: [opt][clang] Enable using -module-summary/-flto=thin with -S/-emit-llvm

Enable using -module-summary with -S
(similarly to what currently can be achieved with opt  -o - | llvm-dis).

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D137768

Added: 


Modified: 
clang/lib/CodeGen/BackendUtil.cpp
clang/test/CodeGen/split-lto-unit.c
llvm/include/llvm/IR/IRPrintingPasses.h
llvm/lib/IR/CMakeLists.txt
llvm/lib/IR/IRPrintingPasses.cpp
llvm/test/Bitcode/thinlto-function-summary.ll
llvm/tools/opt/NewPMDriver.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 41f9ce3a009da..26633f8007037 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -978,19 +978,24 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
 MPM.addPass(VerifierPass());
 
-  switch (Action) {
-  case Backend_EmitBC:
+  if (Action == Backend_EmitBC || Action == Backend_EmitLL) {
 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
-  if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
-ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
-if (!ThinLinkOS)
-  return;
-  }
   if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  CodeGenOpts.EnableSplitLTOUnit);
-  MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
-   : nullptr));
+  if (Action == Backend_EmitBC) {
+if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
+  ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
+  if (!ThinLinkOS)
+return;
+}
+MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? 
&ThinLinkOS->os()
+ : nullptr));
+  } else {
+MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
+true /* EmitLTOSummary */));
+  }
+
 } else {
   // Emit a module summary by default for Regular LTO except for ld64
   // targets
@@ -1002,17 +1007,13 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
uint32_t(1));
   }
-  MPM.addPass(
-  BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, 
EmitLTOSummary));
+  if (Action == Backend_EmitBC)
+MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
+  EmitLTOSummary));
+  else
+MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
+EmitLTOSummary));
 }
-break;
-
-  case Backend_EmitLL:
-MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
-break;
-
-  default:
-break;
   }
 
   // Now that we have all of the passes ready, run them.

diff  --git a/clang/test/CodeGen/split-lto-unit.c 
b/clang/test/CodeGen/split-lto-unit.c
index 941aebafd01b3..b1560b61f3e30 100644
--- a/clang/test/CodeGen/split-lto-unit.c
+++ b/clang/test/CodeGen/split-lto-unit.c
@@ -1,12 +1,15 @@
 // ; Check that -flto=thin without -fsplit-lto-unit has EnableSplitLTOUnit = 0
 // RUN: %clang_cc1 -flto=thin -emit-llvm-bc < %s | llvm-dis -o - | FileCheck %s
+// RUN: %clang_cc1 -flto=thin -emit-llvm < %s | FileCheck %s
 // CHECK: !{i32 1, !"EnableSplitLTOUnit", i32 0}
 //
 // ; Check that -flto=thin with -fsplit-lto-unit has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm-bc < %s | llvm-dis 
-o - | FileCheck %s --check-prefix=SPLIT
+// RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm < %s | FileCheck %s 
--check-prefix=SPLIT
 // SPLIT: !{i32 1, !"EnableSplitLTOUnit", i32 1}
 //
 // ; Check that regular LTO has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm-bc < %s | 
llvm-dis -o - | FileCheck %s --implicit-check-not="EnableSplitLTOUnit" 
--check-prefix=SPLIT
+// RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm < %s | 
FileCheck %s --implicit-check-not="EnableSplitLTOUnit" --check-prefix=SPLIT
 
 int main(void) {}

diff  --git a/llvm/include/llvm/IR/IRPrintingPasses.h 
b/llvm/include/llvm/IR/IRPrintingPasses.h
index 3fba5b81e37a9..5f4880643c52d 100644
--- a/llvm/include/llv

[clang] 8c15c17 - Revert "[opt][clang] Enable using -module-summary/-flto=thin with -S/-emit-llvm"

2022-11-14 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-11-14T21:31:30Z
New Revision: 8c15c17e3ba7916b2efb2a100495c710bae04fb6

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

LOG: Revert "[opt][clang] Enable using -module-summary/-flto=thin with 
-S/-emit-llvm"

This reverts commit ef9e624694c0f125c53f7d0d3472fd486bada57d
for further investigation offline.
It appears to break the buildbot
llvm-clang-x86_64-sie-ubuntu-fast.

Added: 


Modified: 
clang/lib/CodeGen/BackendUtil.cpp
clang/test/CodeGen/split-lto-unit.c
llvm/include/llvm/IR/IRPrintingPasses.h
llvm/lib/IR/CMakeLists.txt
llvm/lib/IR/IRPrintingPasses.cpp
llvm/test/Bitcode/thinlto-function-summary.ll
llvm/tools/opt/NewPMDriver.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 26633f8007037..41f9ce3a009da 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -978,24 +978,19 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
 MPM.addPass(VerifierPass());
 
-  if (Action == Backend_EmitBC || Action == Backend_EmitLL) {
+  switch (Action) {
+  case Backend_EmitBC:
 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
+  if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
+ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
+if (!ThinLinkOS)
+  return;
+  }
   if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  CodeGenOpts.EnableSplitLTOUnit);
-  if (Action == Backend_EmitBC) {
-if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
-  ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
-  if (!ThinLinkOS)
-return;
-}
-MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? 
&ThinLinkOS->os()
- : nullptr));
-  } else {
-MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
-true /* EmitLTOSummary */));
-  }
-
+  MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
+   : nullptr));
 } else {
   // Emit a module summary by default for Regular LTO except for ld64
   // targets
@@ -1007,13 +1002,17 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
uint32_t(1));
   }
-  if (Action == Backend_EmitBC)
-MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
-  EmitLTOSummary));
-  else
-MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
-EmitLTOSummary));
+  MPM.addPass(
+  BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, 
EmitLTOSummary));
 }
+break;
+
+  case Backend_EmitLL:
+MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
+break;
+
+  default:
+break;
   }
 
   // Now that we have all of the passes ready, run them.

diff  --git a/clang/test/CodeGen/split-lto-unit.c 
b/clang/test/CodeGen/split-lto-unit.c
index b1560b61f3e30..941aebafd01b3 100644
--- a/clang/test/CodeGen/split-lto-unit.c
+++ b/clang/test/CodeGen/split-lto-unit.c
@@ -1,15 +1,12 @@
 // ; Check that -flto=thin without -fsplit-lto-unit has EnableSplitLTOUnit = 0
 // RUN: %clang_cc1 -flto=thin -emit-llvm-bc < %s | llvm-dis -o - | FileCheck %s
-// RUN: %clang_cc1 -flto=thin -emit-llvm < %s | FileCheck %s
 // CHECK: !{i32 1, !"EnableSplitLTOUnit", i32 0}
 //
 // ; Check that -flto=thin with -fsplit-lto-unit has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm-bc < %s | llvm-dis 
-o - | FileCheck %s --check-prefix=SPLIT
-// RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm < %s | FileCheck %s 
--check-prefix=SPLIT
 // SPLIT: !{i32 1, !"EnableSplitLTOUnit", i32 1}
 //
 // ; Check that regular LTO has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm-bc < %s | 
llvm-dis -o - | FileCheck %s --implicit-check-not="EnableSplitLTOUnit" 
--check-prefix=SPLIT
-// RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm < %s | 
FileCheck %s --implicit-check-not="EnableSplitLTOUnit" --check-prefix=SPLIT
 
 int main(void) {}

diff  --git a/llvm/include/llvm/IR/IRPrintingPasses.h 
b/llvm/include/llvm/IR/IRPrintingPasses.h
index 5f4880643c52d..3fba5b81e37a9 100644
--- a/llvm/include/llvm/IR/IRPrintingPasses

[clang] bf8381a - [opt][clang] Enable using -module-summary/-flto=thin with -S/-emit-llvm

2022-11-14 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-11-14T23:24:08Z
New Revision: bf8381a8bce28fc69857645cc7e84a72317e693e

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

LOG: [opt][clang] Enable using -module-summary/-flto=thin with -S/-emit-llvm

Enable using -module-summary with -S
(similarly to what currently can be achieved with opt  -o - | llvm-dis).
This is a recommit of ef9e62469.

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D137768

Added: 


Modified: 
clang/lib/CodeGen/BackendUtil.cpp
clang/test/CodeGen/split-lto-unit.c
llvm/include/llvm/IR/IRPrintingPasses.h
llvm/lib/Analysis/ModuleSummaryAnalysis.cpp
llvm/lib/IR/IRPrintingPasses.cpp
llvm/test/Bitcode/thinlto-function-summary.ll
llvm/tools/opt/NewPMDriver.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 41f9ce3a009da..26633f8007037 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -978,19 +978,24 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
 MPM.addPass(VerifierPass());
 
-  switch (Action) {
-  case Backend_EmitBC:
+  if (Action == Backend_EmitBC || Action == Backend_EmitLL) {
 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
-  if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
-ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
-if (!ThinLinkOS)
-  return;
-  }
   if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  CodeGenOpts.EnableSplitLTOUnit);
-  MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
-   : nullptr));
+  if (Action == Backend_EmitBC) {
+if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
+  ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
+  if (!ThinLinkOS)
+return;
+}
+MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? 
&ThinLinkOS->os()
+ : nullptr));
+  } else {
+MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
+true /* EmitLTOSummary */));
+  }
+
 } else {
   // Emit a module summary by default for Regular LTO except for ld64
   // targets
@@ -1002,17 +1007,13 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
uint32_t(1));
   }
-  MPM.addPass(
-  BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, 
EmitLTOSummary));
+  if (Action == Backend_EmitBC)
+MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
+  EmitLTOSummary));
+  else
+MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
+EmitLTOSummary));
 }
-break;
-
-  case Backend_EmitLL:
-MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
-break;
-
-  default:
-break;
   }
 
   // Now that we have all of the passes ready, run them.

diff  --git a/clang/test/CodeGen/split-lto-unit.c 
b/clang/test/CodeGen/split-lto-unit.c
index 941aebafd01b3..b1560b61f3e30 100644
--- a/clang/test/CodeGen/split-lto-unit.c
+++ b/clang/test/CodeGen/split-lto-unit.c
@@ -1,12 +1,15 @@
 // ; Check that -flto=thin without -fsplit-lto-unit has EnableSplitLTOUnit = 0
 // RUN: %clang_cc1 -flto=thin -emit-llvm-bc < %s | llvm-dis -o - | FileCheck %s
+// RUN: %clang_cc1 -flto=thin -emit-llvm < %s | FileCheck %s
 // CHECK: !{i32 1, !"EnableSplitLTOUnit", i32 0}
 //
 // ; Check that -flto=thin with -fsplit-lto-unit has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm-bc < %s | llvm-dis 
-o - | FileCheck %s --check-prefix=SPLIT
+// RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm < %s | FileCheck %s 
--check-prefix=SPLIT
 // SPLIT: !{i32 1, !"EnableSplitLTOUnit", i32 1}
 //
 // ; Check that regular LTO has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm-bc < %s | 
llvm-dis -o - | FileCheck %s --implicit-check-not="EnableSplitLTOUnit" 
--check-prefix=SPLIT
+// RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm < %s | 
FileCheck %s --implicit-check-not="EnableSplitLTOUnit" --check-prefix=SPLIT
 
 int main(void) {}

diff  --git a/llvm/include/llvm/IR/IRPrintingPasses.h 
b/llvm/include/llvm/IR/IRPrintingPasses.h
index 3fba5b81

[clang-tools-extra] 2483a7f - [include-cleaner] Fix the build of include-cleaner with LLVM_BUILD_LLVM_DYLIB=ON

2022-11-17 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-11-18T00:54:45Z
New Revision: 2483a7fffbdf8e04addfbbf9f333155edc2c0346

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

LOG: [include-cleaner] Fix the build of include-cleaner with 
LLVM_BUILD_LLVM_DYLIB=ON

Added: 


Modified: 
clang-tools-extra/include-cleaner/tool/CMakeLists.txt

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/tool/CMakeLists.txt 
b/clang-tools-extra/include-cleaner/tool/CMakeLists.txt
index 3fc8c44081cd2..3b9b03141ce1b 100644
--- a/clang-tools-extra/include-cleaner/tool/CMakeLists.txt
+++ b/clang-tools-extra/include-cleaner/tool/CMakeLists.txt
@@ -5,6 +5,7 @@ add_clang_tool(clang-include-cleaner IncludeCleaner.cpp)
 clang_target_link_libraries(clang-include-cleaner PRIVATE
   clangBasic
   clangFrontend
+  clangLex
   clangSerialization
   clangTooling
   )



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


[clang] 7059a6c - [IR] Split out IR printing passes into IRPrinter

2022-11-17 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-11-18T01:47:56Z
New Revision: 7059a6c32cfad8f272fad47265e3890cd7a1a7e1

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

LOG: [IR] Split out IR printing passes into IRPrinter

This diff splits out (from LLVMCore) IR printing passes into IRPrinter.
This structure is similar to what we already have for IRReader and
enables us to avoid circular dependencies between LLVMCore and Analysis
(this is a preparation for https://reviews.llvm.org/D137768).
The legacy interface is left unchanged, once the legacy pass manager
is removed (in the future) we will be able to clean it up further.
The bazel build configuration has been updated as well.

Test plan:
1/ Tested the following cmake configurations: static/dynamic linking * lld/gold 
* clang/gcc
2/ bazel build --config=generic_clang @llvm-project//...

Differential revision: https://reviews.llvm.org/D138081

Added: 
llvm/include/llvm/IRPrinter/IRPrintingPasses.h
llvm/lib/IRPrinter/CMakeLists.txt
llvm/lib/IRPrinter/IRPrintingPasses.cpp

Modified: 
clang/lib/CodeGen/BackendUtil.cpp
clang/lib/CodeGen/CMakeLists.txt
llvm/include/llvm/CodeGen/CodeGenPassBuilder.h
llvm/include/llvm/IR/IRPrintingPasses.h
llvm/lib/CMakeLists.txt
llvm/lib/IR/IRPrintingPasses.cpp
llvm/lib/Passes/CMakeLists.txt
llvm/lib/Passes/PassBuilder.cpp
llvm/lib/Target/DirectX/DirectXTargetMachine.cpp
llvm/tools/llc/llc.cpp
llvm/tools/opt/CMakeLists.txt
llvm/tools/opt/NewPMDriver.cpp
utils/bazel/llvm-project-overlay/clang/BUILD.bazel
utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
utils/bazel/llvm-project-overlay/mlir/BUILD.bazel

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 8498ca2e63388..9c677140b4a5d 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -31,7 +31,7 @@
 #include "llvm/CodeGen/TargetSubtargetInfo.h"
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/DebugInfo.h"
-#include "llvm/IR/IRPrintingPasses.h"
+#include "llvm/IRPrinter/IRPrintingPasses.h"
 #include "llvm/IR/LegacyPassManager.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/ModuleSummaryIndex.h"

diff  --git a/clang/lib/CodeGen/CMakeLists.txt 
b/clang/lib/CodeGen/CMakeLists.txt
index a97042ee2008b..802c34b5b7e19 100644
--- a/clang/lib/CodeGen/CMakeLists.txt
+++ b/clang/lib/CodeGen/CMakeLists.txt
@@ -10,6 +10,7 @@ set(LLVM_LINK_COMPONENTS
   FrontendHLSL
   FrontendOpenMP
   IPO
+  IRPrinter
   IRReader
   AggressiveInstCombine
   InstCombine

diff  --git a/llvm/include/llvm/CodeGen/CodeGenPassBuilder.h 
b/llvm/include/llvm/CodeGen/CodeGenPassBuilder.h
index 15f46cf46ba7e..95625d13021eb 100644
--- a/llvm/include/llvm/CodeGen/CodeGenPassBuilder.h
+++ b/llvm/include/llvm/CodeGen/CodeGenPassBuilder.h
@@ -29,7 +29,7 @@
 #include "llvm/CodeGen/PreISelIntrinsicLowering.h"
 #include "llvm/CodeGen/ReplaceWithVeclib.h"
 #include "llvm/CodeGen/UnreachableBlockElim.h"
-#include "llvm/IR/IRPrintingPasses.h"
+#include "llvm/IRPrinter/IRPrintingPasses.h"
 #include "llvm/IR/PassManager.h"
 #include "llvm/IR/Verifier.h"
 #include "llvm/MC/MCAsmInfo.h"

diff  --git a/llvm/include/llvm/IR/IRPrintingPasses.h 
b/llvm/include/llvm/IR/IRPrintingPasses.h
index 3fba5b81e37a9..942e420a2d659 100644
--- a/llvm/include/llvm/IR/IRPrintingPasses.h
+++ b/llvm/include/llvm/IR/IRPrintingPasses.h
@@ -7,18 +7,14 @@
 
//===--===//
 /// \file
 ///
-/// This file defines passes to print out IR in various granularities. The
-/// PrintModulePass pass simply prints out the entire module when it is
-/// executed. The PrintFunctionPass class is designed to be pipelined with
-/// other FunctionPass's, and prints out the functions of the module as they
-/// are processed.
+/// This file contains an interface for creating legacy passes to print out IR
+/// in various granularities.
 ///
 
//===--===//
 
 #ifndef LLVM_IR_IRPRINTINGPASSES_H
 #define LLVM_IR_IRPRINTINGPASSES_H
 
-#include "llvm/IR/PassManager.h"
 #include 
 
 namespace llvm {
@@ -50,40 +46,6 @@ void printLLVMNameWithoutPrefix(raw_ostream &OS, StringRef 
Name);
 /// Return true if a pass is for IR printing.
 bool isIRPrintingPass(Pass *P);
 
-/// Pass for printing a Module as LLVM's text IR assembly.
-///
-/// Note: This pass is for use with the new pass manager. Use the create...Pass
-/// functions above to create passes for use with the legacy pass manager.
-class PrintModulePass : public PassInfoMixin {
-  raw_ostream &OS;
-  std::string Banner;
-  bool ShouldPreserveUseListOrder;
-
-public:
-  PrintModulePass();
-  PrintModulePass(raw_ostream &O

[clang] 34ab474 - [opt][clang] Enable using -module-summary/-flto=thin with -S/-emit-llvm

2022-11-17 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-11-18T05:04:07Z
New Revision: 34ab474348e2623cc67abddb7bb662385297ac65

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

LOG: [opt][clang] Enable using -module-summary/-flto=thin with -S/-emit-llvm

Enable using -module-summary with -S
(similarly to what currently can be achieved with opt  -o - | llvm-dis).
This is a recommit of ef9e62469.

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D137768

Added: 


Modified: 
clang/lib/CodeGen/BackendUtil.cpp
clang/test/CodeGen/split-lto-unit.c
llvm/include/llvm/IRPrinter/IRPrintingPasses.h
llvm/lib/IRPrinter/CMakeLists.txt
llvm/lib/IRPrinter/IRPrintingPasses.cpp
llvm/test/Bitcode/thinlto-function-summary.ll
llvm/tools/opt/NewPMDriver.cpp
utils/bazel/llvm-project-overlay/llvm/BUILD.bazel

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 9c677140b4a5d..d6a7a9800ec58 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -983,19 +983,24 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
 MPM.addPass(VerifierPass());
 
-  switch (Action) {
-  case Backend_EmitBC:
+  if (Action == Backend_EmitBC || Action == Backend_EmitLL) {
 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
-  if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
-ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
-if (!ThinLinkOS)
-  return;
-  }
   if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  CodeGenOpts.EnableSplitLTOUnit);
-  MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
-   : nullptr));
+  if (Action == Backend_EmitBC) {
+if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
+  ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
+  if (!ThinLinkOS)
+return;
+}
+MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? 
&ThinLinkOS->os()
+ : nullptr));
+  } else {
+MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
+/*EmitLTOSummary=*/true));
+  }
+
 } else {
   // Emit a module summary by default for Regular LTO except for ld64
   // targets
@@ -1007,17 +1012,13 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
uint32_t(1));
   }
-  MPM.addPass(
-  BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, 
EmitLTOSummary));
+  if (Action == Backend_EmitBC)
+MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
+  EmitLTOSummary));
+  else
+MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
+EmitLTOSummary));
 }
-break;
-
-  case Backend_EmitLL:
-MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
-break;
-
-  default:
-break;
   }
 
   // Now that we have all of the passes ready, run them.

diff  --git a/clang/test/CodeGen/split-lto-unit.c 
b/clang/test/CodeGen/split-lto-unit.c
index 941aebafd01b3..b1560b61f3e30 100644
--- a/clang/test/CodeGen/split-lto-unit.c
+++ b/clang/test/CodeGen/split-lto-unit.c
@@ -1,12 +1,15 @@
 // ; Check that -flto=thin without -fsplit-lto-unit has EnableSplitLTOUnit = 0
 // RUN: %clang_cc1 -flto=thin -emit-llvm-bc < %s | llvm-dis -o - | FileCheck %s
+// RUN: %clang_cc1 -flto=thin -emit-llvm < %s | FileCheck %s
 // CHECK: !{i32 1, !"EnableSplitLTOUnit", i32 0}
 //
 // ; Check that -flto=thin with -fsplit-lto-unit has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm-bc < %s | llvm-dis 
-o - | FileCheck %s --check-prefix=SPLIT
+// RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm < %s | FileCheck %s 
--check-prefix=SPLIT
 // SPLIT: !{i32 1, !"EnableSplitLTOUnit", i32 1}
 //
 // ; Check that regular LTO has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm-bc < %s | 
llvm-dis -o - | FileCheck %s --implicit-check-not="EnableSplitLTOUnit" 
--check-prefix=SPLIT
+// RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm < %s | 
FileCheck %s --implicit-check-not="EnableSplitLTOUnit" --check-prefix=SPLIT
 
 int main(void) {}

diff  --git a/llvm/include/llvm/IRPrinter/IRPrintingPas

[clang] f102fe7 - Revert "Revert "[opt][clang] Enable using -module-summary/-flto=thin with -S/-emit-llvm""

2022-11-18 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2022-11-18T08:58:31Z
New Revision: f102fe73044062542f022182381c17172a999db2

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

LOG: Revert "Revert "[opt][clang] Enable using -module-summary/-flto=thin with 
-S/-emit-llvm""

This reverts commit 7f608a2497c7578b9f3ca98014176ab95cffe3c0
and removes the dependency of Object on IRPrinter.

Added: 


Modified: 
clang/lib/CodeGen/BackendUtil.cpp
clang/test/CodeGen/split-lto-unit.c
llvm/include/llvm/IRPrinter/IRPrintingPasses.h
llvm/lib/IRPrinter/CMakeLists.txt
llvm/lib/IRPrinter/IRPrintingPasses.cpp
llvm/test/Bitcode/thinlto-function-summary.ll
llvm/tools/opt/NewPMDriver.cpp
utils/bazel/llvm-project-overlay/llvm/BUILD.bazel

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 9c677140b4a5d..d6a7a9800ec58 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -983,19 +983,24 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
 MPM.addPass(VerifierPass());
 
-  switch (Action) {
-  case Backend_EmitBC:
+  if (Action == Backend_EmitBC || Action == Backend_EmitLL) {
 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
-  if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
-ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
-if (!ThinLinkOS)
-  return;
-  }
   if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
  CodeGenOpts.EnableSplitLTOUnit);
-  MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
-   : nullptr));
+  if (Action == Backend_EmitBC) {
+if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
+  ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
+  if (!ThinLinkOS)
+return;
+}
+MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? 
&ThinLinkOS->os()
+ : nullptr));
+  } else {
+MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
+/*EmitLTOSummary=*/true));
+  }
+
 } else {
   // Emit a module summary by default for Regular LTO except for ld64
   // targets
@@ -1007,17 +1012,13 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
uint32_t(1));
   }
-  MPM.addPass(
-  BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, 
EmitLTOSummary));
+  if (Action == Backend_EmitBC)
+MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
+  EmitLTOSummary));
+  else
+MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists,
+EmitLTOSummary));
 }
-break;
-
-  case Backend_EmitLL:
-MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
-break;
-
-  default:
-break;
   }
 
   // Now that we have all of the passes ready, run them.

diff  --git a/clang/test/CodeGen/split-lto-unit.c 
b/clang/test/CodeGen/split-lto-unit.c
index 941aebafd01b3..b1560b61f3e30 100644
--- a/clang/test/CodeGen/split-lto-unit.c
+++ b/clang/test/CodeGen/split-lto-unit.c
@@ -1,12 +1,15 @@
 // ; Check that -flto=thin without -fsplit-lto-unit has EnableSplitLTOUnit = 0
 // RUN: %clang_cc1 -flto=thin -emit-llvm-bc < %s | llvm-dis -o - | FileCheck %s
+// RUN: %clang_cc1 -flto=thin -emit-llvm < %s | FileCheck %s
 // CHECK: !{i32 1, !"EnableSplitLTOUnit", i32 0}
 //
 // ; Check that -flto=thin with -fsplit-lto-unit has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm-bc < %s | llvm-dis 
-o - | FileCheck %s --check-prefix=SPLIT
+// RUN: %clang_cc1 -flto=thin -fsplit-lto-unit -emit-llvm < %s | FileCheck %s 
--check-prefix=SPLIT
 // SPLIT: !{i32 1, !"EnableSplitLTOUnit", i32 1}
 //
 // ; Check that regular LTO has EnableSplitLTOUnit = 1
 // RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm-bc < %s | 
llvm-dis -o - | FileCheck %s --implicit-check-not="EnableSplitLTOUnit" 
--check-prefix=SPLIT
+// RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm < %s | 
FileCheck %s --implicit-check-not="EnableSplitLTOUnit" --check-prefix=SPLIT
 
 int main(void) {}

diff  --git a/llvm/include/llvm/IRPrinter/IRPrintingPasses.h 
b/llvm/include/llvm/IRPrinter/IRPrintingPasses.h
index 6cfa7a87af933..8eb7973365172 100644

[clang] 0fd9c37 - [Clang] Treat `std::forward_like` as builtin

2023-01-28 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-01-29T00:13:46Z
New Revision: 0fd9c37d8cf20d1ee42263872ab2135265c3ac3d

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

LOG: [Clang] Treat `std::forward_like` as builtin

This diff extends D123345 by adding support for std::forward_like.

Test plan: ninja check-clang check-clang-tools check-llvm

Differential revision: https://reviews.llvm.org/D142430

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/Builtins.def
clang/lib/AST/ExprConstant.cpp
clang/lib/Analysis/BodyFarm.cpp
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/Sema/SemaChecking.cpp
clang/lib/Sema/SemaDecl.cpp
clang/test/CodeGenCXX/builtin-std-move.cpp
clang/test/SemaCXX/attr-lifetimebound.cpp
clang/test/SemaCXX/builtin-std-move-nobuiltin.cpp
clang/test/SemaCXX/builtin-std-move.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 28345f144fd33..4c72ec64f6e19 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -97,6 +97,9 @@ C2x Feature Support
 
 C++ Language Changes in Clang
 -
+- Improved ``-O0`` code generation for calls to ``std::forward_like``. 
Similarly to
+  ``std::move, std::forward`` et al. it is now treated as a compiler builtin 
and implemented
+  directly rather than instantiating the definition from the standard library.
 
 C++20 Feature Support
 ^

diff  --git a/clang/include/clang/Basic/Builtins.def 
b/clang/include/clang/Basic/Builtins.def
index 41f1245564465..6b54ff7c40e82 100644
--- a/clang/include/clang/Basic/Builtins.def
+++ b/clang/include/clang/Basic/Builtins.def
@@ -1565,6 +1565,7 @@ LIBBUILTIN(addressof, "v*v&", "zfncThE", MEMORY, CXX_LANG)
 LANGBUILTIN(__addressof, "v*v&", "zfncTE", CXX_LANG)
 LIBBUILTIN(as_const, "v&v&", "zfncThE", UTILITY, CXX_LANG)
 LIBBUILTIN(forward, "v&v&", "zfncThE", UTILITY, CXX_LANG)
+LIBBUILTIN(forward_like, "v&v&", "zfncThE", UTILITY, CXX_LANG)
 LIBBUILTIN(move, "v&v&", "zfncThE", UTILITY, CXX_LANG)
 LIBBUILTIN(move_if_noexcept, "v&v&", "zfncThE", UTILITY, CXX_LANG)
 

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 912a210fd2545..2a5b5c3520b4d 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8339,6 +8339,7 @@ bool LValueExprEvaluator::VisitCallExpr(const CallExpr 
*E) {
 return false;
   case Builtin::BIas_const:
   case Builtin::BIforward:
+  case Builtin::BIforward_like:
   case Builtin::BImove:
   case Builtin::BImove_if_noexcept:
 if (cast(E->getCalleeDecl())->isConstexpr())

diff  --git a/clang/lib/Analysis/BodyFarm.cpp b/clang/lib/Analysis/BodyFarm.cpp
index c05534886cb50..b989b8422cfc8 100644
--- a/clang/lib/Analysis/BodyFarm.cpp
+++ b/clang/lib/Analysis/BodyFarm.cpp
@@ -717,6 +717,7 @@ Stmt *BodyFarm::getBody(const FunctionDecl *D) {
 switch (BuiltinID) {
 case Builtin::BIas_const:
 case Builtin::BIforward:
+case Builtin::BIforward_like:
 case Builtin::BImove:
 case Builtin::BImove_if_noexcept:
   FF = create_std_move_forward;

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index f72e04a425d9f..bf23774c3fe12 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -4674,6 +4674,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
   case Builtin::BImove:
   case Builtin::BImove_if_noexcept:
   case Builtin::BIforward:
+  case Builtin::BIforward_like:
   case Builtin::BIas_const:
 return RValue::get(EmitLValue(E->getArg(0)).getPointer(*this));
   case Builtin::BI__GetExceptionInfo: {

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index ea21171aaac62..d414dcf549f38 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -2471,6 +2471,7 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, 
unsigned BuiltinID,
   case Builtin::BIaddressof:
   case Builtin::BI__addressof:
   case Builtin::BIforward:
+  case Builtin::BIforward_like:
   case Builtin::BImove:
   case Builtin::BImove_if_noexcept:
   case Builtin::BIas_const: {

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index b2ac4173410a8..6740a495a8a27 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -9556,6 +9556,7 @@ static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl 
*FD,
   case Builtin::BIaddressof:
   case Builtin::BI__addressof:
   case Builtin::BIforward:
+  case Builtin::BIforward_like:
   case Builtin::BImove:
   case Builtin::BImove_if_noexcept:
   case Builtin::BIas_const: {
@@ -16196,6 +16197,7 @@ void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) 

[clang] 31b0be4 - [Clang] Add lifetimebound attribute to std::move/std::forward

2023-01-19 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-01-19T20:57:24Z
New Revision: 31b0be4eba9e8e9244799f0ebcb18175faff69ab

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

LOG: [Clang] Add lifetimebound attribute to std::move/std::forward

Clang now automatically adds [[clang::lifetimebound]] to the parameters of
std::move, std::forward et al, this enables Clang to diagnose more cases
where the returned reference outlives the object.
Associated GitHub issue: https://github.com/llvm/llvm-project/issues/60020

Test plan: ninja check-clang check-all

Differential revision: https://reviews.llvm.org/D141744

Added: 


Modified: 
clang/docs/LanguageExtensions.rst
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaDecl.cpp
clang/test/SemaCXX/attr-lifetimebound.cpp
clang/test/SemaCXX/builtin-std-move.cpp
clang/test/SemaCXX/builtins.cpp

Removed: 




diff  --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index dbec1cd7c196..2e99a6072a94 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -2933,7 +2933,8 @@ implementation details of ``__sync_lock_test_and_set()``. 
 The
 ``__builtin_addressof`` performs the functionality of the built-in ``&``
 operator, ignoring any ``operator&`` overload.  This is useful in constant
 expressions in C++11, where there is no other way to take the address of an
-object that overloads ``operator&``.
+object that overloads ``operator&``. Clang automatically adds
+``[[clang::lifetimebound]]`` to the parameter of ``__builtin_addressof``.
 
 **Example of use**:
 

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 97ce8866d3cc..541f8e1eb671 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -458,6 +458,9 @@ Improvements to Clang's diagnostics
   only when ``x`` is a string literal.
 - Clang will now reject the GNU extension address of label in coroutines 
explicitly.
   This fixes `Issue 56436 
`_.
+- Clang now automatically adds ``[[clang::lifetimebound]]`` to the parameters 
of
+  ``std::move, std::forward`` et al, this enables Clang to diagnose more cases
+  where the returned reference outlives the object.
 
 Non-comprehensive list of changes in this release
 -

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index faa75f671fde..3ae3e33a6704 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -16182,6 +16182,24 @@ void Sema::AddKnownFunctionAttributes(FunctionDecl 
*FD) {
 default:
   break;
 }
+
+// Add lifetime attribute to std::move, std::fowrard et al.
+switch (BuiltinID) {
+case Builtin::BIaddressof:
+case Builtin::BI__addressof:
+case Builtin::BI__builtin_addressof:
+case Builtin::BIas_const:
+case Builtin::BIforward:
+case Builtin::BImove:
+case Builtin::BImove_if_noexcept:
+  if (ParmVarDecl *P = FD->getParamDecl(0u);
+  !P->hasAttr())
+P->addAttr(
+LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
+  break;
+default:
+  break;
+}
   }
 
   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);

diff  --git a/clang/test/SemaCXX/attr-lifetimebound.cpp 
b/clang/test/SemaCXX/attr-lifetimebound.cpp
index 90124c323d02..22cf5d0ab001 100644
--- a/clang/test/SemaCXX/attr-lifetimebound.cpp
+++ b/clang/test/SemaCXX/attr-lifetimebound.cpp
@@ -113,3 +113,77 @@ namespace p0936r0_examples {
   std::map m;
   const std::string &v = findOrDefault(m, "foo"s, "bar"s); // expected-warning 
{{temporary bound to local reference 'v'}}
 }
+
+// definitions for std::move, std::forward et al.
+namespace std {
+inline namespace foo {
+
+template  struct remove_reference {
+typedef T type;
+};
+template  struct remove_reference {
+typedef T type;
+};
+template  struct remove_reference {
+typedef T type;
+};
+
+template  constexpr typename remove_reference::type &&move(T &&t) {
+return static_cast::type>(t);
+}
+
+template 
+constexpr T &&forward(typename remove_reference::type &t) {
+return static_cast(t);
+}
+
+template 
+constexpr T &&forward(typename remove_reference::type &&t) {
+return static_cast(t);
+}
+
+template  constexpr const T &as_const(T &x) { return x; }
+
+template  struct PickRef {
+using type = typename remove_reference::type &;
+};
+template  struct PickRef {
+using type = typename remove_reference::type &&;
+};
+
+template 
+auto move_if_noexcept(T &t) ->
+typename PickRef(t)))>::type {
+return static_cast<
+typename PickRef(t)))>::type>(t);
+}
+
+template  T *addressof(T &arg) {
+return reinterpret_cast(
+  

[clang-tools-extra] [compiler-rt] Implement __extendxftf2 for x86_64 (PR #66918)

2023-09-22 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov updated 
https://github.com/llvm/llvm-project/pull/66918

>From 84cb5de329c228702da9f864312df31dc00692dc Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Wed, 20 Sep 2023 14:25:46 +
Subject: [PATCH] Implement __extendxftf2 for x86_64

---
 compiler-rt/lib/builtins/CMakeLists.txt   |  1 +
 compiler-rt/lib/builtins/extendxftf2.c| 23 +++
 compiler-rt/lib/builtins/fp_extend.h  | 24 +++
 compiler-rt/lib/builtins/fp_extend_impl.inc   | 48 ++
 compiler-rt/test/builtins/Unit/addtf3_test.c  |  2 +-
 compiler-rt/test/builtins/Unit/divtf3_test.c  |  2 +-
 .../test/builtins/Unit/extenddftf2_test.c |  2 +-
 .../test/builtins/Unit/extendhftf2_test.c |  2 +-
 .../test/builtins/Unit/extendsftf2_test.c |  2 +-
 .../test/builtins/Unit/extendxftf2_test.c | 66 +++
 .../test/builtins/Unit/floatditf_test.c   |  2 +-
 .../test/builtins/Unit/floatsitf_test.c   |  2 +-
 .../test/builtins/Unit/floatunditf_test.c |  2 +-
 .../test/builtins/Unit/floatunsitf_test.c |  2 +-
 compiler-rt/test/builtins/Unit/fp_test.h  | 55 +---
 compiler-rt/test/builtins/Unit/multf3_test.c  |  2 +-
 compiler-rt/test/builtins/Unit/subtf3_test.c  |  2 +-
 17 files changed, 205 insertions(+), 34 deletions(-)
 create mode 100644 compiler-rt/lib/builtins/extendxftf2.c
 create mode 100644 compiler-rt/test/builtins/Unit/extendxftf2_test.c

diff --git a/compiler-rt/lib/builtins/CMakeLists.txt 
b/compiler-rt/lib/builtins/CMakeLists.txt
index 43ef62ffb115d9d..b3e6e8c8b517d83 100644
--- a/compiler-rt/lib/builtins/CMakeLists.txt
+++ b/compiler-rt/lib/builtins/CMakeLists.txt
@@ -280,6 +280,7 @@ endif ()
 # long double is not 80 bits on Android or MSVC.
 set(x86_80_BIT_SOURCES
   divxc3.c
+  extendxftf2.c
   fixxfdi.c
   fixxfti.c
   fixunsxfdi.c
diff --git a/compiler-rt/lib/builtins/extendxftf2.c 
b/compiler-rt/lib/builtins/extendxftf2.c
new file mode 100644
index 000..aa5355e94839f93
--- /dev/null
+++ b/compiler-rt/lib/builtins/extendxftf2.c
@@ -0,0 +1,23 @@
+//===-- lib/extendxftf2.c - long double -> quad conversion *- C 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// Assumption: long double is a IEEE 80 bit floating point type padded to 128
+// bits.
+
+// TODO: use fp_lib.h once QUAD_PRECISION is available on x86_64.
+#if __LDBL_MANT_DIG__ == 64 && defined(__x86_64__) \
+   && (defined(__FLOAT128__) || 
defined(__SIZEOF_FLOAT128__))
+#define SRC_80
+#define DST_QUAD
+#include "fp_extend_impl.inc"
+
+COMPILER_RT_ABI __float128 __extendxftf2(long double a) {
+  return __extendXfYf2__(a);
+}
+
+#endif
diff --git a/compiler-rt/lib/builtins/fp_extend.h 
b/compiler-rt/lib/builtins/fp_extend.h
index eee4722bf90e69f..fc23c1c2d7a6a81 100644
--- a/compiler-rt/lib/builtins/fp_extend.h
+++ b/compiler-rt/lib/builtins/fp_extend.h
@@ -20,14 +20,18 @@
 typedef float src_t;
 typedef uint32_t src_rep_t;
 #define SRC_REP_C UINT32_C
+static const int srcBits = sizeof(src_t) * CHAR_BIT;
 static const int srcSigBits = 23;
+static const int srcSigFracBits = 23;
 #define src_rep_t_clz clzsi
 
 #elif defined SRC_DOUBLE
 typedef double src_t;
 typedef uint64_t src_rep_t;
 #define SRC_REP_C UINT64_C
+static const int srcBits = sizeof(src_t) * CHAR_BIT;
 static const int srcSigBits = 52;
+static const int srcSigFracBits = 52;
 static __inline int src_rep_t_clz(src_rep_t a) {
 #if defined __LP64__
   return __builtin_clzl(a);
@@ -39,6 +43,16 @@ static __inline int src_rep_t_clz(src_rep_t a) {
 #endif
 }
 
+#elif defined SRC_80
+typedef long double src_t;
+typedef __uint128_t src_rep_t;
+#define SRC_REP_C (__uint128_t)
+// sign bit, exponent and significand occupy the lower 80 bits.
+static const int srcBits = 80;
+// significand stores the integer bit.
+static const int srcSigBits = 64;
+static const int srcSigFracBits = 63;
+
 #elif defined SRC_HALF
 #ifdef COMPILER_RT_HAS_FLOAT16
 typedef _Float16 src_t;
@@ -47,7 +61,9 @@ typedef uint16_t src_t;
 #endif
 typedef uint16_t src_rep_t;
 #define SRC_REP_C UINT16_C
+static const int srcBits = sizeof(src_t) * CHAR_BIT;
 static const int srcSigBits = 10;
+static const int srcSigFracBits = 10;
 #define src_rep_t_clz __builtin_clz
 
 #else
@@ -59,18 +75,26 @@ typedef float dst_t;
 typedef uint32_t dst_rep_t;
 #define DST_REP_C UINT32_C
 static const int dstSigBits = 23;
+static const int dstSigFracBits = 23;
 
 #elif defined DST_DOUBLE
 typedef double dst_t;
 typedef uint64_t dst_rep_t;
 #define DST_REP_C UINT64_C
 static const int dstSigBits = 52;
+static const int dstSigFracBits = 52;
 
 #elif defined DST_QUAD
+// TODO: use fp_lib.h once QUAD_PRECISION is available on x86_64.
+#if __LDBL_MA

[clang] [compiler-rt] Implement __extendxftf2 for x86_64 (PR #66918)

2023-09-22 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov updated 
https://github.com/llvm/llvm-project/pull/66918

>From 84cb5de329c228702da9f864312df31dc00692dc Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov 
Date: Wed, 20 Sep 2023 14:25:46 +
Subject: [PATCH] Implement __extendxftf2 for x86_64

---
 compiler-rt/lib/builtins/CMakeLists.txt   |  1 +
 compiler-rt/lib/builtins/extendxftf2.c| 23 +++
 compiler-rt/lib/builtins/fp_extend.h  | 24 +++
 compiler-rt/lib/builtins/fp_extend_impl.inc   | 48 ++
 compiler-rt/test/builtins/Unit/addtf3_test.c  |  2 +-
 compiler-rt/test/builtins/Unit/divtf3_test.c  |  2 +-
 .../test/builtins/Unit/extenddftf2_test.c |  2 +-
 .../test/builtins/Unit/extendhftf2_test.c |  2 +-
 .../test/builtins/Unit/extendsftf2_test.c |  2 +-
 .../test/builtins/Unit/extendxftf2_test.c | 66 +++
 .../test/builtins/Unit/floatditf_test.c   |  2 +-
 .../test/builtins/Unit/floatsitf_test.c   |  2 +-
 .../test/builtins/Unit/floatunditf_test.c |  2 +-
 .../test/builtins/Unit/floatunsitf_test.c |  2 +-
 compiler-rt/test/builtins/Unit/fp_test.h  | 55 +---
 compiler-rt/test/builtins/Unit/multf3_test.c  |  2 +-
 compiler-rt/test/builtins/Unit/subtf3_test.c  |  2 +-
 17 files changed, 205 insertions(+), 34 deletions(-)
 create mode 100644 compiler-rt/lib/builtins/extendxftf2.c
 create mode 100644 compiler-rt/test/builtins/Unit/extendxftf2_test.c

diff --git a/compiler-rt/lib/builtins/CMakeLists.txt 
b/compiler-rt/lib/builtins/CMakeLists.txt
index 43ef62ffb115d9d..b3e6e8c8b517d83 100644
--- a/compiler-rt/lib/builtins/CMakeLists.txt
+++ b/compiler-rt/lib/builtins/CMakeLists.txt
@@ -280,6 +280,7 @@ endif ()
 # long double is not 80 bits on Android or MSVC.
 set(x86_80_BIT_SOURCES
   divxc3.c
+  extendxftf2.c
   fixxfdi.c
   fixxfti.c
   fixunsxfdi.c
diff --git a/compiler-rt/lib/builtins/extendxftf2.c 
b/compiler-rt/lib/builtins/extendxftf2.c
new file mode 100644
index 000..aa5355e94839f93
--- /dev/null
+++ b/compiler-rt/lib/builtins/extendxftf2.c
@@ -0,0 +1,23 @@
+//===-- lib/extendxftf2.c - long double -> quad conversion *- C 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// Assumption: long double is a IEEE 80 bit floating point type padded to 128
+// bits.
+
+// TODO: use fp_lib.h once QUAD_PRECISION is available on x86_64.
+#if __LDBL_MANT_DIG__ == 64 && defined(__x86_64__) \
+   && (defined(__FLOAT128__) || 
defined(__SIZEOF_FLOAT128__))
+#define SRC_80
+#define DST_QUAD
+#include "fp_extend_impl.inc"
+
+COMPILER_RT_ABI __float128 __extendxftf2(long double a) {
+  return __extendXfYf2__(a);
+}
+
+#endif
diff --git a/compiler-rt/lib/builtins/fp_extend.h 
b/compiler-rt/lib/builtins/fp_extend.h
index eee4722bf90e69f..fc23c1c2d7a6a81 100644
--- a/compiler-rt/lib/builtins/fp_extend.h
+++ b/compiler-rt/lib/builtins/fp_extend.h
@@ -20,14 +20,18 @@
 typedef float src_t;
 typedef uint32_t src_rep_t;
 #define SRC_REP_C UINT32_C
+static const int srcBits = sizeof(src_t) * CHAR_BIT;
 static const int srcSigBits = 23;
+static const int srcSigFracBits = 23;
 #define src_rep_t_clz clzsi
 
 #elif defined SRC_DOUBLE
 typedef double src_t;
 typedef uint64_t src_rep_t;
 #define SRC_REP_C UINT64_C
+static const int srcBits = sizeof(src_t) * CHAR_BIT;
 static const int srcSigBits = 52;
+static const int srcSigFracBits = 52;
 static __inline int src_rep_t_clz(src_rep_t a) {
 #if defined __LP64__
   return __builtin_clzl(a);
@@ -39,6 +43,16 @@ static __inline int src_rep_t_clz(src_rep_t a) {
 #endif
 }
 
+#elif defined SRC_80
+typedef long double src_t;
+typedef __uint128_t src_rep_t;
+#define SRC_REP_C (__uint128_t)
+// sign bit, exponent and significand occupy the lower 80 bits.
+static const int srcBits = 80;
+// significand stores the integer bit.
+static const int srcSigBits = 64;
+static const int srcSigFracBits = 63;
+
 #elif defined SRC_HALF
 #ifdef COMPILER_RT_HAS_FLOAT16
 typedef _Float16 src_t;
@@ -47,7 +61,9 @@ typedef uint16_t src_t;
 #endif
 typedef uint16_t src_rep_t;
 #define SRC_REP_C UINT16_C
+static const int srcBits = sizeof(src_t) * CHAR_BIT;
 static const int srcSigBits = 10;
+static const int srcSigFracBits = 10;
 #define src_rep_t_clz __builtin_clz
 
 #else
@@ -59,18 +75,26 @@ typedef float dst_t;
 typedef uint32_t dst_rep_t;
 #define DST_REP_C UINT32_C
 static const int dstSigBits = 23;
+static const int dstSigFracBits = 23;
 
 #elif defined DST_DOUBLE
 typedef double dst_t;
 typedef uint64_t dst_rep_t;
 #define DST_REP_C UINT64_C
 static const int dstSigBits = 52;
+static const int dstSigFracBits = 52;
 
 #elif defined DST_QUAD
+// TODO: use fp_lib.h once QUAD_PRECISION is available on x86_64.
+#if __LDBL_MA

[clang] [clang] Predefined macros for float128 support (PR #67196)

2023-09-25 Thread Alexander Shaposhnikov via cfe-commits


@@ -1076,6 +1076,8 @@ static void InitializePredefinedMacros(const TargetInfo 
&TI,
   DefineFloatMacros(Builder, "FLT", &TI.getFloatFormat(), "F");
   DefineFloatMacros(Builder, "DBL", &TI.getDoubleFormat(), "");
   DefineFloatMacros(Builder, "LDBL", &TI.getLongDoubleFormat(), "L");
+  if (TI.hasFloat128Type())
+DefineFloatMacros(Builder, "FLT128", &TI.getFloat128Format(), "Q");

alexander-shaposhnikov wrote:

This needs tests (see e.g. https://reviews.llvm.org/D111382, 
https://github.com/llvm/llvm-project/blob/main/clang/test/Preprocessor)

https://github.com/llvm/llvm-project/pull/67196
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Predefined macros for float128 support (PR #67196)

2023-09-26 Thread Alexander Shaposhnikov via cfe-commits

https://github.com/alexander-shaposhnikov approved this pull request.

LG

https://github.com/llvm/llvm-project/pull/67196
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r318705 - [analyzer] Diagnose stack leaks via block captures

2017-11-20 Thread Alexander Shaposhnikov via cfe-commits
Author: alexshap
Date: Mon Nov 20 14:53:30 2017
New Revision: 318705

URL: http://llvm.org/viewvc/llvm-project?rev=318705&view=rev
Log:
[analyzer] Diagnose stack leaks via block captures

This diff extends StackAddrEscapeChecker
to catch stack addresses leaks via block captures
if the block is executed asynchronously or
returned from a function.

Differential revision: https://reviews.llvm.org/D39438

Added:
cfe/trunk/test/Analysis/stack-capture-leak-arc.mm
cfe/trunk/test/Analysis/stack-capture-leak-no-arc.mm
Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp?rev=318705&r1=318704&r2=318705&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp Mon Nov 20 
14:53:30 2017
@@ -18,6 +18,7 @@
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "llvm/ADT/SmallString.h"
@@ -26,85 +27,131 @@ using namespace clang;
 using namespace ento;
 
 namespace {
-class StackAddrEscapeChecker : public Checker< check::PreStmt,
-   check::EndFunction > {
+class StackAddrEscapeChecker
+: public Checker,
+ check::EndFunction> {
+  mutable IdentifierInfo *dispatch_semaphore_tII;
   mutable std::unique_ptr BT_stackleak;
   mutable std::unique_ptr BT_returnstack;
+  mutable std::unique_ptr BT_capturedstackasync;
+  mutable std::unique_ptr BT_capturedstackret;
 
 public:
+  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
   void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
   void checkEndFunction(CheckerContext &Ctx) const;
+
 private:
+  void checkReturnedBlockCaptures(const BlockDataRegion &B,
+  CheckerContext &C) const;
+  void checkAsyncExecutedBlockCaptures(const BlockDataRegion &B,
+   CheckerContext &C) const;
   void EmitStackError(CheckerContext &C, const MemRegion *R,
   const Expr *RetE) const;
+  bool isSemaphoreCaptured(const BlockDecl &B) const;
   static SourceRange genName(raw_ostream &os, const MemRegion *R,
  ASTContext &Ctx);
+  static SmallVector
+  getCapturedStackRegions(const BlockDataRegion &B, CheckerContext &C);
+  static bool isArcManagedBlock(const MemRegion *R, CheckerContext &C);
+  static bool isNotInCurrentFrame(const MemRegion *R, CheckerContext &C);
 };
-}
+} // namespace
 
 SourceRange StackAddrEscapeChecker::genName(raw_ostream &os, const MemRegion 
*R,
 ASTContext &Ctx) {
-// Get the base region, stripping away fields and elements.
+  // Get the base region, stripping away fields and elements.
   R = R->getBaseRegion();
   SourceManager &SM = Ctx.getSourceManager();
   SourceRange range;
   os << "Address of ";
 
   // Check if the region is a compound literal.
-  if (const CompoundLiteralRegion* CR = dyn_cast(R)) {
+  if (const auto *CR = dyn_cast(R)) {
 const CompoundLiteralExpr *CL = CR->getLiteralExpr();
 os << "stack memory associated with a compound literal "
   "declared on line "
-<< SM.getExpansionLineNumber(CL->getLocStart())
-<< " returned to caller";
+   << SM.getExpansionLineNumber(CL->getLocStart()) << " returned to 
caller";
 range = CL->getSourceRange();
-  }
-  else if (const AllocaRegion* AR = dyn_cast(R)) {
+  } else if (const auto *AR = dyn_cast(R)) {
 const Expr *ARE = AR->getExpr();
 SourceLocation L = ARE->getLocStart();
 range = ARE->getSourceRange();
 os << "stack memory allocated by call to alloca() on line "
<< SM.getExpansionLineNumber(L);
-  }
-  else if (const BlockDataRegion *BR = dyn_cast(R)) {
+  } else if (const auto *BR = dyn_cast(R)) {
 const BlockDecl *BD = BR->getCodeRegion()->getDecl();
 SourceLocation L = BD->getLocStart();
 range = BD->getSourceRange();
 os << "stack-allocated block declared on line "
<< SM.getExpansionLineNumber(L);
-  }
-  else if (const VarRegion *VR = dyn_cast(R)) {
-os << "stack memory associated with local variable '"
-   << VR->getString() << '\'';
+  } else if (const auto *VR = dyn_cast(R)) {
+os << "stack memory associated with local variable '" << VR->getString()
+   << '\'';
 range = VR->getDecl()->getSourceRange();
-  }
-  else if (const CXXTempObject

[clang] 8403ccd - [Clang][CodeGen] Fix linkage and visibility of template parameter objects

2023-03-14 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-03-14T18:23:06Z
New Revision: 8403ccdcd28c2ff30c1e980ce4a8c851fae01a9d

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

LOG: [Clang][CodeGen] Fix linkage and visibility of template parameter objects

This diff fixes linkage and visibility of template parameter objects.
The associated GitHub issue: https://github.com/llvm/llvm-project/issues/51571#

Test plan:
1/ ninja check-all
2/ bootstrapped Clang passes tests

Differential revision: https://reviews.llvm.org/D145859

Added: 
clang/test/CodeGenCXX/template-param-objects-linkage.cpp
clang/test/CodeGenCXX/template-param-objects-visibility.cpp

Modified: 
clang/lib/CodeGen/CodeGenModule.cpp
clang/test/CodeGenCXX/template-param-objects.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index b512fb576a2c0..7055205862ded 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3238,9 +3238,13 @@ ConstantAddress 
CodeGenModule::GetAddrOfTemplateParamObject(
 return ConstantAddress::invalid();
   }
 
-  auto *GV = new llvm::GlobalVariable(
-  getModule(), Init->getType(),
-  /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
+  llvm::GlobalValue::LinkageTypes Linkage =
+  isExternallyVisible(TPO->getLinkageAndVisibility().getLinkage())
+  ? llvm::GlobalValue::LinkOnceODRLinkage
+  : llvm::GlobalValue::InternalLinkage;
+  auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
+  /*isConstant=*/true, Linkage, Init, 
Name);
+  setGVProperties(GV, TPO);
   if (supportsCOMDAT())
 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
   Emitter.finalize(GV);

diff  --git a/clang/test/CodeGenCXX/template-param-objects-linkage.cpp 
b/clang/test/CodeGenCXX/template-param-objects-linkage.cpp
new file mode 100644
index 0..63e7d8c646869
--- /dev/null
+++ b/clang/test/CodeGenCXX/template-param-objects-linkage.cpp
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -std=c++20 %s -emit-llvm -o - | 
FileCheck %s
+
+struct S { char buf[32]; };
+template constexpr const char* f() { return s.buf; }
+const char* fbuf = f();
+// CHECK: @_ZTAXtl1StlA32_cLc97 = linkonce_odr constant { <{ i8, [31 x i8] 
}> }
+
+namespace {
+  struct UN { char buf[64]; };
+}
+template  constexpr const char* g() { return un.buf; }
+const char* gbuf = g();
+// CHECK: @_ZTAXtlN12_GLOBAL__N_12UNEtlA64_cLc98 = internal constant { <{ 
i8, [63 x i8] }> }
+
+struct Foo { int *i; };
+int m = 0;
+namespace { int n; }
+
+template 
+const int* h() { return foo.i; }
+
+const int* hm = h();
+// CHECK: @_ZTAXtl3FooadL_Z1mEEE = linkonce_odr constant %struct.Foo { ptr @m }
+
+const int* hn = h();
+// CHECK: @_ZTAXtl3FooadL_ZN12_GLOBAL__N_11n = internal constant 
%struct.Foo { ptr @_ZN12_GLOBAL__N_11nE }

diff  --git a/clang/test/CodeGenCXX/template-param-objects-visibility.cpp 
b/clang/test/CodeGenCXX/template-param-objects-visibility.cpp
new file mode 100644
index 0..bf85016b0aff6
--- /dev/null
+++ b/clang/test/CodeGenCXX/template-param-objects-visibility.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -std=c++20 %s -emit-llvm -o - | 
FileCheck %s
+
+struct S { char buf[32]; };
+template constexpr const char* f() { return s.buf; }
+const char* fbuf = f();
+// CHECK: @_ZTAXtl1StlA32_cLc97 = linkonce_odr constant { <{ i8, [31 x i8] 
}> }
+
+struct __attribute__ ((visibility ("hidden"))) HN { char buf[64]; };
+template  constexpr const char* g() { return hn.buf; }
+const char* gbuf = g();
+// CHECK: @_ZTAXtl2HNtlA64_cLc98 = linkonce_odr hidden constant { <{ i8, 
[63 x i8] }> }

diff  --git a/clang/test/CodeGenCXX/template-param-objects.cpp 
b/clang/test/CodeGenCXX/template-param-objects.cpp
index e36b27185b526..11ebd21521e83 100644
--- a/clang/test/CodeGenCXX/template-param-objects.cpp
+++ b/clang/test/CodeGenCXX/template-param-objects.cpp
@@ -7,7 +7,9 @@ template constexpr const char *end() { return s.buf + 
__builtin_strlen(s.bu
 
 // ITANIUM: 
[[HELLO:@_ZTAXtl1StlA32_cLc104ELc101ELc108ELc108ELc111ELc32ELc119ELc111ELc114ELc108ELc100]]
 // MSABI: 
[[HELLO:@"[?][?]__N2US@@3D0GI@@0GF@@0GM@@0GM@@0GP@@0CA@@0HH@@0GP@@0HC@@0GM@@0GE@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@@0A@"]]
-// CHECK-SAME: = linkonce_odr constant { <{ [11 x i8], [21 x i8] }> } { <{ [11 
x i8], [21 x i8] }> <{ [11 x i8] c"hello world", [21 x i8] zeroinitializer }> 
}, comdat
+// ITANIUM-SAME: = linkonce_odr constant { <{ [11 x i8], [21 x i8] }> } { <{ 
[11 x i8], [21 x i8] }> <{ [11 x i8] c"hello world", [21 x i8] zeroinitializer 
}> }, comdat
+// MSABI-SAME:

[clang] 421c098 - [Clang][Sema] Start fixing handling of out-of-line definitions of constrained templates

2023-03-10 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-03-10T09:21:09Z
New Revision: 421c098b32bd50122de8de03a71092c7f36994eb

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

LOG: [Clang][Sema] Start fixing handling of out-of-line definitions of 
constrained templates

This diff starts fixing our handling of out-of-line definitions of constrained 
templates.
Initially it was motivated by https://github.com/llvm/llvm-project/issues/49620 
and
https://github.com/llvm/llvm-project/issues/60231.
In particular, this diff adjusts Sema::computeDeclContext to work properly in 
the case of
constrained template parameters.

Test plan:
1/ ninja check-all
2/ Bootstrapped Clang passes all the tests
3/ Internal testing

Differential revision: https://reviews.llvm.org/D145034

Added: 
clang/test/SemaTemplate/concepts-out-of-line-def.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/DeclSpec.h
clang/lib/Parse/ParseDecl.cpp
clang/lib/Parse/ParseDeclCXX.cpp
clang/lib/Sema/SemaCXXScopeSpec.cpp

clang/test/CXX/temp/temp.decls/temp.class.spec/temp.class.spec.mfunc/p1-neg.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 332431e08ce07..8d880a4fba266 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -78,6 +78,8 @@ C++ Language Changes
 
 C++20 Feature Support
 ^
+- Support for out-of-line definitions of constrained templates has been 
improved.
+  This partially fixes `https://github.com/llvm/llvm-project/issues/49620`.
 
 C++2b Feature Support
 ^

diff  --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index 96963fb6aa807..65111b1ac6b36 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -2513,7 +2513,8 @@ class Parser : public CodeCompletionHandler {
   /// this is a constructor declarator.
   bool isConstructorDeclarator(
   bool Unqualified, bool DeductionGuide = false,
-  DeclSpec::FriendSpecified IsFriend = DeclSpec::FriendSpecified::No);
+  DeclSpec::FriendSpecified IsFriend = DeclSpec::FriendSpecified::No,
+  const ParsedTemplateInfo *TemplateInfo = nullptr);
 
   /// Specifies the context in which type-id/expression
   /// disambiguation will occur.

diff  --git a/clang/include/clang/Sema/DeclSpec.h 
b/clang/include/clang/Sema/DeclSpec.h
index 69fe2c541607b..b0bf87dc18d79 100644
--- a/clang/include/clang/Sema/DeclSpec.h
+++ b/clang/include/clang/Sema/DeclSpec.h
@@ -62,9 +62,18 @@ namespace clang {
 /// often used as if it meant "present".
 ///
 /// The actual scope is described by getScopeRep().
+///
+/// If the kind of getScopeRep() is TypeSpec then TemplateParamLists may be 
empty
+/// or contain the template parameter lists attached to the current 
declaration.
+/// Consider the following example:
+/// template  void SomeType::some_method() {}
+/// If CXXScopeSpec refers to SomeType then TemplateParamLists will contain
+/// a single element referring to template .
+
 class CXXScopeSpec {
   SourceRange Range;
   NestedNameSpecifierLocBuilder Builder;
+  ArrayRef TemplateParamLists;
 
 public:
   SourceRange getRange() const { return Range; }
@@ -74,6 +83,13 @@ class CXXScopeSpec {
   SourceLocation getBeginLoc() const { return Range.getBegin(); }
   SourceLocation getEndLoc() const { return Range.getEnd(); }
 
+  void setTemplateParamLists(ArrayRef L) {
+TemplateParamLists = L;
+  }
+  ArrayRef getTemplateParamLists() const {
+return TemplateParamLists;
+  }
+
   /// Retrieve the representation of the nested-name-specifier.
   NestedNameSpecifier *getScopeRep() const {
 return Builder.getRepresentation();

diff  --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 3106571728692..da84da04e43d0 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -3380,6 +3380,8 @@ void Parser::ParseDeclarationSpecifiers(
 goto DoneWithDeclSpec;
 
   CXXScopeSpec SS;
+  if (TemplateInfo.TemplateParams)
+SS.setTemplateParamLists(*TemplateInfo.TemplateParams);
   Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
Tok.getAnnotationRange(),
SS);
@@ -3475,7 +3477,8 @@ void Parser::ParseDeclarationSpecifiers(
  &SS) &&
   isConstructorDeclarator(/*Unqualified=*/false,
   /*DeductionGuide=*/false,
-  DS.isFriendSpecified()))
+  DS.isFriendSpecified(),
+  &TemplateInfo))

[clang] 60bee9f - [Clang][Sema] Fix comparison of constraint expressions

2023-04-03 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-04-04T02:31:13Z
New Revision: 60bee9ff544541e83ffbd4be31923d0e8b644690

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

LOG: [Clang][Sema] Fix comparison of constraint expressions

This diff switches the approach to comparison of constraint expressions
to the new one based on template args substitution.
It continues the effort to fix our handling of out-of-line definitions
of constrained templates.

The associated GitHub issue: https://github.com/llvm/llvm-project/issues/61414

Test plan:
1/ ninja check-all
2/ bootstrapped Clang passes tests

Differential revision: https://reviews.llvm.org/D146178

Added: 


Modified: 
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaOverload.cpp
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/SemaTemplate/concepts-out-of-line-def.cpp
clang/test/SemaTemplate/concepts.cpp
clang/www/cxx_status.html

Removed: 




diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 2882b10613fdc..4e7033c9d588d 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -260,6 +260,9 @@ calculateConstraintSatisfaction(Sema &S, const Expr 
*ConstraintExpr,
 return SubstitutedAtomicExpr;
   }
 
+  if (SubstitutedAtomicExpr.get()->isValueDependent())
+return SubstitutedAtomicExpr;
+
   EnterExpressionEvaluationContext ConstantEvaluated(
   S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
   SmallVector EvaluationDiags;
@@ -752,27 +755,43 @@ namespace {
   };
 } // namespace
 
+static const Expr *SubstituteConstraintExpression(Sema &S, const NamedDecl *ND,
+  const Expr *ConstrExpr) {
+  MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
+  ND, /*Final=*/false, /*Innermost=*/nullptr,
+  /*RelativeToPrimary=*/true,
+  /*Pattern=*/nullptr,
+  /*ForConstraintInstantiation=*/true, /*SkipForSpecialization*/ false);
+  if (MLTAL.getNumSubstitutedLevels() == 0)
+return ConstrExpr;
+  Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/false);
+  std::optional ThisScope;
+  if (auto *RD = dyn_cast(ND->getDeclContext()))
+ThisScope.emplace(S, const_cast(RD), Qualifiers());
+  ExprResult SubstConstr =
+  S.SubstConstraintExpr(const_cast(ConstrExpr), MLTAL);
+  if (SFINAE.hasErrorOccurred() || !SubstConstr.isUsable())
+return nullptr;
+  return SubstConstr.get();
+}
+
 bool Sema::AreConstraintExpressionsEqual(const NamedDecl *Old,
  const Expr *OldConstr,
  const NamedDecl *New,
  const Expr *NewConstr) {
+  if (OldConstr == NewConstr)
+return true;
   if (Old && New && Old != New) {
-unsigned Depth1 = CalculateTemplateDepthForConstraints(
-*this, Old);
-unsigned Depth2 = CalculateTemplateDepthForConstraints(
-*this, New);
-
-// Adjust the 'shallowest' verison of this to increase the depth to match
-// the 'other'.
-if (Depth2 > Depth1) {
-  OldConstr = AdjustConstraintDepth(*this, Depth2 - Depth1)
-  .TransformExpr(const_cast(OldConstr))
-  .get();
-} else if (Depth1 > Depth2) {
-  NewConstr = AdjustConstraintDepth(*this, Depth1 - Depth2)
-  .TransformExpr(const_cast(NewConstr))
-  .get();
-}
+if (const Expr *SubstConstr =
+SubstituteConstraintExpression(*this, Old, OldConstr))
+  OldConstr = SubstConstr;
+else
+  return false;
+if (const Expr *SubstConstr =
+SubstituteConstraintExpression(*this, New, NewConstr))
+  NewConstr = SubstConstr;
+else
+  return false;
   }
 
   llvm::FoldingSetNodeID ID1, ID2;

diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index f10d937ed74d5..5cbd9e8a46234 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -1294,7 +1294,7 @@ bool Sema::IsOverload(FunctionDecl *New, FunctionDecl 
*Old,
 // We check the return type and template parameter lists for function
 // templates first; the remaining checks follow.
 bool SameTemplateParameterList = TemplateParameterListsAreEqual(
-NewTemplate->getTemplateParameters(),
+NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
 OldTemplate->getTemplateParameters(), false, TPL_TemplateMatch);
 bool SameReturnType = Context.hasSameType(Old->getDeclaredReturnType(),
   New->getDeclaredReturnType());

diff  --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/c

[clang] 13d44a8 - Revert "[Clang][Sema] Fix comparison of constraint expressions"

2023-04-07 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-04-07T18:41:57Z
New Revision: 13d44a8f5647819efd3ef57af384a3666f99d066

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

LOG: Revert "[Clang][Sema] Fix comparison of constraint expressions"

This temporarily reverts commit
60bee9ff544541e83ffbd4be31923d0e8b644690.
The diff will be recommitted once the newly discovered
regressions are fixed.

Added: 


Modified: 
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaOverload.cpp
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/SemaTemplate/concepts-out-of-line-def.cpp
clang/test/SemaTemplate/concepts.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 4e7033c9d588..2882b10613fd 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -260,9 +260,6 @@ calculateConstraintSatisfaction(Sema &S, const Expr 
*ConstraintExpr,
 return SubstitutedAtomicExpr;
   }
 
-  if (SubstitutedAtomicExpr.get()->isValueDependent())
-return SubstitutedAtomicExpr;
-
   EnterExpressionEvaluationContext ConstantEvaluated(
   S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
   SmallVector EvaluationDiags;
@@ -755,43 +752,27 @@ namespace {
   };
 } // namespace
 
-static const Expr *SubstituteConstraintExpression(Sema &S, const NamedDecl *ND,
-  const Expr *ConstrExpr) {
-  MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
-  ND, /*Final=*/false, /*Innermost=*/nullptr,
-  /*RelativeToPrimary=*/true,
-  /*Pattern=*/nullptr,
-  /*ForConstraintInstantiation=*/true, /*SkipForSpecialization*/ false);
-  if (MLTAL.getNumSubstitutedLevels() == 0)
-return ConstrExpr;
-  Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/false);
-  std::optional ThisScope;
-  if (auto *RD = dyn_cast(ND->getDeclContext()))
-ThisScope.emplace(S, const_cast(RD), Qualifiers());
-  ExprResult SubstConstr =
-  S.SubstConstraintExpr(const_cast(ConstrExpr), MLTAL);
-  if (SFINAE.hasErrorOccurred() || !SubstConstr.isUsable())
-return nullptr;
-  return SubstConstr.get();
-}
-
 bool Sema::AreConstraintExpressionsEqual(const NamedDecl *Old,
  const Expr *OldConstr,
  const NamedDecl *New,
  const Expr *NewConstr) {
-  if (OldConstr == NewConstr)
-return true;
   if (Old && New && Old != New) {
-if (const Expr *SubstConstr =
-SubstituteConstraintExpression(*this, Old, OldConstr))
-  OldConstr = SubstConstr;
-else
-  return false;
-if (const Expr *SubstConstr =
-SubstituteConstraintExpression(*this, New, NewConstr))
-  NewConstr = SubstConstr;
-else
-  return false;
+unsigned Depth1 = CalculateTemplateDepthForConstraints(
+*this, Old);
+unsigned Depth2 = CalculateTemplateDepthForConstraints(
+*this, New);
+
+// Adjust the 'shallowest' verison of this to increase the depth to match
+// the 'other'.
+if (Depth2 > Depth1) {
+  OldConstr = AdjustConstraintDepth(*this, Depth2 - Depth1)
+  .TransformExpr(const_cast(OldConstr))
+  .get();
+} else if (Depth1 > Depth2) {
+  NewConstr = AdjustConstraintDepth(*this, Depth1 - Depth2)
+  .TransformExpr(const_cast(NewConstr))
+  .get();
+}
   }
 
   llvm::FoldingSetNodeID ID1, ID2;

diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index aa40bff4c575..ab4300518ecf 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -1294,7 +1294,7 @@ bool Sema::IsOverload(FunctionDecl *New, FunctionDecl 
*Old,
 // We check the return type and template parameter lists for function
 // templates first; the remaining checks follow.
 bool SameTemplateParameterList = TemplateParameterListsAreEqual(
-NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
+NewTemplate->getTemplateParameters(),
 OldTemplate->getTemplateParameters(), false, TPL_TemplateMatch);
 bool SameReturnType = Context.hasSameType(Old->getDeclaredReturnType(),
   New->getDeclaredReturnType());

diff  --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index bdcee77ce67c..526f19b8aedc 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -208,10 +208,6 @@ Response HandleFunction(const FunctionDecl *Function,
   return Response::UseNextDecl(Function);

[clang] f799901 - [Clang][Sema] Add MultiLevelTemplateArgumentList::dump

2023-04-07 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-04-07T19:36:59Z
New Revision: f799901c06c015cc30cf123a8f0c01f8b107669e

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

LOG: [Clang][Sema] Add MultiLevelTemplateArgumentList::dump

Add MultiLevelTemplateArgumentList::dump
(similarly to TemplateArgument::dump).

Differential revision: https://reviews.llvm.org/D147744

Added: 


Modified: 
clang/include/clang/Sema/Template.h

Removed: 




diff  --git a/clang/include/clang/Sema/Template.h 
b/clang/include/clang/Sema/Template.h
index 908389438389f..48e8b78311e12 100644
--- a/clang/include/clang/Sema/Template.h
+++ b/clang/include/clang/Sema/Template.h
@@ -261,6 +261,23 @@ enum class TemplateSubstitutionKind : char {
 }
 ArgListsIterator end() { return TemplateArgumentLists.end(); }
 ConstArgListsIterator end() const { return TemplateArgumentLists.end(); }
+
+LLVM_DUMP_METHOD void dump() const {
+  LangOptions LO;
+  LO.CPlusPlus = true;
+  LO.Bool = true;
+  PrintingPolicy PP(LO);
+  llvm::errs() << "NumRetainedOuterLevels: " << NumRetainedOuterLevels
+   << "\n";
+  for (unsigned Depth = NumRetainedOuterLevels; Depth < getNumLevels();
+   ++Depth) {
+llvm::errs() << Depth << ": ";
+printTemplateArgumentList(
+llvm::errs(),
+TemplateArgumentLists[getNumLevels() - Depth - 1].Args, PP);
+llvm::errs() << "\n";
+  }
+}
   };
 
   /// The context in which partial ordering of function templates occurs.



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


[clang] 8f5d815 - [Clang][LLVM] Enable __arithmetic_fence and fprotect-parens on AArch64

2023-02-13 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-02-13T19:26:11Z
New Revision: 8f5d81585aa9261342d5304e460925916ea1f851

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

LOG: [Clang][LLVM] Enable __arithmetic_fence and fprotect-parens on AArch64

Enable __arithmetic_fence and fprotect-parens on AArch64.

Test plan: ninja check-clang check-clang-tools check-llvm

Differential revision: https://reviews.llvm.org/D143781

Added: 
llvm/test/CodeGen/AArch64/arithmetic_fence.ll

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Basic/Targets/AArch64.h
clang/test/AST/arithmetic-fence-builtin.c
clang/test/CodeGen/arithmetic-fence-builtin.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 06f0bdcc796d6..0dcd9b9f04b1d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -181,13 +181,16 @@ DWARF Support in Clang
 Arm and AArch64 Support in Clang
 
 
-* The hard-float ABI is now available in Armv8.1-M configurations that
+- The hard-float ABI is now available in Armv8.1-M configurations that
   have integer MVE instructions (and therefore have FP registers) but
   no scalar or vector floating point computation. Previously, trying
   to select the hard-float ABI on such a target (via
   ``-mfloat-abi=hard`` or a triple ending in ``hf``) would silently
   use the soft-float ABI instead.
 
+- Clang builtin ``__arithmetic_fence`` and the command line option 
``-fprotect-parens``
+  are now enabled for AArch64.
+
 Floating Point Support in Clang
 ---
 - Add ``__builtin_elementwise_log`` builtin for floating point types only.

diff  --git a/clang/lib/Basic/Targets/AArch64.h 
b/clang/lib/Basic/Targets/AArch64.h
index 7f88f3516780f..23cabc5885104 100644
--- a/clang/lib/Basic/Targets/AArch64.h
+++ b/clang/lib/Basic/Targets/AArch64.h
@@ -155,6 +155,8 @@ class LLVM_LIBRARY_VISIBILITY AArch64TargetInfo : public 
TargetInfo {
   ParsedTargetAttr parseTargetAttr(StringRef Str) const override;
   bool supportsTargetAttributeTune() const override { return true; }
 
+  bool checkArithmeticFenceSupported() const override { return true; }
+
   bool hasBFloat16Type() const override;
 
   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override;

diff  --git a/clang/test/AST/arithmetic-fence-builtin.c 
b/clang/test/AST/arithmetic-fence-builtin.c
index 4b3c8bed5..acdefade0748a 100644
--- a/clang/test/AST/arithmetic-fence-builtin.c
+++ b/clang/test/AST/arithmetic-fence-builtin.c
@@ -2,30 +2,54 @@
 // RUN: %clang_cc1 -ast-dump -triple i386-pc-linux-gnu %s \
 // RUN: | FileCheck %s --strict-whitespace --check-prefixes=CHECK,CHECK1
 //
+// RUN: %clang_cc1 -ast-dump -triple aarch64-unknown-linux-gnu %s \
+// RUN: | FileCheck %s --strict-whitespace --check-prefixes=CHECK,CHECK1
+//
 // RUN: %clang_cc1 -ast-dump -triple i386-pc-linux-gnu -DFAST -mreassociate %s 
\
 // RUN: | FileCheck %s --strict-whitespace --check-prefixes=CHECK,CHECK1
 //
+// RUN: %clang_cc1 -ast-dump -triple aarch64-unknown-linux-gnu -DFAST 
-mreassociate %s \
+// RUN: | FileCheck %s --strict-whitespace --check-prefixes=CHECK,CHECK1
+//
 // RUN: %clang_cc1 -ast-dump -triple i386-pc-linux-gnu -DFAST -mreassociate %s 
\
 // RUN: -fprotect-parens \
 // RUN: | FileCheck %s --strict-whitespace --check-prefixes=CHECK,CHECK2
 //
+// RUN: %clang_cc1 -ast-dump -triple aarch64-unknown-linux-gnu -DFAST 
-mreassociate %s \
+// RUN: -fprotect-parens \
+// RUN: | FileCheck %s --strict-whitespace --check-prefixes=CHECK,CHECK2
+//
 // Tests with serialization:
 // RUN: %clang_cc1 -ast-dump -triple i386-pc-linux-gnu -emit-pch -o %t %s
 // RUN: %clang_cc1 -triple i386-pc-linux-gnu -include-pch %t -ast-dump-all 
/dev/null \
 // RUN: | FileCheck %s --strict-whitespace
 //
+// RUN: %clang_cc1 -ast-dump -triple aarch64-unknown-linux-gnu -emit-pch -o %t 
%s
+// RUN: %clang_cc1 -triple aarch64-unknown-linux-gnu -include-pch %t 
-ast-dump-all /dev/null \
+// RUN: | FileCheck %s --strict-whitespace
+//
 // RUN: %clang_cc1 -ast-dump -triple i386-pc-linux-gnu -DFAST -mreassociate %s 
\
 // RUN: -emit-pch -o %t
 // RUN: %clang_cc1 -triple i386-pc-linux-gnu -include-pch %t -ast-dump-all 
/dev/null \
 // RUN: | FileCheck %s --strict-whitespace --check-prefixes=CHECK,CHECK1
 //
+// RUN: %clang_cc1 -ast-dump -triple aarch64-unknown-linux-gnu -DFAST 
-mreassociate %s \
+// RUN: -emit-pch -o %t
+// RUN: %clang_cc1 -triple aarch64-unknown-linux-gnu -include-pch %t 
-ast-dump-all /dev/null \
+// RUN: | FileCheck %s --strict-whitespace --check-prefixes=CHECK,CHECK1
+//
 // RUN: %clang_cc1 -ast-dump -triple i386-pc-linux-gnu -DFAST -mreassociate %s 
\
 // RUN: -fprotect-parens \
 // RUN: -emit-pch -o %t
 // RUN: %clang_cc1 -triple i3

[clang] 3b9ed6e - Revert "[Clang][Sema] Fix comparison of constraint expressions"

2023-05-04 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-05-05T00:02:26Z
New Revision: 3b9ed6e5323176550925f3b0a2c50ced1b61438d

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

LOG: Revert "[Clang][Sema] Fix comparison of constraint expressions"

This reverts commit 3a540229341e3c8dc6d8ee61309eafaf943ea254.
A new regression is discovered and needs to be investigated.

Added: 


Modified: 
clang/include/clang/AST/DeclTemplate.h
clang/include/clang/Sema/Template.h
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaOverload.cpp
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/SemaTemplate/concepts-friends.cpp
clang/test/SemaTemplate/concepts-out-of-line-def.cpp
clang/test/SemaTemplate/concepts.cpp

Removed: 




diff  --git a/clang/include/clang/AST/DeclTemplate.h 
b/clang/include/clang/AST/DeclTemplate.h
index 7cd505218f2b9..3677335fa176f 100644
--- a/clang/include/clang/AST/DeclTemplate.h
+++ b/clang/include/clang/AST/DeclTemplate.h
@@ -2309,15 +2309,9 @@ class ClassTemplateDecl : public 
RedeclarableTemplateDecl {
 return static_cast(RedeclarableTemplateDecl::getCommonPtr());
   }
 
-  void setCommonPtr(Common *C) {
-RedeclarableTemplateDecl::Common = C;
-  }
-
 public:
-
   friend class ASTDeclReader;
   friend class ASTDeclWriter;
-  friend class TemplateDeclInstantiator;
 
   /// Load any lazily-loaded specializations from the external source.
   void LoadLazySpecializations() const;

diff  --git a/clang/include/clang/Sema/Template.h 
b/clang/include/clang/Sema/Template.h
index 1de2cc6917b42..48e8b78311e12 100644
--- a/clang/include/clang/Sema/Template.h
+++ b/clang/include/clang/Sema/Template.h
@@ -232,21 +232,9 @@ enum class TemplateSubstitutionKind : char {
 /// Replaces the current 'innermost' level with the provided argument list.
 /// This is useful for type deduction cases where we need to get the entire
 /// list from the AST, but then add the deduced innermost list.
-void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args) 
{
-  assert((!TemplateArgumentLists.empty() || NumRetainedOuterLevels) &&
- "Replacing in an empty list?");
-
-  if (!TemplateArgumentLists.empty()) {
-assert((TemplateArgumentLists[0].AssociatedDeclAndFinal.getPointer() ||
-TemplateArgumentLists[0].AssociatedDeclAndFinal.getPointer() ==
-AssociatedDecl) &&
-   "Trying to change incorrect declaration?");
-TemplateArgumentLists[0].Args = Args;
-  } else {
---NumRetainedOuterLevels;
-TemplateArgumentLists.push_back(
-{{AssociatedDecl, /*Final=*/false}, Args});
-  }
+void replaceInnermostTemplateArguments(ArgList Args) {
+  assert(TemplateArgumentLists.size() > 0 && "Replacing in an empty 
list?");
+  TemplateArgumentLists[0].Args = Args;
 }
 
 /// Add an outermost level that we are not substituting. We have no

diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 1126c2c517fe4..7aa06b615fec2 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -722,7 +722,7 @@ CalculateTemplateDepthForConstraints(Sema &S, const 
NamedDecl *ND,
   ND, /*Final=*/false, /*Innermost=*/nullptr, /*RelativeToPrimary=*/true,
   /*Pattern=*/nullptr,
   /*ForConstraintInstantiation=*/true, SkipForSpecialization);
-  return MLTAL.getNumLevels();
+  return MLTAL.getNumSubstitutedLevels();
 }
 
 namespace {
@@ -753,44 +753,27 @@ namespace {
   };
 } // namespace
 
-static const Expr *SubstituteConstraintExpression(Sema &S, const NamedDecl *ND,
-  const Expr *ConstrExpr) {
-  MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
-  ND, /*Final=*/false, /*Innermost=*/nullptr,
-  /*RelativeToPrimary=*/true,
-  /*Pattern=*/nullptr, /*ForConstraintInstantiation=*/true,
-  /*SkipForSpecialization*/ false);
-  if (MLTAL.getNumSubstitutedLevels() == 0)
-return ConstrExpr;
-
-  Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/false);
-  std::optional ThisScope;
-  if (auto *RD = dyn_cast(ND->getDeclContext()))
-ThisScope.emplace(S, const_cast(RD), Qualifiers());
-  ExprResult SubstConstr =
-  S.SubstConstraintExpr(const_cast(ConstrExpr), MLTAL);
-  if (SFINAE.hasErrorOccurred() || !SubstConstr.isUsable())
-return nullptr;
-  return SubstConstr.get();
-}
-
 bool Sema::AreConstraintExpressionsEqual(const NamedDecl *Old,
  const Expr *OldConstr,
  const NamedDecl *New,
   

[clang] 6db007a - [Clang][Sema] Fix comparison of constraint expressions

2023-05-09 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-05-09T18:14:39Z
New Revision: 6db007a0654ed7a6ed5c3aa3b61a937c19a6bc6b

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

LOG: [Clang][Sema] Fix comparison of constraint expressions

This diff switches the approach to comparison of constraint expressions
to the new one based on template args substitution.
It continues the effort to fix our handling of out-of-line definitions
of constrained templates.
This is a recommit of 3a54022934.

Differential revision: https://reviews.llvm.org/D146178

Added: 


Modified: 
clang/include/clang/AST/DeclTemplate.h
clang/include/clang/Sema/Template.h
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaOverload.cpp
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/SemaTemplate/concepts-friends.cpp
clang/test/SemaTemplate/concepts-out-of-line-def.cpp
clang/test/SemaTemplate/concepts.cpp

Removed: 




diff  --git a/clang/include/clang/AST/DeclTemplate.h 
b/clang/include/clang/AST/DeclTemplate.h
index 3677335fa176f..7cd505218f2b9 100644
--- a/clang/include/clang/AST/DeclTemplate.h
+++ b/clang/include/clang/AST/DeclTemplate.h
@@ -2309,9 +2309,15 @@ class ClassTemplateDecl : public 
RedeclarableTemplateDecl {
 return static_cast(RedeclarableTemplateDecl::getCommonPtr());
   }
 
+  void setCommonPtr(Common *C) {
+RedeclarableTemplateDecl::Common = C;
+  }
+
 public:
+
   friend class ASTDeclReader;
   friend class ASTDeclWriter;
+  friend class TemplateDeclInstantiator;
 
   /// Load any lazily-loaded specializations from the external source.
   void LoadLazySpecializations() const;

diff  --git a/clang/include/clang/Sema/Template.h 
b/clang/include/clang/Sema/Template.h
index 48e8b78311e12..1de2cc6917b42 100644
--- a/clang/include/clang/Sema/Template.h
+++ b/clang/include/clang/Sema/Template.h
@@ -232,9 +232,21 @@ enum class TemplateSubstitutionKind : char {
 /// Replaces the current 'innermost' level with the provided argument list.
 /// This is useful for type deduction cases where we need to get the entire
 /// list from the AST, but then add the deduced innermost list.
-void replaceInnermostTemplateArguments(ArgList Args) {
-  assert(TemplateArgumentLists.size() > 0 && "Replacing in an empty 
list?");
-  TemplateArgumentLists[0].Args = Args;
+void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args) 
{
+  assert((!TemplateArgumentLists.empty() || NumRetainedOuterLevels) &&
+ "Replacing in an empty list?");
+
+  if (!TemplateArgumentLists.empty()) {
+assert((TemplateArgumentLists[0].AssociatedDeclAndFinal.getPointer() ||
+TemplateArgumentLists[0].AssociatedDeclAndFinal.getPointer() ==
+AssociatedDecl) &&
+   "Trying to change incorrect declaration?");
+TemplateArgumentLists[0].Args = Args;
+  } else {
+--NumRetainedOuterLevels;
+TemplateArgumentLists.push_back(
+{{AssociatedDecl, /*Final=*/false}, Args});
+  }
 }
 
 /// Add an outermost level that we are not substituting. We have no

diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 7aa06b615fec2..1126c2c517fe4 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -722,7 +722,7 @@ CalculateTemplateDepthForConstraints(Sema &S, const 
NamedDecl *ND,
   ND, /*Final=*/false, /*Innermost=*/nullptr, /*RelativeToPrimary=*/true,
   /*Pattern=*/nullptr,
   /*ForConstraintInstantiation=*/true, SkipForSpecialization);
-  return MLTAL.getNumSubstitutedLevels();
+  return MLTAL.getNumLevels();
 }
 
 namespace {
@@ -753,27 +753,44 @@ namespace {
   };
 } // namespace
 
+static const Expr *SubstituteConstraintExpression(Sema &S, const NamedDecl *ND,
+  const Expr *ConstrExpr) {
+  MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
+  ND, /*Final=*/false, /*Innermost=*/nullptr,
+  /*RelativeToPrimary=*/true,
+  /*Pattern=*/nullptr, /*ForConstraintInstantiation=*/true,
+  /*SkipForSpecialization*/ false);
+  if (MLTAL.getNumSubstitutedLevels() == 0)
+return ConstrExpr;
+
+  Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/false);
+  std::optional ThisScope;
+  if (auto *RD = dyn_cast(ND->getDeclContext()))
+ThisScope.emplace(S, const_cast(RD), Qualifiers());
+  ExprResult SubstConstr =
+  S.SubstConstraintExpr(const_cast(ConstrExpr), MLTAL);
+  if (SFINAE.hasErrorOccurred() || !SubstConstr.isUsable())
+return nullptr;
+  return SubstConstr.get();
+}
+
 bool Sema::AreConstraintExpressionsEqual(co

[clang] 122b938 - [Clang][Sema] Substitute constraints only for declarations with different lexical contexts

2023-05-17 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-05-17T21:24:44Z
New Revision: 122b938944ceb966e04d7a4d253f7f9ba27c477d

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

LOG: [Clang][Sema] Substitute constraints only for declarations with different 
lexical contexts

Substitute constraints only for declarations with different lexical contexts.
This results in avoiding the substitution of constraints during the 
redeclaration check
inside a class (and by product caching the wrong substitution result).

Test plan: ninja check-all

Differential revision: https://reviews.llvm.org/D150730

Added: 
clang/test/SemaTemplate/concepts-no-early-substitution.cpp

Modified: 
clang/lib/Sema/SemaConcept.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 1126c2c517fe4..2f5fb8f8d029e 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -780,7 +780,9 @@ bool Sema::AreConstraintExpressionsEqual(const NamedDecl 
*Old,
  const Expr *NewConstr) {
   if (OldConstr == NewConstr)
 return true;
-  if (Old && New && Old != New) {
+  // C++ [temp.constr.decl]p4
+  if (Old && New && Old != New &&
+  Old->getLexicalDeclContext() != New->getLexicalDeclContext()) {
 if (const Expr *SubstConstr =
 SubstituteConstraintExpression(*this, Old, OldConstr))
   OldConstr = SubstConstr;

diff  --git a/clang/test/SemaTemplate/concepts-no-early-substitution.cpp 
b/clang/test/SemaTemplate/concepts-no-early-substitution.cpp
new file mode 100644
index 0..9e576f16a263b
--- /dev/null
+++ b/clang/test/SemaTemplate/concepts-no-early-substitution.cpp
@@ -0,0 +1,33 @@
+// RUN: %clang_cc1 -std=c++20 -x c++ %s -verify -fsyntax-only
+// expected-no-diagnostics
+
+template 
+concept HasMemberBegin = requires(T0 t) { t.begin(); };
+
+struct GetBegin {
+  template 
+  void operator()(T1);
+};
+
+GetBegin begin;
+
+template 
+concept Concept = requires(T2 t) { begin(t); };
+
+struct Subrange;
+
+template 
+struct View {
+  Subrange &getSubrange();
+
+  operator bool()
+requires true;
+
+  operator bool()
+requires requires { begin(getSubrange()); };
+
+  void begin();
+};
+
+struct Subrange : View {};
+static_assert(Concept);



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


[clang] cd4677f - [Clang] Update release notes

2023-05-18 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-05-18T20:02:37Z
New Revision: cd4677f207041e74f55d0cac6145942f04301ee7

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

LOG: [Clang] Update release notes

Update release notes.
This is a follow-up to https://reviews.llvm.org/D146178

Differential revision: https://reviews.llvm.org/D149906

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 9420a9e687ca7..5c6459d01b14c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -77,8 +77,13 @@ C++ Language Changes
 
 C++20 Feature Support
 ^
-- Support for out-of-line definitions of constrained templates has been 
improved.
-  This partially fixes `#49620 
`_.
+- Implemented the rule introduced by `CA104 `_  for 
comparison of
+  constraint-expressions. Improved support for out-of-line definitions of 
constrained templates.
+  This fixes:
+  `#49620 `_,
+  `#60231 `_,
+  `#61414 `_,
+  `#61809 `_.
 - Lambda templates with a requires clause directly after the template 
parameters now parse
   correctly if the requires clause consists of a variable with a dependent 
type.
   (`#61278 `_)



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


[clang] 7c26919 - [Clang] Fix typo in ReleaseNotes.rst

2023-05-18 Thread Alexander Shaposhnikov via cfe-commits

Author: Alexander Shaposhnikov
Date: 2023-05-18T20:08:54Z
New Revision: 7c26919c32f0620441417805329867884a5efc7b

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

LOG: [Clang] Fix typo in ReleaseNotes.rst

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5c6459d01b14..b0f848d47a67 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -82,7 +82,7 @@ C++20 Feature Support
   This fixes:
   `#49620 `_,
   `#60231 `_,
-  `#61414 `_,
+  `#61414 `_,
   `#61809 `_.
 - Lambda templates with a requires clause directly after the template 
parameters now parse
   correctly if the requires clause consists of a variable with a dependent 
type.



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


  1   2   3   4   >