Re: r345099 - [analyzer] Trust summaries for OSObject::retain and OSObject::release

2018-11-26 Thread Mikael Holmén via cfe-commits
Hi again,

Do you have any opinion about the below valgrind complaint that starts 
appearing with this patch?

valgrind still complains on it on current trunk.

I see it when compiling with clang 3.6.0. I've also tried gcc 5.4.0 but 
then I don't get it.

Regards,
Mikael

On 11/21/18 8:33 AM, Mikael Holmén via cfe-commits wrote:
> Hi George,
> 
> I noticed that valgrind started complaining in one case with this patch.
> 
> I've no idea if it's really due to something in the patch or if it's
> something old that surfaced or if it's a false flag.
> 
> Anyway, with this patch the following
> 
>valgrind clang-tidy -checks='-*,clang-analyzer-*' 'memcpy.c' -- -O0
> 
> gives me
> 
> ==18829== Memcheck, a memory error detector
> ==18829== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
> ==18829== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
> ==18829== Command: build-all/bin/clang-tidy -checks=-*,clang-analyzer-*
> memcpy.c -- -O0
> ==18829==
> ==18829== Conditional jump or move depends on uninitialised value(s)
> ==18829==at 0xE580DF:
> clang::ento::RetainSummaryManager::canEval(clang::CallExpr const*,
> clang::FunctionDecl const*, bool&) (in
> /data/repo/llvm-patch/build-all/bin/clang-tidy)
> ==18829==by 0xD034AA:
> clang::ento::retaincountchecker::RetainCountChecker::evalCall(clang::CallExpr
> const*, clang::ento::CheckerContext&) const (in
> /data/repo/llvm-patch/build-all/bin/clang-tidy)
> ==18829==by 0xDCBCD7:
> clang::ento::CheckerManager::runCheckersForEvalCall(clang::ento::ExplodedNodeSet&,
> clang::ento::ExplodedNodeSet const&, clang::ento::CallEvent const&,
> clang::ento::ExprEngine&) (in
> /data/repo/llvm-patch/build-all/bin/clang-tidy)
> ==18829==by 0xE033D5:
> clang::ento::ExprEngine::evalCall(clang::ento::ExplodedNodeSet&,
> clang::ento::ExplodedNode*, clang::ento::CallEvent const&) (in
> /data/repo/llvm-patch/build-all/bin/clang-tidy)
> ==18829==by 0xE03165:
> clang::ento::ExprEngine::VisitCallExpr(clang::CallExpr const*,
> clang::ento::ExplodedNode*, clang::ento::ExplodedNodeSet&) (in
> /data/repo/llvm-patch/build-all/bin/clang-tidy)
> ==18829==by 0xDE3D9A: clang::ento::ExprEngine::Visit(clang::Stmt
> const*, clang::ento::ExplodedNode*, clang::ento::ExplodedNodeSet&) (in
> /data/repo/llvm-patch/build-all/bin/clang-tidy)
> ==18829==by 0xDDEFD1:
> clang::ento::ExprEngine::ProcessStmt(clang::Stmt const*,
> clang::ento::ExplodedNode*) (in
> /data/repo/llvm-patch/build-all/bin/clang-tidy)
> ==18829==by 0xDDEBBC:
> clang::ento::ExprEngine::processCFGElement(clang::CFGElement,
> clang::ento::ExplodedNode*, unsigned int,
> clang::ento::NodeBuilderContext*) (in
> /data/repo/llvm-patch/build-all/bin/clang-tidy)
> ==18829==by 0xDD3154:
> clang::ento::CoreEngine::HandlePostStmt(clang::CFGBlock const*, unsigned
> int, clang::ento::ExplodedNode*) (in
> /data/repo/llvm-patch/build-all/bin/clang-tidy)
> ==18829==by 0xDD24D3:
> clang::ento::CoreEngine::ExecuteWorkList(clang::LocationContext const*,
> unsigned int, llvm::IntrusiveRefCntPtr)
> (in /data/repo/llvm-patch/build-all/bin/clang-tidy)
> ==18829==by 0xB8E90E: (anonymous
> namespace)::AnalysisConsumer::HandleCode(clang::Decl*, unsigned int,
> clang::ento::ExprEngine::InliningModes, llvm::DenseSet const*, llvm::DenseMapInfo >*) (in
> /data/repo/llvm-patch/build-all/bin/clang-tidy)
> ==18829==by 0xB89943: (anonymous
> namespace)::AnalysisConsumer::HandleTranslationUnit(clang::ASTContext&)
> (in /data/repo/llvm-patch/build-all/bin/clang-tidy)
> ==18829==
> 
> The call to
> 
>   const FunctionDecl* FDD = FD->getDefinition();
> 
> in RetainSummaryManager::canEval eventually ends up in
> 
> bool isThisDeclarationADefinition() const {
>   return isDeletedAsWritten() || isDefaulted() || Body ||
> hasSkippedBody() ||
>  isLateTemplateParsed() || willHaveBody() || hasDefiningAttr();
> }
> 
> And here it seems to be the access of "Body" that valgrind complains on.
> If I simply comment out "Body" the complaint is gone.
> 
> I really have no clue about this code, but perhaps this makes some sense
> to you? Or perhaps to someone else?
> 
> Regards,
> Mikael
> 
> On 10/24/18 1:11 AM, George Karpenkov via cfe-commits wrote:
>> Author: george.karpenkov
>> Date: Tue Oct 23 16:11:30 2018
>> New Revision: 345099
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=345099&view=rev
>> Log:
>> [analyzer] Trust summaries for OSObject::retain and OSObject::release
>>
>> Refactor the way in which summaries are consumed for safeMetaCast
>>
>> Differential Revision: https://reviews.llvm.org/D53549
>>
>> Modified:
>>   
>> cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
>>   cfe/trunk/lib/StaticAnalyzer/Core/RetainSummaryManager.cpp
>>   cfe/trunk/test/Analysis/osobject-retain-release.cpp
>>
>> Modified: 
>> cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
>> URL: 
>> http://llvm.org/viewvc/llvm-p

[PATCH] D53754: [Analyzer] Skip symbolic regions based on conjured symbols in comparison of the containers of iterators

2018-11-26 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware added a comment.
Herald added a subscriber: gamesh411.

In D53754#1277253 , @Szelethus wrote:

> I wonder whether a method in `MemRegion` called `isSameRegion` or 
> `isSurelySameRegion` would be better. I think it's likely that there are (or 
> will be) checkers that would do similar things.


Unfortunately the question whether two regions are the same is a partially 
decidable problem. We can never be sure whether two regions are "surely" the 
same. We can only disclose some highly unreliable region types such as symbolic 
regions based on conjured symbols to reduce false positives.


Repository:
  rC Clang

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

https://reviews.llvm.org/D53754



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


[PATCH] D53488: [clang-tidy] Improving narrowing conversions

2018-11-26 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet updated this revision to Diff 175203.
gchatelet marked 16 inline comments as done.
gchatelet added a comment.

- Addressing comments


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D53488

Files:
  clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
  clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/cppcoreguidelines-narrowing-conversions.rst
  
test/clang-tidy/cppcoreguidelines-narrowing-conversions-castingliterals-option.cpp
  test/clang-tidy/cppcoreguidelines-narrowing-conversions-long-is-32bits.cpp
  
test/clang-tidy/cppcoreguidelines-narrowing-conversions-narrowingfloatingpoint-option.cpp
  test/clang-tidy/cppcoreguidelines-narrowing-conversions-unsigned-char.cpp
  test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp

Index: test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp
===
--- test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp
+++ test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp
@@ -1,4 +1,9 @@
-// RUN: %check_clang_tidy %s cppcoreguidelines-narrowing-conversions %t
+// RUN: %check_clang_tidy %s cppcoreguidelines-narrowing-conversions %t \
+// RUN: -config="{CheckOptions: [ \
+// RUN:   {key: "cppcoreguidelines-narrowing-conversions.WarnOnFloatingPointNarrowingConversion", value: 0}, \
+// RUN:   {key: "cppcoreguidelines-narrowing-conversions.PedanticMode", value: 0} \
+// RUN: ]}" \
+// RUN: -- -target x86_64-unknown-linux -fsigned-char
 
 float ceil(float);
 namespace std {
@@ -9,47 +14,282 @@
 namespace floats {
 
 struct ConvertsToFloat {
-  operator float() const { return 0.5; }
+  operator float() const { return 0.5f; }
 };
 
-float operator "" _Pa(unsigned long long);
+float operator"" _float(unsigned long long);
 
-void not_ok(double d) {
+void narrow_fp_to_int_not_ok(double d) {
   int i = 0;
   i = d;
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
   i = 0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from constant 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i = static_cast(d);
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i = ConvertsToFloat();
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
-  i = 15_Pa;
+  i = 15_float;
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
-}
-
-void not_ok_binary_ops(double d) {
-  int i = 0;
+  i += d;
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
   i += 0.5;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: narrowing conversion from constant 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
   i += 0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
-  i += d;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
-  // We warn on the following even though it's not dangerous because there is no
-  // reason to use a double literal here.
-  // TODO(courbet): Provide an automatic fix.
-  i += 2.0;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
-  i += 2.0f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
-
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: narrowing conversion from constant 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i *= 0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: narrowing conversion from constant 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i /= 0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: narrowing conversion from constant 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i += (double)0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narro

[PATCH] D53488: [clang-tidy] Improving narrowing conversions

2018-11-26 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet added a comment.

Thank you for bearing with me  @aaron.ballman.




Comment at: clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp:259-263
+void NarrowingConversionsCheck::handleIntegralToBoolean(
+const ASTContext &Context, SourceLocation SourceLoc, const Expr &Lhs,
+const Expr &Rhs) {
+  // Conversion from Integral to Bool value is well defined.
+}

aaron.ballman wrote:
> Why is this function needed at all?
The two empty functions are placeholders so the cases handled by `ImplicitCast` 
and `BinaryOp` are the same.
I'll add some documentation.



Comment at: clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp:311-315
+void NarrowingConversionsCheck::handleBooleanToSignedIntegral(
+const ASTContext &Context, SourceLocation SourceLoc, const Expr &Lhs,
+const Expr &Rhs) {
+  // Conversion from Bool to SignedIntegral value is well defined.
+}

aaron.ballman wrote:
> Why is this function needed at all?
Ditto.



Comment at: clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp:372
+  if (const auto *CO = llvm::dyn_cast(&Rhs)) {
+// We create variables so we make sure both sides of the
+// ConditionalOperator are evaluated, the || operator would short ciruit

aaron.ballman wrote:
> What variables are created here?
Leftover. I rewrote the comment.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D53488



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


[PATCH] D53488: [clang-tidy] Improving narrowing conversions

2018-11-26 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet updated this revision to Diff 175204.
gchatelet added a comment.

- Fixing  documentation.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D53488

Files:
  clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
  clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/cppcoreguidelines-narrowing-conversions.rst
  
test/clang-tidy/cppcoreguidelines-narrowing-conversions-castingliterals-option.cpp
  test/clang-tidy/cppcoreguidelines-narrowing-conversions-long-is-32bits.cpp
  
test/clang-tidy/cppcoreguidelines-narrowing-conversions-narrowingfloatingpoint-option.cpp
  test/clang-tidy/cppcoreguidelines-narrowing-conversions-unsigned-char.cpp
  test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp

Index: test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp
===
--- test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp
+++ test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp
@@ -1,4 +1,9 @@
-// RUN: %check_clang_tidy %s cppcoreguidelines-narrowing-conversions %t
+// RUN: %check_clang_tidy %s cppcoreguidelines-narrowing-conversions %t \
+// RUN: -config="{CheckOptions: [ \
+// RUN:   {key: "cppcoreguidelines-narrowing-conversions.WarnOnFloatingPointNarrowingConversion", value: 0}, \
+// RUN:   {key: "cppcoreguidelines-narrowing-conversions.PedanticMode", value: 0} \
+// RUN: ]}" \
+// RUN: -- -target x86_64-unknown-linux -fsigned-char
 
 float ceil(float);
 namespace std {
@@ -9,47 +14,282 @@
 namespace floats {
 
 struct ConvertsToFloat {
-  operator float() const { return 0.5; }
+  operator float() const { return 0.5f; }
 };
 
-float operator "" _Pa(unsigned long long);
+float operator"" _float(unsigned long long);
 
-void not_ok(double d) {
+void narrow_fp_to_int_not_ok(double d) {
   int i = 0;
   i = d;
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
   i = 0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from constant 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i = static_cast(d);
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i = ConvertsToFloat();
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
-  i = 15_Pa;
+  i = 15_float;
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
-}
-
-void not_ok_binary_ops(double d) {
-  int i = 0;
+  i += d;
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
   i += 0.5;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: narrowing conversion from constant 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
   i += 0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
-  i += d;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
-  // We warn on the following even though it's not dangerous because there is no
-  // reason to use a double literal here.
-  // TODO(courbet): Provide an automatic fix.
-  i += 2.0;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
-  i += 2.0f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
-
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: narrowing conversion from constant 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i *= 0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: narrowing conversion from constant 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i /= 0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: narrowing conversion from constant 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i += (double)0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[

[PATCH] D54865: [clangd] Auto-index watches global CDB for changes.

2018-11-26 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

LGTM, seems to share a lot of context with what I am preparing for loading 
shards.
Interfaces looks compatible with what I had before, only difference is it was 
more `tooling::CompileCommand` oriented before, now it can only look at 
filenames, which seems more natural.

Thanks!




Comment at: clangd/index/Background.cpp:115
+
+// We shuffle the files so because processing them in a random order should
+// quickly give us good coverage of headers in the project.

s/so //



Comment at: clangd/index/Background.cpp:130
+  if (auto Cmd = CDB.getCompileCommand(File, &Project)) {
+auto *Storage = IndexStorageFactory(Project.SourceRoot);
+enqueueTask(Bind(

In case of an OverlayCDB with some commands set through LSP configuration, we 
might end up `Project.SourceRoot` being an empty string, which will result in 
creating the index storage directory in cwd. I believe we wouldn't want that, 
but not sure if it should be handled by `BackgroundIndex` or 
`DiskBackedIndexStorage`. WDYT?


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54865



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


[PATCH] D54745: [clang-tidy] Don't generate incorrect fixes for class with deleted copy/move constructor in smart_ptr check.

2018-11-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 175205.
hokein marked 3 inline comments as done.
hokein added a comment.

Address review comments.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54745

Files:
  clang-tidy/modernize/MakeSmartPtrCheck.cpp
  test/clang-tidy/modernize-make-unique.cpp

Index: test/clang-tidy/modernize-make-unique.cpp
===
--- test/clang-tidy/modernize-make-unique.cpp
+++ test/clang-tidy/modernize-make-unique.cpp
@@ -32,6 +32,38 @@
 
 struct Empty {};
 
+struct NoCopyMoveCtor {
+  NoCopyMoveCtor(const NoCopyMoveCtor &) = delete; // implies move ctor is deleted
+};
+
+struct NoCopyMoveCtorVisible {
+private:
+  NoCopyMoveCtorVisible(const NoCopyMoveCtorVisible&) = default;
+  NoCopyMoveCtorVisible(NoCopyMoveCtorVisible&&) = default;
+};
+
+struct OnlyMoveCtor {
+  OnlyMoveCtor() = default;
+  OnlyMoveCtor(OnlyMoveCtor&&) = default;
+  OnlyMoveCtor(const OnlyMoveCtor &) = delete;
+};
+
+struct OnlyCopyCtor {
+  OnlyCopyCtor(const OnlyCopyCtor&) = default;
+  OnlyCopyCtor(OnlyCopyCtor&&) = delete;
+};
+
+struct OnlyCopyCtorVisible {
+  OnlyCopyCtorVisible(const OnlyCopyCtorVisible &) = default;
+
+private:
+  OnlyCopyCtorVisible(OnlyCopyCtorVisible &&) = default;
+};
+
+struct ImplicitDeletedCopyCtor {
+  const OnlyMoveCtor ctor;
+};
+
 struct E {
   E(std::initializer_list);
   E();
@@ -274,6 +306,33 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:35: warning: use std::make_unique instead
   // CHECK-FIXES: std::unique_ptr PEmpty = std::make_unique(Empty{});
 
+  // No fixes for classes with deleted copy&move constructors.
+  auto PNoCopyMoveCtor = std::unique_ptr(new NoCopyMoveCtor{});
+  // CHECK-MESSAGES: :[[@LINE-1]]:26: warning: use std::make_unique instead
+  // CHECK-FIXES: auto PNoCopyMoveCtor = std::unique_ptr(new NoCopyMoveCtor{});
+
+  auto PNoCopyMoveCtorVisible = std::unique_ptr(new NoCopyMoveCtorVisible{});
+  // CHECK-MESSAGES: :[[@LINE-1]]:33: warning: use std::make_unique instead
+  // CHECK-FIXES: auto PNoCopyMoveCtorVisible = std::unique_ptr(new NoCopyMoveCtorVisible{});
+
+  auto POnlyMoveCtor = std::unique_ptr(new OnlyMoveCtor{});
+  // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: use std::make_unique instead
+  // CHECK-FIXES: auto POnlyMoveCtor = std::unique_ptr(new OnlyMoveCtor{});
+
+  // Fix for classes with classes with move constructor.
+  auto POnlyCopyCtor = std::unique_ptr(new OnlyCopyCtor{});
+  // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: use std::make_unique instead
+  // CHECK-FIXES: auto POnlyCopyCtor = std::unique_ptr(new OnlyCopyCtor{});
+
+   // Fix for classes with classes with move constructor.
+  auto POnlyCopyCtorVisible = std::unique_ptr(new OnlyCopyCtorVisible{});
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: use std::make_unique instead
+  // CHECK-FIXES: auto POnlyCopyCtorVisible = std::unique_ptr(new OnlyCopyCtorVisible{});
+
+  auto PImplicitDeletedCopyCtor = std::unique_ptr(new ImplicitDeletedCopyCtor{});
+  // CHECK-MESSAGES: :[[@LINE-1]]:35: warning: use std::make_unique instead
+  // CHECK-FIXES: auto PImplicitDeletedCopyCtor = std::unique_ptr(new ImplicitDeletedCopyCtor{});
+
   // Initialization with default constructor.
   std::unique_ptr PE1 = std::unique_ptr(new E{});
   // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead
Index: clang-tidy/modernize/MakeSmartPtrCheck.cpp
===
--- clang-tidy/modernize/MakeSmartPtrCheck.cpp
+++ clang-tidy/modernize/MakeSmartPtrCheck.cpp
@@ -387,6 +387,19 @@
   //   smart_ptr(new Pair{first, second});
   // Has to be replaced with:
   //   smart_ptr(Pair{first, second});
+  //
+  // The fix (std::make_unique) needs to see copy/move constructor of
+  // Pair. If we found any invisible or deleted copy/move constructor, we
+  // stop generating fixes -- as the C++ rule is complicated and we are less
+  // certain about the correct fixes.
+  if (const CXXRecordDecl *RD = New->getType()->getPointeeCXXRecordDecl()) {
+if (llvm::find_if(RD->ctors(), [](const CXXConstructorDecl *Ctor) {
+  return Ctor->isCopyOrMoveConstructor() &&
+ (Ctor->isDeleted() || Ctor->getAccess() == AS_private);
+}) != RD->ctor_end()) {
+  return false;
+}
+  }
   InitRange = SourceRange(
   New->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
   New->getInitializer()->getSourceRange().getEnd());
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r347537 - [clang-tidy] Don't generate incorrect fixes for class with deleted copy constructor in smart_ptr check.

2018-11-26 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Mon Nov 26 01:33:08 2018
New Revision: 347537

URL: http://llvm.org/viewvc/llvm-project?rev=347537&view=rev
Log:
[clang-tidy] Don't generate incorrect fixes for class with deleted copy 
constructor in smart_ptr check.

Summary:
The fix for aggregate initialization (`std::make_unique(Foo {1, 2})` needs
to see Foo copy constructor, otherwise we will have a compiler error. So we
only emit the check warning.

Reviewers: JonasToth, aaron.ballman

Subscribers: xazax.hun, cfe-commits

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

Modified:
clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp

Modified: clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp?rev=347537&r1=347536&r2=347537&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp Mon Nov 
26 01:33:08 2018
@@ -387,6 +387,19 @@ bool MakeSmartPtrCheck::replaceNew(Diagn
   //   smart_ptr(new Pair{first, second});
   // Has to be replaced with:
   //   smart_ptr(Pair{first, second});
+  //
+  // The fix (std::make_unique) needs to see copy/move constructor of
+  // Pair. If we found any invisible or deleted copy/move constructor, we
+  // stop generating fixes -- as the C++ rule is complicated and we are 
less
+  // certain about the correct fixes.
+  if (const CXXRecordDecl *RD = New->getType()->getPointeeCXXRecordDecl()) 
{
+if (llvm::find_if(RD->ctors(), [](const CXXConstructorDecl *Ctor) {
+  return Ctor->isCopyOrMoveConstructor() &&
+ (Ctor->isDeleted() || Ctor->getAccess() == AS_private);
+}) != RD->ctor_end()) {
+  return false;
+}
+  }
   InitRange = SourceRange(
   New->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
   New->getInitializer()->getSourceRange().getEnd());

Modified: clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp?rev=347537&r1=347536&r2=347537&view=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp (original)
+++ clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp Mon Nov 
26 01:33:08 2018
@@ -32,6 +32,38 @@ struct MyVector {
 
 struct Empty {};
 
+struct NoCopyMoveCtor {
+  NoCopyMoveCtor(const NoCopyMoveCtor &) = delete; // implies move ctor is 
deleted
+};
+
+struct NoCopyMoveCtorVisible {
+private:
+  NoCopyMoveCtorVisible(const NoCopyMoveCtorVisible&) = default;
+  NoCopyMoveCtorVisible(NoCopyMoveCtorVisible&&) = default;
+};
+
+struct OnlyMoveCtor {
+  OnlyMoveCtor() = default;
+  OnlyMoveCtor(OnlyMoveCtor&&) = default;
+  OnlyMoveCtor(const OnlyMoveCtor &) = delete;
+};
+
+struct OnlyCopyCtor {
+  OnlyCopyCtor(const OnlyCopyCtor&) = default;
+  OnlyCopyCtor(OnlyCopyCtor&&) = delete;
+};
+
+struct OnlyCopyCtorVisible {
+  OnlyCopyCtorVisible(const OnlyCopyCtorVisible &) = default;
+
+private:
+  OnlyCopyCtorVisible(OnlyCopyCtorVisible &&) = default;
+};
+
+struct ImplicitDeletedCopyCtor {
+  const OnlyMoveCtor ctor;
+};
+
 struct E {
   E(std::initializer_list);
   E();
@@ -274,6 +306,33 @@ void initialization(int T, Base b) {
   // CHECK-MESSAGES: :[[@LINE-1]]:35: warning: use std::make_unique instead
   // CHECK-FIXES: std::unique_ptr PEmpty = 
std::make_unique(Empty{});
 
+  // No fixes for classes with deleted copy&move constructors.
+  auto PNoCopyMoveCtor = std::unique_ptr(new NoCopyMoveCtor{});
+  // CHECK-MESSAGES: :[[@LINE-1]]:26: warning: use std::make_unique instead
+  // CHECK-FIXES: auto PNoCopyMoveCtor = std::unique_ptr(new 
NoCopyMoveCtor{});
+
+  auto PNoCopyMoveCtorVisible = std::unique_ptr(new 
NoCopyMoveCtorVisible{});
+  // CHECK-MESSAGES: :[[@LINE-1]]:33: warning: use std::make_unique instead
+  // CHECK-FIXES: auto PNoCopyMoveCtorVisible = 
std::unique_ptr(new NoCopyMoveCtorVisible{});
+
+  auto POnlyMoveCtor = std::unique_ptr(new OnlyMoveCtor{});
+  // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: use std::make_unique instead
+  // CHECK-FIXES: auto POnlyMoveCtor = std::unique_ptr(new 
OnlyMoveCtor{});
+
+  // Fix for classes with classes with move constructor.
+  auto POnlyCopyCtor = std::unique_ptr(new OnlyCopyCtor{});
+  // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: use std::make_unique instead
+  // CHECK-FIXES: auto POnlyCopyCtor = std::unique_ptr(new 
OnlyCopyCtor{});
+
+   // Fix for classes with classes with move constructor.
+  auto POnlyCopyCtorVisible = std::unique_ptr(new 
OnlyCopyCtorVisible{});
+  // CH

[PATCH] D53751: [ASTImporter] Added Import functions for transition to new API.

2018-11-26 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 175207.
balazske added a comment.

- Split long lines.


Repository:
  rC Clang

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

https://reviews.llvm.org/D53751

Files:
  include/clang/AST/ASTImporter.h
  lib/AST/ASTImporter.cpp

Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -7656,6 +7656,12 @@
 
 ASTImporter::~ASTImporter() = default;
 
+Expected ASTImporter::Import_New(QualType FromT) {
+  QualType ToT = Import(FromT);
+  if (ToT.isNull() && !FromT.isNull())
+return make_error();
+  return ToT;
+}
 QualType ASTImporter::Import(QualType FromT) {
   if (FromT.isNull())
 return {};
@@ -7682,6 +7688,12 @@
   return ToContext.getQualifiedType(*ToTOrErr, FromT.getLocalQualifiers());
 }
 
+Expected ASTImporter::Import_New(TypeSourceInfo *FromTSI) {
+  TypeSourceInfo *ToTSI = Import(FromTSI);
+  if (!ToTSI && FromTSI)
+return llvm::make_error();
+  return ToTSI;
+}
 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
   if (!FromTSI)
 return FromTSI;
@@ -7696,8 +7708,12 @@
   T, Import(FromTSI->getTypeLoc().getBeginLoc()));
 }
 
+Expected ASTImporter::Import_New(const Attr *FromAttr) {
+  return Import(FromAttr);
+}
 Attr *ASTImporter::Import(const Attr *FromAttr) {
   Attr *ToAttr = FromAttr->clone(ToContext);
+  // NOTE: Import of SourceRange may fail.
   ToAttr->setRange(Import(FromAttr->getRange()));
   return ToAttr;
 }
@@ -7715,6 +7731,12 @@
   }
 }
 
+Expected ASTImporter::Import_New(Decl *FromD) {
+  Decl *ToD = Import(FromD);
+  if (!ToD && FromD)
+return llvm::make_error();
+  return ToD;
+}
 Decl *ASTImporter::Import(Decl *FromD) {
   if (!FromD)
 return nullptr;
@@ -7803,6 +7825,12 @@
   return ToDC;
 }
 
+Expected ASTImporter::Import_New(Expr *FromE) {
+  Expr *ToE = Import(FromE);
+  if (!ToE && FromE)
+return llvm::make_error();
+  return ToE;
+}
 Expr *ASTImporter::Import(Expr *FromE) {
   if (!FromE)
 return nullptr;
@@ -7810,6 +7838,12 @@
   return cast_or_null(Import(cast(FromE)));
 }
 
+Expected ASTImporter::Import_New(Stmt *FromS) {
+  Stmt *ToS = Import(FromS);
+  if (!ToS && FromS)
+return llvm::make_error();
+  return ToS;
+}
 Stmt *ASTImporter::Import(Stmt *FromS) {
   if (!FromS)
 return nullptr;
@@ -7845,6 +7879,12 @@
   return *ToSOrErr;
 }
 
+Expected ASTImporter::Import_New(NestedNameSpecifier *FromNNS) {
+  NestedNameSpecifier *ToNNS = Import(FromNNS);
+  if (!ToNNS && FromNNS)
+return llvm::make_error();
+  return ToNNS;
+}
 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
   if (!FromNNS)
 return nullptr;
@@ -7898,6 +7938,10 @@
   llvm_unreachable("Invalid nested name specifier kind");
 }
 
+Expected ASTImporter::Import_New(NestedNameSpecifierLoc FromNNS) {
+  NestedNameSpecifierLoc ToNNS = Import(FromNNS);
+  return ToNNS;
+}
 NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
   // Copied from NestedNameSpecifier mostly.
   SmallVector NestedNames;
@@ -7969,6 +8013,12 @@
   return Builder.getWithLocInContext(getToContext());
 }
 
+Expected ASTImporter::Import_New(TemplateName From) {
+  TemplateName To = Import(From);
+  if (To.isNull() && !From.isNull())
+return llvm::make_error();
+  return To;
+}
 TemplateName ASTImporter::Import(TemplateName From) {
   switch (From.getKind()) {
   case TemplateName::Template:
@@ -8059,6 +8109,12 @@
   llvm_unreachable("Invalid template name kind");
 }
 
+Expected ASTImporter::Import_New(SourceLocation FromLoc) {
+  SourceLocation ToLoc = Import(FromLoc);
+  if (ToLoc.isInvalid() && !FromLoc.isInvalid())
+return llvm::make_error();
+  return ToLoc;
+}
 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
   if (FromLoc.isInvalid())
 return {};
@@ -8073,10 +8129,20 @@
   return ToSM.getComposedLoc(ToFileID, Decomposed.second);
 }
 
+Expected ASTImporter::Import_New(SourceRange FromRange) {
+  SourceRange ToRange = Import(FromRange);
+  return ToRange;
+}
 SourceRange ASTImporter::Import(SourceRange FromRange) {
   return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
 }
 
+Expected ASTImporter::Import_New(FileID FromID) {
+  FileID ToID = Import(FromID);
+  if (ToID.isInvalid() && FromID.isValid())
+return llvm::make_error();
+  return ToID;
+}
 FileID ASTImporter::Import(FileID FromID) {
   llvm::DenseMap::iterator Pos = ImportedFileIDs.find(FromID);
   if (Pos != ImportedFileIDs.end())
@@ -8134,6 +8200,12 @@
   return ToID;
 }
 
+Expected ASTImporter::Import_New(CXXCtorInitializer *From) {
+  CXXCtorInitializer *To = Import(From);
+  if (!To && From)
+return llvm::make_error();
+  return To;
+}
 CXXCtorInitializer *ASTImporter::Import(CXXCtorInitializer *From) {
   Expr *ToExpr = Import(From->getInit());
   if (!ToExpr && From->getInit())
@@ -8179,6 +8251,12 @@
   }
 }
 
+Expected ASTImporter::Import_New(const CX

[PATCH] D54745: [clang-tidy] Don't generate incorrect fixes for class with deleted copy/move constructor in smart_ptr check.

2018-11-26 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL347537: [clang-tidy] Don't generate incorrect fixes for 
class with deleted copy… (authored by hokein, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

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

https://reviews.llvm.org/D54745

Files:
  clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
  clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp

Index: clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
===
--- clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
+++ clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
@@ -387,6 +387,19 @@
   //   smart_ptr(new Pair{first, second});
   // Has to be replaced with:
   //   smart_ptr(Pair{first, second});
+  //
+  // The fix (std::make_unique) needs to see copy/move constructor of
+  // Pair. If we found any invisible or deleted copy/move constructor, we
+  // stop generating fixes -- as the C++ rule is complicated and we are less
+  // certain about the correct fixes.
+  if (const CXXRecordDecl *RD = New->getType()->getPointeeCXXRecordDecl()) {
+if (llvm::find_if(RD->ctors(), [](const CXXConstructorDecl *Ctor) {
+  return Ctor->isCopyOrMoveConstructor() &&
+ (Ctor->isDeleted() || Ctor->getAccess() == AS_private);
+}) != RD->ctor_end()) {
+  return false;
+}
+  }
   InitRange = SourceRange(
   New->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
   New->getInitializer()->getSourceRange().getEnd());
Index: clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp
===
--- clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp
+++ clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp
@@ -32,6 +32,38 @@
 
 struct Empty {};
 
+struct NoCopyMoveCtor {
+  NoCopyMoveCtor(const NoCopyMoveCtor &) = delete; // implies move ctor is deleted
+};
+
+struct NoCopyMoveCtorVisible {
+private:
+  NoCopyMoveCtorVisible(const NoCopyMoveCtorVisible&) = default;
+  NoCopyMoveCtorVisible(NoCopyMoveCtorVisible&&) = default;
+};
+
+struct OnlyMoveCtor {
+  OnlyMoveCtor() = default;
+  OnlyMoveCtor(OnlyMoveCtor&&) = default;
+  OnlyMoveCtor(const OnlyMoveCtor &) = delete;
+};
+
+struct OnlyCopyCtor {
+  OnlyCopyCtor(const OnlyCopyCtor&) = default;
+  OnlyCopyCtor(OnlyCopyCtor&&) = delete;
+};
+
+struct OnlyCopyCtorVisible {
+  OnlyCopyCtorVisible(const OnlyCopyCtorVisible &) = default;
+
+private:
+  OnlyCopyCtorVisible(OnlyCopyCtorVisible &&) = default;
+};
+
+struct ImplicitDeletedCopyCtor {
+  const OnlyMoveCtor ctor;
+};
+
 struct E {
   E(std::initializer_list);
   E();
@@ -274,6 +306,33 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:35: warning: use std::make_unique instead
   // CHECK-FIXES: std::unique_ptr PEmpty = std::make_unique(Empty{});
 
+  // No fixes for classes with deleted copy&move constructors.
+  auto PNoCopyMoveCtor = std::unique_ptr(new NoCopyMoveCtor{});
+  // CHECK-MESSAGES: :[[@LINE-1]]:26: warning: use std::make_unique instead
+  // CHECK-FIXES: auto PNoCopyMoveCtor = std::unique_ptr(new NoCopyMoveCtor{});
+
+  auto PNoCopyMoveCtorVisible = std::unique_ptr(new NoCopyMoveCtorVisible{});
+  // CHECK-MESSAGES: :[[@LINE-1]]:33: warning: use std::make_unique instead
+  // CHECK-FIXES: auto PNoCopyMoveCtorVisible = std::unique_ptr(new NoCopyMoveCtorVisible{});
+
+  auto POnlyMoveCtor = std::unique_ptr(new OnlyMoveCtor{});
+  // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: use std::make_unique instead
+  // CHECK-FIXES: auto POnlyMoveCtor = std::unique_ptr(new OnlyMoveCtor{});
+
+  // Fix for classes with classes with move constructor.
+  auto POnlyCopyCtor = std::unique_ptr(new OnlyCopyCtor{});
+  // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: use std::make_unique instead
+  // CHECK-FIXES: auto POnlyCopyCtor = std::unique_ptr(new OnlyCopyCtor{});
+
+   // Fix for classes with classes with move constructor.
+  auto POnlyCopyCtorVisible = std::unique_ptr(new OnlyCopyCtorVisible{});
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: use std::make_unique instead
+  // CHECK-FIXES: auto POnlyCopyCtorVisible = std::unique_ptr(new OnlyCopyCtorVisible{});
+
+  auto PImplicitDeletedCopyCtor = std::unique_ptr(new ImplicitDeletedCopyCtor{});
+  // CHECK-MESSAGES: :[[@LINE-1]]:35: warning: use std::make_unique instead
+  // CHECK-FIXES: auto PImplicitDeletedCopyCtor = std::unique_ptr(new ImplicitDeletedCopyCtor{});
+
   // Initialization with default constructor.
   std::unique_ptr PE1 = std::unique_ptr(new E{});
   // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
ht

[PATCH] D54865: [clangd] Auto-index watches global CDB for changes.

2018-11-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 3 inline comments as done.
sammccall added inline comments.



Comment at: clangd/index/Background.cpp:130
+  if (auto Cmd = CDB.getCompileCommand(File, &Project)) {
+auto *Storage = IndexStorageFactory(Project.SourceRoot);
+enqueueTask(Bind(

kadircet wrote:
> In case of an OverlayCDB with some commands set through LSP configuration, we 
> might end up `Project.SourceRoot` being an empty string, which will result in 
> creating the index storage directory in cwd. I believe we wouldn't want that, 
> but not sure if it should be handled by `BackgroundIndex` or 
> `DiskBackedIndexStorage`. WDYT?
You're right. To a first approximation, I think that the right behavior is to 
keep indexing in memory and just not persist the shards.
The storage seems like the right layer because:
 - the factory makes it easy to encapsulate this special case
 - we may want to change the strategy in future (e.g. write index files into a 
central location if the builddir is unavailable).

The downside I see is by encapsulating it we can't do things like "downgrade 
priority of indexing if storage isn't available", but we can find ways around 
that if we really want to.

I've added a null storage to this patch which is used if the CDB dir is empty.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54865



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


[PATCH] D54865: [clangd] Auto-index watches global CDB for changes.

2018-11-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 175208.
sammccall marked an inline comment as done.
sammccall added a comment.

If the CDB dir is unknown, don't try to write shards to disk.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54865

Files:
  clangd/GlobalCompilationDatabase.cpp
  clangd/GlobalCompilationDatabase.h
  clangd/index/Background.cpp
  clangd/index/Background.h
  clangd/index/BackgroundIndexStorage.cpp
  unittests/clangd/BackgroundIndexTests.cpp
  unittests/clangd/GlobalCompilationDatabaseTests.cpp
  unittests/clangd/TestFS.cpp
  unittests/clangd/TestFS.h

Index: unittests/clangd/TestFS.h
===
--- unittests/clangd/TestFS.h
+++ unittests/clangd/TestFS.h
@@ -41,7 +41,7 @@
 class MockCompilationDatabase : public GlobalCompilationDatabase {
 public:
   /// If \p Directory is not empty, use that as the Directory field of the
-  /// CompileCommand.
+  /// CompileCommand, and as project SourceRoot.
   ///
   /// If \p RelPathPrefix is not empty, use that as a prefix in front of the
   /// source file name, instead of using an absolute path.
@@ -49,7 +49,7 @@
   StringRef RelPathPrefix = StringRef());
 
   llvm::Optional
-  getCompileCommand(PathRef File) const override;
+  getCompileCommand(PathRef File, ProjectInfo * = nullptr) const override;
 
   std::vector ExtraClangFlags;
 
Index: unittests/clangd/TestFS.cpp
===
--- unittests/clangd/TestFS.cpp
+++ unittests/clangd/TestFS.cpp
@@ -39,7 +39,8 @@
 }
 
 Optional
-MockCompilationDatabase::getCompileCommand(PathRef File) const {
+MockCompilationDatabase::getCompileCommand(PathRef File,
+   ProjectInfo *Project) const {
   if (ExtraClangFlags.empty())
 return None;
 
@@ -58,6 +59,8 @@
 CommandLine.push_back(RelativeFilePath.str());
   }
 
+  if (Project)
+Project->SourceRoot = Directory;
   return {tooling::CompileCommand(
   Directory != StringRef() ? Directory : sys::path::parent_path(File),
   FileName, std::move(CommandLine), "")};
Index: unittests/clangd/GlobalCompilationDatabaseTests.cpp
===
--- unittests/clangd/GlobalCompilationDatabaseTests.cpp
+++ unittests/clangd/GlobalCompilationDatabaseTests.cpp
@@ -41,9 +41,12 @@
   class BaseCDB : public GlobalCompilationDatabase {
   public:
 Optional
-getCompileCommand(StringRef File) const override {
-  if (File == testPath("foo.cc"))
+getCompileCommand(StringRef File, ProjectInfo *Project) const override {
+  if (File == testPath("foo.cc")) {
+if (Project)
+  Project->SourceRoot = testRoot();
 return cmd(File, "-DA=1");
+  }
   return None;
 }
 
Index: unittests/clangd/BackgroundIndexTests.cpp
===
--- unittests/clangd/BackgroundIndexTests.cpp
+++ unittests/clangd/BackgroundIndexTests.cpp
@@ -80,14 +80,15 @@
   llvm::StringMap Storage;
   size_t CacheHits = 0;
   MemoryShardStorage MSS(Storage, CacheHits);
-  BackgroundIndex Idx(Context::empty(), "", FS,
+  OverlayCDB CDB(/*Base=*/nullptr);
+  BackgroundIndex Idx(Context::empty(), "", FS, CDB,
   [&](llvm::StringRef) { return &MSS; });
 
   tooling::CompileCommand Cmd;
   Cmd.Filename = testPath("root/A.cc");
   Cmd.Directory = testPath("root");
   Cmd.CommandLine = {"clang++", "-DA=1", testPath("root/A.cc")};
-  Idx.enqueue(testPath("root"), Cmd);
+  CDB.setCompileCommand(testPath("root"), Cmd);
 
   Idx.blockUntilIdleForTest();
   EXPECT_THAT(
@@ -97,7 +98,7 @@
 
   Cmd.Filename = testPath("root/B.cc");
   Cmd.CommandLine = {"clang++", Cmd.Filename};
-  Idx.enqueue(testPath("root"), Cmd);
+  CDB.setCompileCommand(testPath("root"), Cmd);
 
   Idx.blockUntilIdleForTest();
   // B_CC is dropped as we don't collect symbols from A.h in this compilation.
@@ -136,9 +137,10 @@
   Cmd.CommandLine = {"clang++", testPath("root/A.cc")};
   // Check nothing is loaded from Storage, but A.cc and A.h has been stored.
   {
-BackgroundIndex Idx(Context::empty(), "", FS,
+OverlayCDB CDB(/*Base=*/nullptr);
+BackgroundIndex Idx(Context::empty(), "", FS, CDB,
 [&](llvm::StringRef) { return &MSS; });
-Idx.enqueue(testPath("root"), Cmd);
+CDB.setCompileCommand(testPath("root"), Cmd);
 Idx.blockUntilIdleForTest();
   }
   EXPECT_EQ(CacheHits, 0U);
Index: clangd/index/BackgroundIndexStorage.cpp
===
--- clangd/index/BackgroundIndexStorage.cpp
+++ clangd/index/BackgroundIndexStorage.cpp
@@ -81,6 +81,23 @@
   }
 };
 
+// Doesn't persist index shards anywhere (used when the CDB dir is unknown).
+// We could consider indexing into ~/.clangd/ or so instead.
+class NullStorage : pub

[PATCH] D54865: [clangd] Auto-index watches global CDB for changes.

2018-11-26 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL347538: [clangd] Auto-index watches global CDB for changes. 
(authored by sammccall, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

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

https://reviews.llvm.org/D54865

Files:
  clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp
  clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.h
  clang-tools-extra/trunk/clangd/index/Background.cpp
  clang-tools-extra/trunk/clangd/index/Background.h
  clang-tools-extra/trunk/clangd/index/BackgroundIndexStorage.cpp
  clang-tools-extra/trunk/unittests/clangd/BackgroundIndexTests.cpp
  clang-tools-extra/trunk/unittests/clangd/GlobalCompilationDatabaseTests.cpp
  clang-tools-extra/trunk/unittests/clangd/TestFS.cpp
  clang-tools-extra/trunk/unittests/clangd/TestFS.h

Index: clang-tools-extra/trunk/clangd/index/BackgroundIndexStorage.cpp
===
--- clang-tools-extra/trunk/clangd/index/BackgroundIndexStorage.cpp
+++ clang-tools-extra/trunk/clangd/index/BackgroundIndexStorage.cpp
@@ -81,6 +81,23 @@
   }
 };
 
+// Doesn't persist index shards anywhere (used when the CDB dir is unknown).
+// We could consider indexing into ~/.clangd/ or so instead.
+class NullStorage : public BackgroundIndexStorage {
+public:
+  std::unique_ptr
+  loadShard(llvm::StringRef ShardIdentifier) const override {
+return nullptr;
+  }
+
+  llvm::Error storeShard(llvm::StringRef ShardIdentifier,
+ IndexFileOut Shard) const override {
+vlog("Couldn't find project for {0}, indexing in-memory only",
+ ShardIdentifier);
+return llvm::Error::success();
+  }
+};
+
 // Creates and owns IndexStorages for multiple CDBs.
 class DiskBackedIndexStorageManager {
 public:
@@ -89,7 +106,7 @@
 std::lock_guard Lock(*IndexStorageMapMu);
 auto &IndexStorage = IndexStorageMap[CDBDirectory];
 if (!IndexStorage)
-  IndexStorage = llvm::make_unique(CDBDirectory);
+  IndexStorage = create(CDBDirectory);
 return IndexStorage.get();
   }
 
@@ -97,6 +114,12 @@
   BackgroundIndexStorage *createStorage(llvm::StringRef CDBDirectory);
 
 private:
+  std::unique_ptr create(llvm::StringRef CDBDirectory) {
+if (CDBDirectory.empty())
+  return llvm::make_unique();
+return llvm::make_unique(CDBDirectory);
+  }
+
   llvm::StringMap> IndexStorageMap;
   std::unique_ptr IndexStorageMapMu;
 };
Index: clang-tools-extra/trunk/clangd/index/Background.h
===
--- clang-tools-extra/trunk/clangd/index/Background.h
+++ clang-tools-extra/trunk/clangd/index/Background.h
@@ -12,6 +12,7 @@
 
 #include "Context.h"
 #include "FSProvider.h"
+#include "GlobalCompilationDatabase.h"
 #include "index/FileIndex.h"
 #include "index/Index.h"
 #include "index/Serialization.h"
@@ -64,17 +65,16 @@
   // FIXME: resource-dir injection should be hoisted somewhere common.
   BackgroundIndex(Context BackgroundContext, llvm::StringRef ResourceDir,
   const FileSystemProvider &,
+  const GlobalCompilationDatabase &CDB,
   BackgroundIndexStorage::Factory IndexStorageFactory,
   size_t ThreadPoolSize = llvm::hardware_concurrency());
   ~BackgroundIndex(); // Blocks while the current task finishes.
 
-  // Enqueue a translation unit for indexing.
+  // Enqueue translation units for indexing.
   // The indexing happens in a background thread, so the symbols will be
   // available sometime later.
-  void enqueue(llvm::StringRef Directory, tooling::CompileCommand);
-  // Index all TUs described in the compilation database.
-  void enqueueAll(llvm::StringRef Directory,
-  const tooling::CompilationDatabase &);
+  void enqueue(const std::vector &ChangedFiles);
+  void enqueue(const std::string &File);
 
   // Cause background threads to stop after ther current task, any remaining
   // tasks will be discarded.
@@ -94,6 +94,7 @@
   // configuration
   std::string ResourceDir;
   const FileSystemProvider &FSProvider;
+  const GlobalCompilationDatabase &CDB;
   Context BackgroundContext;
 
   // index state
@@ -109,6 +110,7 @@
   // queue management
   using Task = std::function;
   void run(); // Main loop executed by Thread. Runs tasks from Queue.
+  void enqueueTask(Task T);
   void enqueueLocked(tooling::CompileCommand Cmd,
  BackgroundIndexStorage *IndexStorage);
   std::mutex QueueMu;
@@ -117,6 +119,7 @@
   bool ShouldStop = false;
   std::deque Queue;
   std::vector ThreadPool; // FIXME: Abstract this away.
+  GlobalCompilationDatabase::CommandChanged::Subscription CommandsChanged;
 };
 
 } // namespace clangd
Index: clang-tools-extra/trunk/clangd/index/Background.cpp
===
--- clang-tools-extra/trunk/clangd/index/Ba

[clang-tools-extra] r347538 - [clangd] Auto-index watches global CDB for changes.

2018-11-26 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Mon Nov 26 01:51:50 2018
New Revision: 347538

URL: http://llvm.org/viewvc/llvm-project?rev=347538&view=rev
Log:
[clangd] Auto-index watches global CDB for changes.

Summary:
Instead of receiving compilation commands, auto-index is triggered by just
filenames to reindex, and gets commands from the global comp DB internally.
This has advantages:
 - more of the work can be done asynchronously (fetching compilation commands
   upfront can be slow for large CDBs)
 - we get access to the CDB which can be used to retrieve interpolated commands
   for headers (useful in some cases where the original TU goes away)
 - fits nicely with the filename-only change observation from r347297

The interface to GlobalCompilationDatabase gets extended: when retrieving a
compile command, the GCDB can optionally report the project the file belongs to.
This naturally fits together with getCompileCommand: it's hard to implement one
without the other. But because most callers don't care, I've ended up with an
awkward optional-out-param-in-virtual method pattern - maybe there's a better
one.

This is the main missing integration point between ClangdServer and
BackgroundIndex, after this we should be able to add an auto-index flag.

Reviewers: ioeric, kadircet

Subscribers: MaskRay, jkorous, arphaman, cfe-commits, ilya-biryukov

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

Modified:
clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp
clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.h
clang-tools-extra/trunk/clangd/index/Background.cpp
clang-tools-extra/trunk/clangd/index/Background.h
clang-tools-extra/trunk/clangd/index/BackgroundIndexStorage.cpp
clang-tools-extra/trunk/unittests/clangd/BackgroundIndexTests.cpp
clang-tools-extra/trunk/unittests/clangd/GlobalCompilationDatabaseTests.cpp
clang-tools-extra/trunk/unittests/clangd/TestFS.cpp
clang-tools-extra/trunk/unittests/clangd/TestFS.h

Modified: clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp?rev=347538&r1=347537&r2=347538&view=diff
==
--- clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp (original)
+++ clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp Mon Nov 26 
01:51:50 2018
@@ -38,11 +38,13 @@ DirectoryBasedGlobalCompilationDatabase:
 ~DirectoryBasedGlobalCompilationDatabase() = default;
 
 Optional
-DirectoryBasedGlobalCompilationDatabase::getCompileCommand(PathRef File) const 
{
-  if (auto CDB = getCDBForFile(File)) {
+DirectoryBasedGlobalCompilationDatabase::getCompileCommand(
+PathRef File, ProjectInfo *Project) const {
+  if (auto CDB = getCDBForFile(File, Project)) {
 auto Candidates = CDB->getCompileCommands(File);
-if (!Candidates.empty())
+if (!Candidates.empty()) {
   return std::move(Candidates.front());
+}
   } else {
 log("Failed to find compilation database for {0}", File);
   }
@@ -63,7 +65,8 @@ DirectoryBasedGlobalCompilationDatabase:
 }
 
 tooling::CompilationDatabase *
-DirectoryBasedGlobalCompilationDatabase::getCDBForFile(PathRef File) const {
+DirectoryBasedGlobalCompilationDatabase::getCDBForFile(
+PathRef File, ProjectInfo *Project) const {
   namespace path = sys::path;
   assert((path::is_absolute(File, path::Style::posix) ||
   path::is_absolute(File, path::Style::windows)) &&
@@ -74,10 +77,14 @@ DirectoryBasedGlobalCompilationDatabase:
   std::lock_guard Lock(Mutex);
   if (CompileCommandsDir) {
 std::tie(CDB, Cached) = getCDBInDirLocked(*CompileCommandsDir);
+if (Project && CDB)
+  Project->SourceRoot = *CompileCommandsDir;
   } else {
 for (auto Path = path::parent_path(File); !CDB && !Path.empty();
  Path = path::parent_path(Path)) {
   std::tie(CDB, Cached) = getCDBInDirLocked(Path);
+  if (Project && CDB)
+Project->SourceRoot = Path;
 }
   }
   if (CDB && !Cached)
@@ -95,12 +102,15 @@ OverlayCDB::OverlayCDB(const GlobalCompi
 }
 
 Optional
-OverlayCDB::getCompileCommand(PathRef File) const {
+OverlayCDB::getCompileCommand(PathRef File, ProjectInfo *Project) const {
   {
 std::lock_guard Lock(Mutex);
 auto It = Commands.find(File);
-if (It != Commands.end())
+if (It != Commands.end()) {
+  if (Project)
+Project->SourceRoot = "";
   return It->second;
+}
   }
   return Base ? Base->getCompileCommand(File) : None;
 }

Modified: clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.h?rev=347538&r1=347537&r2=347538&view=diff
==
--- clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.h (original)
+++ clang-tools-extra/trunk/clangd/GlobalCompilationData

[PATCH] D53866: [Preamble] Fix preamble for circular #includes

2018-11-26 Thread Nikolai Kosjar via Phabricator via cfe-commits
nik updated this revision to Diff 175210.
nik added a comment.

> Maybe produce a **fatal** error in the preprocessor? That seems to be the 
> simplest option: the preprocessor is aware it's building the preamble and 
> there's definitely some logic to produce fatal errors in other cases (include 
> not found).
>  A fatal error currently aborts other stages of the compilation pipeline and 
> producing one would make the run of the compiler that tries to produce the 
> preamble fail, giving the empty preamble as a result.

Done. I'm using diag::err_pp_error_opening_file as introducing an new 
artificial diagnostic error that the user will never see feels wrong.

Note that a preamble is generated for fatal errors like an unresolved #include 
and I think that's fine. As such, I need a way to propagate the error up to 
PrecompilePreambleConsumer to avoid writing the preamble. I've done that with 
an extra flag in Preprocessor. An alternative might be to put it into 
PreambleConditionalStackStore (as state? and rename that class to something 
more general?) - what do you think?


Repository:
  rC Clang

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

https://reviews.llvm.org/D53866

Files:
  include/clang/Lex/Preprocessor.h
  include/clang/Serialization/ASTWriter.h
  lib/Frontend/PrecompiledPreamble.cpp
  lib/Lex/PPDirectives.cpp
  test/Index/preamble-cyclic-include.cpp


Index: test/Index/preamble-cyclic-include.cpp
===
--- /dev/null
+++ test/Index/preamble-cyclic-include.cpp
@@ -0,0 +1,9 @@
+// RUN: env CINDEXTEST_EDITING=1 c-index-test -test-annotate-tokens=%s:4:1:8:1 
%s 2>&1 | FileCheck %s
+// CHECK-NOT: error: unterminated conditional directive
+// CHECK-NOT: Skipping: [4:1 - 8:7]
+#ifndef A_H
+#define A_H
+#  include "preamble-cyclic-include.cpp"
+int bar();
+#endif
+
Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -1933,6 +1933,20 @@
 return;
   }
 
+  // Check whether it makes sense to continue preamble generation. We can't
+  // generate a consistent preamble with regard to the conditional stack if the
+  // main file is included again as due to the preamble bounds some directives
+  // (e.g. #endif of a header guard) will never be seen. Since this will lead 
to
+  // confusing errors, abort the preamble generation.
+  if (File && PreambleConditionalStack.isRecording() &&
+  SourceMgr.translateFile(File) == SourceMgr.getMainFileID()) {
+PreambleGenerationFailed = true;
+// Generate a fatal error to skip further processing.
+Diag(FilenameTok.getLocation(), diag::err_pp_error_opening_file) << ""
+ << "";
+return;
+  }
+
   // Should we enter the source file? Set to false if either the source file is
   // known to have no effect beyond its effect on module visibility -- that is,
   // if it's got an include guard that is already defined or is a modular 
header
Index: lib/Frontend/PrecompiledPreamble.cpp
===
--- lib/Frontend/PrecompiledPreamble.cpp
+++ lib/Frontend/PrecompiledPreamble.cpp
@@ -170,6 +170,9 @@
   }
 
   void HandleTranslationUnit(ASTContext &Ctx) override {
+if (getPreprocessor().preambleGenerationFailed())
+  return;
+
 PCHGenerator::HandleTranslationUnit(Ctx);
 if (!hasEmittedPCH())
   return;
Index: include/clang/Serialization/ASTWriter.h
===
--- include/clang/Serialization/ASTWriter.h
+++ include/clang/Serialization/ASTWriter.h
@@ -979,6 +979,7 @@
   ASTWriter &getWriter() { return Writer; }
   const ASTWriter &getWriter() const { return Writer; }
   SmallVectorImpl &getPCH() const { return Buffer->Data; }
+  const Preprocessor &getPreprocessor() const { return PP; }
 
 public:
   PCHGenerator(const Preprocessor &PP, StringRef OutputFile, StringRef 
isysroot,
Index: include/clang/Lex/Preprocessor.h
===
--- include/clang/Lex/Preprocessor.h
+++ include/clang/Lex/Preprocessor.h
@@ -388,6 +388,7 @@
 SmallVector ConditionalStack;
 State ConditionalStackState = Off;
   } PreambleConditionalStack;
+  bool PreambleGenerationFailed = false;
 
   /// The current top of the stack that we're lexing from if
   /// not expanding a macro and we are lexing directly from source code.
@@ -2159,6 +2160,10 @@
   Module *M,
   SourceLocation MLoc);
 
+  bool preambleGenerationFailed() const {
+return PreambleGenerationFailed;
+  }
+
   bool isRecordingPreamble() const {
 return PreambleConditionalStack.isRecording();
   }


Index: test/Index/preamble-cyclic-include.cpp
==

[clang-tools-extra] r347539 - [clangd] Cleanup after landing documentSymbol. NFC

2018-11-26 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Nov 26 01:57:41 2018
New Revision: 347539

URL: http://llvm.org/viewvc/llvm-project?rev=347539&view=rev
Log:
[clangd] Cleanup after landing documentSymbol. NFC

- fix compile error on older gcc in Protocol.cpp,
- remove redundant 'llvm::' qualifiers from Protocol.cpp,
- remove unused variables in AST.cpp

Modified:
clang-tools-extra/trunk/clangd/AST.cpp
clang-tools-extra/trunk/clangd/Protocol.cpp

Modified: clang-tools-extra/trunk/clangd/AST.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/AST.cpp?rev=347539&r1=347538&r2=347539&view=diff
==
--- clang-tools-extra/trunk/clangd/AST.cpp (original)
+++ clang-tools-extra/trunk/clangd/AST.cpp Mon Nov 26 01:57:41 2018
@@ -95,11 +95,11 @@ std::string printName(const ASTContext &
 return Out.str();
   }
   // The name was empty, so present an anonymous entity.
-  if (auto *NS = llvm::dyn_cast(&ND))
+  if (llvm::dyn_cast(&ND))
 return "(anonymous namespace)";
   if (auto *Cls = llvm::dyn_cast(&ND))
 return ("(anonymous " + Cls->getKindName() + ")").str();
-  if (auto *En = llvm::dyn_cast(&ND))
+  if (llvm::dyn_cast(&ND))
 return "(anonymous enum)";
   return "(anonymous)";
 }

Modified: clang-tools-extra/trunk/clangd/Protocol.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Protocol.cpp?rev=347539&r1=347538&r2=347539&view=diff
==
--- clang-tools-extra/trunk/clangd/Protocol.cpp (original)
+++ clang-tools-extra/trunk/clangd/Protocol.cpp Mon Nov 26 01:57:41 2018
@@ -455,11 +455,11 @@ json::Value toJSON(const CodeAction &CA)
   return std::move(CodeAction);
 }
 
-llvm::raw_ostream &operator<<(llvm::raw_ostream &O, const DocumentSymbol &S) {
+raw_ostream &operator<<(raw_ostream &O, const DocumentSymbol &S) {
   return O << S.name << " - " << toJSON(S);
 }
 
-llvm::json::Value toJSON(const DocumentSymbol &S) {
+json::Value toJSON(const DocumentSymbol &S) {
   json::Object Result{{"name", S.name},
   {"kind", static_cast(S.kind)},
   {"range", S.range},
@@ -471,7 +471,8 @@ llvm::json::Value toJSON(const DocumentS
 Result["children"] = S.children;
   if (S.deprecated)
 Result["deprecated"] = true;
-  return Result;
+  // Older gcc cannot compile 'return Result', even though it is legal.
+  return json::Value(std::move(Result));
 }
 
 json::Value toJSON(const WorkspaceEdit &WE) {


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


[PATCH] D53751: [ASTImporter] Added Import functions for transition to new API.

2018-11-26 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 175212.
balazske marked an inline comment as done.
balazske added a comment.

- Split long lines (ASTImporter.cpp).


Repository:
  rC Clang

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

https://reviews.llvm.org/D53751

Files:
  include/clang/AST/ASTImporter.h
  lib/AST/ASTImporter.cpp

Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -7656,6 +7656,12 @@
 
 ASTImporter::~ASTImporter() = default;
 
+Expected ASTImporter::Import_New(QualType FromT) {
+  QualType ToT = Import(FromT);
+  if (ToT.isNull() && !FromT.isNull())
+return make_error();
+  return ToT;
+}
 QualType ASTImporter::Import(QualType FromT) {
   if (FromT.isNull())
 return {};
@@ -7682,6 +7688,12 @@
   return ToContext.getQualifiedType(*ToTOrErr, FromT.getLocalQualifiers());
 }
 
+Expected ASTImporter::Import_New(TypeSourceInfo *FromTSI) {
+  TypeSourceInfo *ToTSI = Import(FromTSI);
+  if (!ToTSI && FromTSI)
+return llvm::make_error();
+  return ToTSI;
+}
 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
   if (!FromTSI)
 return FromTSI;
@@ -7696,8 +7708,12 @@
   T, Import(FromTSI->getTypeLoc().getBeginLoc()));
 }
 
+Expected ASTImporter::Import_New(const Attr *FromAttr) {
+  return Import(FromAttr);
+}
 Attr *ASTImporter::Import(const Attr *FromAttr) {
   Attr *ToAttr = FromAttr->clone(ToContext);
+  // NOTE: Import of SourceRange may fail.
   ToAttr->setRange(Import(FromAttr->getRange()));
   return ToAttr;
 }
@@ -7715,6 +7731,12 @@
   }
 }
 
+Expected ASTImporter::Import_New(Decl *FromD) {
+  Decl *ToD = Import(FromD);
+  if (!ToD && FromD)
+return llvm::make_error();
+  return ToD;
+}
 Decl *ASTImporter::Import(Decl *FromD) {
   if (!FromD)
 return nullptr;
@@ -7803,6 +7825,12 @@
   return ToDC;
 }
 
+Expected ASTImporter::Import_New(Expr *FromE) {
+  Expr *ToE = Import(FromE);
+  if (!ToE && FromE)
+return llvm::make_error();
+  return ToE;
+}
 Expr *ASTImporter::Import(Expr *FromE) {
   if (!FromE)
 return nullptr;
@@ -7810,6 +7838,12 @@
   return cast_or_null(Import(cast(FromE)));
 }
 
+Expected ASTImporter::Import_New(Stmt *FromS) {
+  Stmt *ToS = Import(FromS);
+  if (!ToS && FromS)
+return llvm::make_error();
+  return ToS;
+}
 Stmt *ASTImporter::Import(Stmt *FromS) {
   if (!FromS)
 return nullptr;
@@ -7845,6 +7879,13 @@
   return *ToSOrErr;
 }
 
+Expected
+ASTImporter::Import_New(NestedNameSpecifier *FromNNS) {
+  NestedNameSpecifier *ToNNS = Import(FromNNS);
+  if (!ToNNS && FromNNS)
+return llvm::make_error();
+  return ToNNS;
+}
 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
   if (!FromNNS)
 return nullptr;
@@ -7898,6 +7939,11 @@
   llvm_unreachable("Invalid nested name specifier kind");
 }
 
+Expected
+ASTImporter::Import_New(NestedNameSpecifierLoc FromNNS) {
+  NestedNameSpecifierLoc ToNNS = Import(FromNNS);
+  return ToNNS;
+}
 NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
   // Copied from NestedNameSpecifier mostly.
   SmallVector NestedNames;
@@ -7969,6 +8015,12 @@
   return Builder.getWithLocInContext(getToContext());
 }
 
+Expected ASTImporter::Import_New(TemplateName From) {
+  TemplateName To = Import(From);
+  if (To.isNull() && !From.isNull())
+return llvm::make_error();
+  return To;
+}
 TemplateName ASTImporter::Import(TemplateName From) {
   switch (From.getKind()) {
   case TemplateName::Template:
@@ -8059,6 +8111,12 @@
   llvm_unreachable("Invalid template name kind");
 }
 
+Expected ASTImporter::Import_New(SourceLocation FromLoc) {
+  SourceLocation ToLoc = Import(FromLoc);
+  if (ToLoc.isInvalid() && !FromLoc.isInvalid())
+return llvm::make_error();
+  return ToLoc;
+}
 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
   if (FromLoc.isInvalid())
 return {};
@@ -8073,10 +8131,20 @@
   return ToSM.getComposedLoc(ToFileID, Decomposed.second);
 }
 
+Expected ASTImporter::Import_New(SourceRange FromRange) {
+  SourceRange ToRange = Import(FromRange);
+  return ToRange;
+}
 SourceRange ASTImporter::Import(SourceRange FromRange) {
   return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
 }
 
+Expected ASTImporter::Import_New(FileID FromID) {
+  FileID ToID = Import(FromID);
+  if (ToID.isInvalid() && FromID.isValid())
+return llvm::make_error();
+  return ToID;
+}
 FileID ASTImporter::Import(FileID FromID) {
   llvm::DenseMap::iterator Pos = ImportedFileIDs.find(FromID);
   if (Pos != ImportedFileIDs.end())
@@ -8134,6 +8202,13 @@
   return ToID;
 }
 
+Expected
+ASTImporter::Import_New(CXXCtorInitializer *From) {
+  CXXCtorInitializer *To = Import(From);
+  if (!To && From)
+return llvm::make_error();
+  return To;
+}
 CXXCtorInitializer *ASTImporter::Import(CXXCtorInitializer *From) {
   Expr *ToExpr = Import(From->getInit());
   if (!ToExpr && From->getInit())
@@ -8179,6 

[PATCH] D54832: [clang-tidy] No fixes for auto new expression in smart check

2018-11-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 175216.
hokein marked 3 inline comments as done.
hokein added a comment.

No diagnose this case as well.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54832

Files:
  clang-tidy/modernize/MakeSmartPtrCheck.cpp
  test/clang-tidy/modernize-make-unique.cpp


Index: test/clang-tidy/modernize-make-unique.cpp
===
--- test/clang-tidy/modernize-make-unique.cpp
+++ test/clang-tidy/modernize-make-unique.cpp
@@ -282,6 +282,9 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
   // CHECK-FIXES: PE1 = std::make_unique();
 
+  // No warninags for `auto` new expression.
+  PE1.reset(new auto(E()));
+
   
//
   //  NOTE: For initlializer-list constructors, the check only gives warnings,
   //  and no fixes are generated.
Index: clang-tidy/modernize/MakeSmartPtrCheck.cpp
===
--- clang-tidy/modernize/MakeSmartPtrCheck.cpp
+++ clang-tidy/modernize/MakeSmartPtrCheck.cpp
@@ -120,6 +120,9 @@
 
   if (New->getNumPlacementArgs() != 0)
 return;
+  // Skip when this is a new-expression with `auto`, e.g. new auto(1)
+  if (New->getType()->getPointeeType()->getContainedAutoType())
+return;
 
   // Be conservative for cases where we construct an array without any
   // initalization.


Index: test/clang-tidy/modernize-make-unique.cpp
===
--- test/clang-tidy/modernize-make-unique.cpp
+++ test/clang-tidy/modernize-make-unique.cpp
@@ -282,6 +282,9 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
   // CHECK-FIXES: PE1 = std::make_unique();
 
+  // No warninags for `auto` new expression.
+  PE1.reset(new auto(E()));
+
   //
   //  NOTE: For initlializer-list constructors, the check only gives warnings,
   //  and no fixes are generated.
Index: clang-tidy/modernize/MakeSmartPtrCheck.cpp
===
--- clang-tidy/modernize/MakeSmartPtrCheck.cpp
+++ clang-tidy/modernize/MakeSmartPtrCheck.cpp
@@ -120,6 +120,9 @@
 
   if (New->getNumPlacementArgs() != 0)
 return;
+  // Skip when this is a new-expression with `auto`, e.g. new auto(1)
+  if (New->getType()->getPointeeType()->getContainedAutoType())
+return;
 
   // Be conservative for cases where we construct an array without any
   // initalization.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D54832: [clang-tidy] No fixes for auto new expression in smart check

2018-11-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: test/clang-tidy/modernize-make-unique.cpp:288
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
+  // CHECK-FIXES: PE1.reset(new auto(E()));
+

aaron.ballman wrote:
> It seems like we could also generate the correct replacement for the user 
> here.
> ```
> PE1 = std::make_unique();
> ```
> However, I feel like this isn't worth it in general and the correct behavior 
> is to not diagnose in this situation in the first place -- I don't think 
> anyone will find the `make_unique<>` version to be an improvement over the 
> `new auto()` version. What do you think?
This seems reasonable to me. Also the `new auto()` is very rare even in our 
monolithic repository. 


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54832



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


[PATCH] D54878: [clangd] NFC: Eliminate the unused variable warning.

2018-11-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov accepted this revision.
ilya-biryukov added a comment.

Ah, sorry, landed a cleanup fixing the warnings (rL347539 
)  before seeing this change.
But given that `isa<>` are still better than `dyn_cast<>`, this change might 
still be worth landing.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54878



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


[PATCH] D54253: [OpenCL] Launch opencl-types.cl test only on x86

2018-11-26 Thread Andrew Savonichev via Phabricator via cfe-commits
asavonic added a comment.

>> FWIW, I'd vote for the first revision of this patch. From my
>> 
>>   understanding, the test verifies that libclang is able to parse OpenCL
>>   code correctly. It doesn't do anything specific to x86: target for x86 just
>>   happens to support a set of OpenCL extensions.
> 
> I am trying to understand what exactly does it bring into testing if the code 
> doesn't have anything target specific in there?

It brings the architecture that does not support any OpenCL extension,
thus we check that types are "invalid".

> Tests are not entirely free, so we can't test absolutely everything.

Right. There is no big difference b/w these two revisions, so I'll leave
that to your discretion.


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

https://reviews.llvm.org/D54253



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


[clang-tools-extra] r347546 - [clang-tidy] PrintStackTraceOnErrorSignal

2018-11-26 Thread Alexander Kornienko via cfe-commits
Author: alexfh
Date: Mon Nov 26 03:11:52 2018
New Revision: 347546

URL: http://llvm.org/viewvc/llvm-project?rev=347546&view=rev
Log:
[clang-tidy] PrintStackTraceOnErrorSignal

Modified:
clang-tools-extra/trunk/clang-tidy/tool/ClangTidyMain.cpp

Modified: clang-tools-extra/trunk/clang-tidy/tool/ClangTidyMain.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/tool/ClangTidyMain.cpp?rev=347546&r1=347545&r2=347546&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/tool/ClangTidyMain.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/tool/ClangTidyMain.cpp Mon Nov 26 
03:11:52 2018
@@ -19,6 +19,7 @@
 #include "clang/Config/config.h"
 #include "clang/Tooling/CommonOptionsParser.h"
 #include "llvm/Support/Process.h"
+#include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
 
 using namespace clang::ast_matchers;
@@ -328,6 +329,7 @@ getVfsOverlayFromFile(const std::string
 }
 
 static int clangTidyMain(int argc, const char **argv) {
+  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
   CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
 cl::ZeroOrMore);
   llvm::IntrusiveRefCntPtr BaseFS(


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


[PATCH] D52276: [clangd] Add type boosting in code completion

2018-11-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov marked 4 inline comments as done.
ilya-biryukov added inline comments.



Comment at: clangd/Quality.h:98
+  /// Whether the item matches the type expected in the completion context.
+  bool TypeMatchesPreferred = false;
   /// FIXME: unify with index proximity score - signals should be

sammccall wrote:
> ilya-biryukov wrote:
> > sammccall wrote:
> > > sammccall wrote:
> > > > you've inserted in the middle of the file proximity stuff :-)
> > > Generally we'd put both context/symbol types as the signal here, rather 
> > > than just whether they match, unless it's prohibitive. They'd get 
> > > populated manually, and by merge() overloads, respectively.
> > I did it to avoid inefficiencies of:
> > 1. copying the context type for each completion item,
> > 2. copying the symbol type for each of the indexed items.
> > 
> > My understanding is that (1) can be avoided by storing a reference to a 
> > type, since it outlives the signals.
> > But we'll still have to do a copy for (2), right?
> > 
> > That's probably not a bottleneck anyway, but keeping it a bool flag for now 
> > and happy to change it  to your liking.
> Agree with your analysis.
> 
> I think our goal here should be to have a model with small # of per-symbol 
> types, and small size of each type, so the per-symbol copy would be cheap. 
> Sequencing is tricky - we don't have that optimization yet. Can we replay a 
> session with some code completion and see if it shows up in a profiler?
> 
> (Perfect would be one type per symbol, types are 8-byte hashes. Unfortunately 
> I think pointer->base conversions mean symbols must admit multiple tokens. 
> But I have some ideas...)
After discussing offline, we ended up with a bunch of flags to indicate whether:
1. a symbol or a sema decl had a type,
2. a context had a type,
3. those types were the same.

Let me know if that look ok. The bit that I don't like is that they're computed 
ad-hoc outside the merge function, which is a bit ugly.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D52276



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


[PATCH] D54781: [clangd] Add 'Switch header/source' command in clangd-vscode

2018-11-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

@malaperle, do you want a new release of `vscode-clangd` extension for this?


Repository:
  rL LLVM

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

https://reviews.llvm.org/D54781



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


[clang-tools-extra] r347547 - [clangd] Use testPath in the test.

2018-11-26 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Mon Nov 26 03:18:16 2018
New Revision: 347547

URL: http://llvm.org/viewvc/llvm-project?rev=347547&view=rev
Log:
[clangd] Use testPath in the test.

Modified:
clang-tools-extra/trunk/unittests/clangd/FindSymbolsTests.cpp

Modified: clang-tools-extra/trunk/unittests/clangd/FindSymbolsTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/FindSymbolsTests.cpp?rev=347547&r1=347546&r2=347547&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/FindSymbolsTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/FindSymbolsTests.cpp Mon Nov 26 
03:18:16 2018
@@ -478,7 +478,7 @@ TEST_F(DocumentSymbolsTest, Unnamed) {
 }
 
 TEST_F(DocumentSymbolsTest, InHeaderFile) {
-  addFile("bar.h", R"cpp(
+  addFile(testPath("bar.h"), R"cpp(
   int foo() {
   }
   )cpp");
@@ -488,7 +488,7 @@ TEST_F(DocumentSymbolsTest, InHeaderFile
   int test() {
   }
   )cpp");
-  addFile("foo.cpp", R"cpp(
+  addFile(testPath("foo.cpp"), R"cpp(
   #include "foo.h"
   )cpp");
   EXPECT_THAT(getSymbols(FilePath), ElementsAre(WithName("test")));


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


[PATCH] D52276: [clangd] Add type boosting in code completion

2018-11-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 175223.
ilya-biryukov added a comment.

- Address comments, add more flags to signals


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D52276

Files:
  clangd/CodeComplete.cpp
  clangd/Quality.cpp
  clangd/Quality.h

Index: clangd/Quality.h
===
--- clangd/Quality.h
+++ clangd/Quality.h
@@ -28,6 +28,7 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_QUALITY_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_QUALITY_H
 
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "clang/Sema/CodeCompleteConsumer.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -122,6 +123,13 @@
   // Whether symbol is an instance member of a class.
   bool IsInstanceMember = false;
 
+  // Whether clang provided a preferred type in the completion context.
+  bool HadContextType = false;
+  // Whether a source completion item or a symbol had a type information.
+  bool HadSymbolType = false;
+  // Whether the item matches the type expected in the completion context.
+  bool TypeMatchesPreferred = false;
+
   void merge(const CodeCompletionResult &SemaResult);
   void merge(const Symbol &IndexResult);
 
Index: clangd/Quality.cpp
===
--- clangd/Quality.cpp
+++ clangd/Quality.cpp
@@ -369,6 +369,9 @@
 }
   }
 
+  if (TypeMatchesPreferred)
+Score *= 5.0;
+
   // Penalize non-instance members when they are accessed via a class instance.
   if (!IsInstanceMember &&
   (Context == CodeCompletionContext::CCC_DotMemberAccess ||
@@ -412,6 +415,10 @@
 OS << formatv("\tIndex scope boost: {0}\n",
   scopeBoost(*S.ScopeProximityMatch, S.SymbolScope));
 
+  OS << formatv("\tSema provided preferred type: {0}\n", S.HadContextType);
+  OS << formatv("\tSymbol had type: {0}\n", S.HadSymbolType);
+  OS << formatv("\tType matched preferred: {0}\n", S.TypeMatchesPreferred);
+
   return OS;
 }
 
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -24,6 +24,7 @@
 #include "CodeCompletionStrings.h"
 #include "Compiler.h"
 #include "Diagnostics.h"
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "FuzzyMatch.h"
 #include "Headers.h"
@@ -1225,6 +1226,7 @@
   std::vector QueryScopes; // Initialized once Sema runs.
   // Initialized once QueryScopes is initialized, if there are scopes.
   Optional ScopeProximity;
+  llvm::Optional PreferredType; // Initialized once Sema runs.
   // Whether to query symbols from any scope. Initialized once Sema runs.
   bool AllScopes = false;
   // Include-insertion and proximity scoring rely on the include structure.
@@ -1302,9 +1304,12 @@
   Inserter.reset(); // Make sure this doesn't out-live Clang.
   SPAN_ATTACH(Tracer, "sema_completion_kind",
   getCompletionKindString(Recorder->CCContext.getKind()));
-  log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2})",
+  log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
+  "expected type {3}",
   getCompletionKindString(Recorder->CCContext.getKind()),
-  join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes);
+  join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
+  PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
+: "");
 });
 
 Recorder = RecorderOwner.get();
@@ -1354,6 +1359,9 @@
 getQueryScopes(Recorder->CCContext, *Recorder->CCSema, Opts);
 if (!QueryScopes.empty())
   ScopeProximity.emplace(QueryScopes);
+PreferredType =
+OpaqueType::fromType(Recorder->CCSema->getASTContext(),
+ Recorder->CCContext.getPreferredType());
 // Sema provides the needed context to query the index.
 // FIXME: in addition to querying for extra/overlapping symbols, we should
 //explicitly request symbols corresponding to Sema results.
@@ -1492,6 +1500,8 @@
 Relevance.FileProximityMatch = FileProximity.getPointer();
 if (ScopeProximity)
   Relevance.ScopeProximityMatch = ScopeProximity.getPointer();
+if (PreferredType)
+  Relevance.HadContextType |= true;
 
 auto &First = Bundle.front();
 if (auto FuzzyScore = fuzzyScore(First))
@@ -1506,10 +1516,24 @@
 Relevance.merge(*Candidate.IndexResult);
 Origin |= Candidate.IndexResult->Origin;
 FromIndex = true;
+if (!Candidate.IndexResult->Type.empty())
+  Relevance.HadSymbolType |= true;
+if (PreferredType &&
+PreferredType->raw() == Candidate.IndexResult->Type) {
+  Relevance.TypeMatchesPreferred = true;
+}
   }
   if (Candidate.SemaResult) {
 Quality.merge(*Candidate.SemaResult);
 Relevance.mer

[PATCH] D41005: Reuse preamble even if an unsaved file does not exist

2018-11-26 Thread Nikolai Kosjar via Phabricator via cfe-commits
nik added a comment.

Ping.


Repository:
  rC Clang

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

https://reviews.llvm.org/D41005



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


[PATCH] D54796: [clangd] C++ API for emitting file status

2018-11-26 Thread Jan Korous via Phabricator via cfe-commits
jkorous added a comment.

Hi @hokein, I am just keeping up to date with changes.




Comment at: clangd/ClangdServer.h:39
 
+// FIXME: find a better name.
 class DiagnosticsConsumer {

It would be unfortunate to have this name clashing with 
`clang::DiagnosticsConsumer` indeed.
How about something like `FileEventConsumer`?



Comment at: clangd/TUScheduler.cpp:367
   IdleASTs.take(this);
+  FStatus.messages.push_back("fail to build CompilerInvocation;");
+  Callbacks.onFileUpdated(FStatus);

Wouldn't some different failure status like `FileStatusKind::FailedBuild` be 
appropriate here?


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54796



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


[PATCH] D54796: [clangd] C++ API for emitting file status

2018-11-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

In D54796#1306960 , @hokein wrote:

> There is one thing I'm not certain: should we stop emitting the file status 
> when the file is removed (similar to the behavior of diagnostics)? For 
> example, the file is removed while the AST is building. The current behavior 
> of the patch will emit them.


It would be reasonable to be consistent with diagnostics: stop emitting the 
statuses when ASTWorker was put into shutdown mode.
However, the clients will still need to handle statuses for "removed" files 
somehow: the notifications in the LSP are inherently racy, IIUC there's no way 
to serialize removeFile and status updates if we're processing the requests in 
a (truly) asynchronous manner.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54796



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


Re: [clang-tools-extra] r347498 - [clangd] Add support for hierarchical documentSymbol

2018-11-26 Thread Ilya Biryukov via cfe-commits
Sorry about that, should be fixed in r347539.

On Mon, Nov 26, 2018 at 8:10 AM Mikael Holmén 
wrote:

> Hi Ilya,
>
> This patch doesn't compile for me with clang 3.6.0. I get:
>
> ../tools/clang/tools/extra/clangd/Protocol.cpp:474:10: error: no viable
> conversion from 'json::Object' to 'llvm::json::Value'
>return Result;
>   ^~
> ../include/llvm/Support/JSON.h:291:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'const
> llvm::json::Value &' for 1st argument
>Value(const Value &M) { copyFrom(M); }
>^
> ../include/llvm/Support/JSON.h:292:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'llvm::json::Value
> &&' for 1st argument
>Value(Value &&M) { moveFrom(std::move(M)); }
>^
> ../include/llvm/Support/JSON.h:293:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to
> 'std::initializer_list' for 1st argument
>Value(std::initializer_list Elements);
>^
> ../include/llvm/Support/JSON.h:294:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'json::Array &&' for
> 1st argument
>Value(json::Array &&Elements) : Type(T_Array) {
>^
> ../include/llvm/Support/JSON.h:299:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'json::Object &&' for
> 1st argument
>Value(json::Object &&Properties) : Type(T_Object) {
>^
> ../include/llvm/Support/JSON.h:305:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'std::string' (aka
> 'basic_string') for 1st argument
>Value(std::string V) : Type(T_String) {
>^
> ../include/llvm/Support/JSON.h:312:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'const
> llvm::SmallVectorImpl &' for 1st argument
>Value(const llvm::SmallVectorImpl &V)
>^
> ../include/llvm/Support/JSON.h:314:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'const
> llvm::formatv_object_base &' for 1st argument
>Value(const llvm::formatv_object_base &V) : Value(V.str()){};
>^
> ../include/llvm/Support/JSON.h:316:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'llvm::StringRef' for
> 1st argument
>Value(StringRef V) : Type(T_StringRef) {
>^
> ../include/llvm/Support/JSON.h:323:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'const char *' for
> 1st argument
>Value(const char *V) : Value(StringRef(V)) {}
>^
> ../include/llvm/Support/JSON.h:324:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'std::nullptr_t' (aka
> 'nullptr_t') for 1st argument
>Value(std::nullptr_t) : Type(T_Null) {}
>^
> ../include/llvm/Support/JSON.h:298:3: note: candidate template ignored:
> could not match 'vector allocator >' against 'llvm::json::Object'
>Value(const std::vector &C) : Value(json::Array(C)) {}
>^
> ../include/llvm/Support/JSON.h:303:3: note: candidate template ignored:
> could not match 'map, type-parameter-0-0,
> std::less >, allocator std::basic_string, type-parameter-0-0> > >' against
> 'llvm::json::Object'
>Value(const std::map &C) : Value(json::Object(C)) {}
>^
> ../include/llvm/Support/JSON.h:329:42: note: candidate template ignored:
> disabled by 'enable_if' [with T = llvm::json::Object]
>typename = typename std::enable_if bool>::value>::type,
>   ^
> ../include/llvm/Support/JSON.h:337:42: note: candidate template ignored:
> disabled by 'enable_if' [with T = llvm::json::Object]
>typename = typename
> std::enable_if::value>::type,
>   ^
> ../include/llvm/Support/JSON.h:345:41: note: candidate template ignored:
> disabled by 'enable_if' [with T = llvm::json::Object]
>  typename
> std::enable_if::value>::type,
>  ^
> ../include/llvm/Support/JSON.h:355:3: note: candidate template ignored:
> substitution failure [with T = llvm::json::Object]: no matching function
> for call to 'toJSON'
>Value(const T &V) : Value(toJSON(V)) {}
>^
> 1 error generated.
> ninja: build stopped: subcommand failed.
> system(/proj/flexasic/app/ninja/1.8.2/SLED11-64/bin/ninja -j1 -C
> build-all  all) failed: child exited with value 1
>
>
> A couple of the build bots fail the same way, see e.g:
>
>
>
> http://lab.llvm.org:8011/builders/clang-cmake-armv7-quick/builds/5512/steps/build%20stage%201/logs/stdio
>
>
> -
>
>
> This patch also causes a couple of new warnings:
>
> ../tools/clang/tools/extra/clangd/AST.cpp:98:13: error: unused variable
> 'NS' [-Werror,-Wunused-variable]
>if (auto *NS = llvm::dyn_cast(&ND))
>  ^
> ../tools/clang/tools/extra/clangd/AST.cpp:102:13: error: unused variable
> 'En' [-Werror,-Wunused-variable]
>if (auto *En = ll

[PATCH] D54872: [clangd] Add ability to not use -resource-dir at all

2018-11-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

We have to point clangd into the resource dir, corresponding to the version of 
the headers it was built with. It's important we pick the exact version of the 
built-in headers that clangd was built for.
Note that resource-dir should **only** be used for the built-in headers, any 
compiler-specific libraries should be found using other flags. Could you 
provide an example clang-cl commands that it breaks with?


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54872



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


[PATCH] D54589: [clang][UBSan] Sanitization for alignment assumptions.

2018-11-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

ping


Repository:
  rC Clang

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

https://reviews.llvm.org/D54589



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


[clang-tools-extra] r347548 - [clangd] Tune down scope boost for global scope

2018-11-26 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Mon Nov 26 04:12:01 2018
New Revision: 347548

URL: http://llvm.org/viewvc/llvm-project?rev=347548&view=rev
Log:
[clangd] Tune down scope boost for global scope

Summary:
This improves cross-namespace completions and has ignorable
impact on other completion types.

Metrics
```
==
OVERALL (excl. CROSS_NAMESPACE)
==
  Total measurements: 109367 (-6)
  All measurements:
MRR: 68.11 (+0.04)  Top-1: 58.59% (+0.03%)  Top-5: 80.00% (+0.01%)  
Top-100: 95.92% (-0.02%)
  Full identifiers:
MRR: 98.35 (+0.09)  Top-1: 97.87% (+0.17%)  Top-5: 98.96% (+0.01%)  
Top-100: 99.03% (+0.00%)
  Filter length 0-5:
MRR:  23.20 (+0.05) 58.72 (+0.01)   70.16 (-0.03)   
73.44 (+0.03)   76.24 (+0.00)   80.79 (+0.14)
Top-1:11.90% (+0.03%)   45.07% (+0.03%) 58.49% 
(-0.05%) 62.44% (-0.02%) 66.31% (-0.05%) 72.10% (+0.07%)
Top-5:35.51% (+0.08%)   76.94% (-0.01%) 85.10% 
(-0.13%) 87.40% (-0.02%) 88.65% (+0.01%) 91.84% (+0.17%)
Top-100:  83.25% (-0.02%)   96.61% (-0.15%) 98.15% 
(-0.02%) 98.43% (-0.01%) 98.53% (+0.01%) 98.66% (+0.02%)

==
CROSS_NAMESPACE
==
  Total measurements: 17702 (+27)
  All measurements:
MRR: 28.12 (+3.26)  Top-1: 21.07% (+2.70%)  Top-5: 35.11% (+4.48%)  
Top-100: 74.31% (+1.02%)
  Full identifiers:
MRR: 79.20 (+3.72)  Top-1: 71.78% (+4.86%)  Top-5: 88.39% (+2.84%)  
Top-100: 98.99% (+0.00%)
  Filter length 0-5:
MRR:  0.92 (-0.10)  5.51 (+0.57)18.30 (+2.34)   
21.62 (+3.76)   32.00 (+6.00)   41.55 (+7.61)
Top-1:0.56% (-0.08%)2.44% (+0.15%)  9.82% 
(+1.47%)  12.59% (+2.16%) 21.17% (+4.47%) 30.05% 
(+6.72%)
Top-5:1.20% (-0.15%)7.14% (+1.04%)  25.17% 
(+3.91%) 29.74% (+5.90%) 43.29% (+9.59%) 54.75% (+9.79%)
Top-100:  5.49% (-0.01%)56.22% (+2.59%) 86.69% 
(+1.08%) 89.03% (+2.04%) 93.74% (+0.78%) 96.99% (+0.59%)
```

Reviewers: sammccall

Reviewed By: sammccall

Subscribers: ilya-biryukov, MaskRay, jkorous, arphaman, kadircet, cfe-commits

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

Modified:
clang-tools-extra/trunk/clangd/FileDistance.cpp

Modified: clang-tools-extra/trunk/clangd/FileDistance.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FileDistance.cpp?rev=347548&r1=347547&r2=347548&view=diff
==
--- clang-tools-extra/trunk/clangd/FileDistance.cpp (original)
+++ clang-tools-extra/trunk/clangd/FileDistance.cpp Mon Nov 26 04:12:01 2018
@@ -196,11 +196,11 @@ static FileDistance createScopeFileDista
 // symbols in it, and there is pattern where using-namespace is used in
 // place of enclosing namespaces (e.g. in implementation files).
 if (S == Preferred)
-  Param.Cost = S == "" ? 2 : 0;
+  Param.Cost = S == "" ? 4 : 0;
 else if (Preferred.startswith(S) && !S.empty())
   continue; // just rely on up-traversals.
 else
-  Param.Cost = S == "" ? 5 : 2;
+  Param.Cost = S == "" ? 6 : 2;
 auto Path = scopeToPath(S);
 // The global namespace is not 'near' its children.
 Param.MaxUpTraversals = std::max(Path.second - 1, 0);


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


[PATCH] D54851: [clangd] Tune down scope boost for global scope

2018-11-26 Thread Eric Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE347548: [clangd] Tune down scope boost for global scope 
(authored by ioeric, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D54851?vs=175106&id=175226#toc

Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54851

Files:
  clangd/FileDistance.cpp


Index: clangd/FileDistance.cpp
===
--- clangd/FileDistance.cpp
+++ clangd/FileDistance.cpp
@@ -196,11 +196,11 @@
 // symbols in it, and there is pattern where using-namespace is used in
 // place of enclosing namespaces (e.g. in implementation files).
 if (S == Preferred)
-  Param.Cost = S == "" ? 2 : 0;
+  Param.Cost = S == "" ? 4 : 0;
 else if (Preferred.startswith(S) && !S.empty())
   continue; // just rely on up-traversals.
 else
-  Param.Cost = S == "" ? 5 : 2;
+  Param.Cost = S == "" ? 6 : 2;
 auto Path = scopeToPath(S);
 // The global namespace is not 'near' its children.
 Param.MaxUpTraversals = std::max(Path.second - 1, 0);


Index: clangd/FileDistance.cpp
===
--- clangd/FileDistance.cpp
+++ clangd/FileDistance.cpp
@@ -196,11 +196,11 @@
 // symbols in it, and there is pattern where using-namespace is used in
 // place of enclosing namespaces (e.g. in implementation files).
 if (S == Preferred)
-  Param.Cost = S == "" ? 2 : 0;
+  Param.Cost = S == "" ? 4 : 0;
 else if (Preferred.startswith(S) && !S.empty())
   continue; // just rely on up-traversals.
 else
-  Param.Cost = S == "" ? 5 : 2;
+  Param.Cost = S == "" ? 6 : 2;
 auto Path = scopeToPath(S);
 // The global namespace is not 'near' its children.
 Param.MaxUpTraversals = std::max(Path.second - 1, 0);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [clang-tools-extra] r347498 - [clangd] Add support for hierarchical documentSymbol

2018-11-26 Thread Mikael Holmén via cfe-commits


On 11/26/18 12:41 PM, Ilya Biryukov wrote:
> Sorry about that, should be fixed in r347539.
> 

Yep, thanks!

/Mikael

> On Mon, Nov 26, 2018 at 8:10 AM Mikael Holmén 
> mailto:mikael.hol...@ericsson.com>> wrote:
> 
> Hi Ilya,
> 
> This patch doesn't compile for me with clang 3.6.0. I get:
> 
> ../tools/clang/tools/extra/clangd/Protocol.cpp:474:10: error: no viable
> conversion from 'json::Object' to 'llvm::json::Value'
>     return Result;
>            ^~
> ../include/llvm/Support/JSON.h:291:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'const
> llvm::json::Value &' for 1st argument
>     Value(const Value &M) { copyFrom(M); }
>     ^
> ../include/llvm/Support/JSON.h:292:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'llvm::json::Value
> &&' for 1st argument
>     Value(Value &&M) { moveFrom(std::move(M)); }
>     ^
> ../include/llvm/Support/JSON.h:293:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to
> 'std::initializer_list' for 1st argument
>     Value(std::initializer_list Elements);
>     ^
> ../include/llvm/Support/JSON.h:294:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'json::Array &&' for
> 1st argument
>     Value(json::Array &&Elements) : Type(T_Array) {
>     ^
> ../include/llvm/Support/JSON.h:299:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'json::Object &&'
> for
> 1st argument
>     Value(json::Object &&Properties) : Type(T_Object) {
>     ^
> ../include/llvm/Support/JSON.h:305:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'std::string' (aka
> 'basic_string') for 1st argument
>     Value(std::string V) : Type(T_String) {
>     ^
> ../include/llvm/Support/JSON.h:312:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'const
> llvm::SmallVectorImpl &' for 1st argument
>     Value(const llvm::SmallVectorImpl &V)
>     ^
> ../include/llvm/Support/JSON.h:314:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'const
> llvm::formatv_object_base &' for 1st argument
>     Value(const llvm::formatv_object_base &V) : Value(V.str()){};
>     ^
> ../include/llvm/Support/JSON.h:316:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'llvm::StringRef'
> for
> 1st argument
>     Value(StringRef V) : Type(T_StringRef) {
>     ^
> ../include/llvm/Support/JSON.h:323:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'const char *' for
> 1st argument
>     Value(const char *V) : Value(StringRef(V)) {}
>     ^
> ../include/llvm/Support/JSON.h:324:3: note: candidate constructor not
> viable: no known conversion from 'json::Object' to 'std::nullptr_t'
> (aka
> 'nullptr_t') for 1st argument
>     Value(std::nullptr_t) : Type(T_Null) {}
>     ^
> ../include/llvm/Support/JSON.h:298:3: note: candidate template ignored:
> could not match 'vector allocator >' against 'llvm::json::Object'
>     Value(const std::vector &C) : Value(json::Array(C)) {}
>     ^
> ../include/llvm/Support/JSON.h:303:3: note: candidate template ignored:
> could not match 'map, type-parameter-0-0,
> std::less >, allocator std::basic_string, type-parameter-0-0> > >' against
> 'llvm::json::Object'
>     Value(const std::map &C) :
> Value(json::Object(C)) {}
>     ^
> ../include/llvm/Support/JSON.h:329:42: note: candidate template
> ignored:
> disabled by 'enable_if' [with T = llvm::json::Object]
>         typename = typename std::enable_if bool>::value>::type,
>                                            ^
> ../include/llvm/Support/JSON.h:337:42: note: candidate template
> ignored:
> disabled by 'enable_if' [with T = llvm::json::Object]
>         typename = typename
> std::enable_if::value>::type,
>                                            ^
> ../include/llvm/Support/JSON.h:345:41: note: candidate template
> ignored:
> disabled by 'enable_if' [with T = llvm::json::Object]
>                   typename
> std::enable_if::value>::type,
>                                           ^
> ../include/llvm/Support/JSON.h:355:3: note: candidate template ignored:
> substitution failure [with T = llvm::json::Object]: no matching
> function
> for call to 'toJSON'
>     Value(const T &V) : Value(toJSON(V)) {}
>     ^
> 1 error generated.
> ninja: build stopped: subcommand failed.
> system(/proj/flexasic/app/ninja/1.8.2/SLED11-64/bin/ninja -j1 -C
> build-all  

[PATCH] D54832: [clang-tidy] No fixes for auto new expression in smart check

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

LGTM with a minor typo to correct.




Comment at: test/clang-tidy/modernize-make-unique.cpp:285
 
+  // No warninags for `auto` new expression.
+  PE1.reset(new auto(E()));

warninags -> warnings


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54832



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


[PATCH] D54832: [clang-tidy] No fixes for auto new expression in smart check

2018-11-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 175227.
hokein marked 2 inline comments as done.
hokein added a comment.

Fix a typo.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54832

Files:
  clang-tidy/modernize/MakeSmartPtrCheck.cpp
  test/clang-tidy/modernize-make-unique.cpp


Index: test/clang-tidy/modernize-make-unique.cpp
===
--- test/clang-tidy/modernize-make-unique.cpp
+++ test/clang-tidy/modernize-make-unique.cpp
@@ -282,6 +282,9 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
   // CHECK-FIXES: PE1 = std::make_unique();
 
+  // No warnings for `auto` new expression.
+  PE1.reset(new auto(E()));
+
   
//
   //  NOTE: For initlializer-list constructors, the check only gives warnings,
   //  and no fixes are generated.
Index: clang-tidy/modernize/MakeSmartPtrCheck.cpp
===
--- clang-tidy/modernize/MakeSmartPtrCheck.cpp
+++ clang-tidy/modernize/MakeSmartPtrCheck.cpp
@@ -120,6 +120,9 @@
 
   if (New->getNumPlacementArgs() != 0)
 return;
+  // Skip when this is a new-expression with `auto`, e.g. new auto(1)
+  if (New->getType()->getPointeeType()->getContainedAutoType())
+return;
 
   // Be conservative for cases where we construct an array without any
   // initalization.


Index: test/clang-tidy/modernize-make-unique.cpp
===
--- test/clang-tidy/modernize-make-unique.cpp
+++ test/clang-tidy/modernize-make-unique.cpp
@@ -282,6 +282,9 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
   // CHECK-FIXES: PE1 = std::make_unique();
 
+  // No warnings for `auto` new expression.
+  PE1.reset(new auto(E()));
+
   //
   //  NOTE: For initlializer-list constructors, the check only gives warnings,
   //  and no fixes are generated.
Index: clang-tidy/modernize/MakeSmartPtrCheck.cpp
===
--- clang-tidy/modernize/MakeSmartPtrCheck.cpp
+++ clang-tidy/modernize/MakeSmartPtrCheck.cpp
@@ -120,6 +120,9 @@
 
   if (New->getNumPlacementArgs() != 0)
 return;
+  // Skip when this is a new-expression with `auto`, e.g. new auto(1)
+  if (New->getType()->getPointeeType()->getContainedAutoType())
+return;
 
   // Be conservative for cases where we construct an array without any
   // initalization.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D54832: [clang-tidy] No fixes for auto new expression in smart check

2018-11-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

Thanks for the quick review.




Comment at: test/clang-tidy/modernize-make-unique.cpp:285
 
+  // No warninags for `auto` new expression.
+  PE1.reset(new auto(E()));

aaron.ballman wrote:
> warninags -> warnings
oops...


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54832



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


[clang-tools-extra] r347551 - [clang-tidy] No warning for auto new expression in smart check

2018-11-26 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Mon Nov 26 04:42:08 2018
New Revision: 347551

URL: http://llvm.org/viewvc/llvm-project?rev=347551&view=rev
Log:
[clang-tidy] No warning for auto new expression in smart check

Summary: The fix for `auto` new expression is illegal.

Reviewers: aaron.ballman

Subscribers: xazax.hun, cfe-commits

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

Modified:
clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp

Modified: clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp?rev=347551&r1=347550&r2=347551&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp Mon Nov 
26 04:42:08 2018
@@ -120,6 +120,9 @@ void MakeSmartPtrCheck::check(const Matc
 
   if (New->getNumPlacementArgs() != 0)
 return;
+  // Skip when this is a new-expression with `auto`, e.g. new auto(1)
+  if (New->getType()->getPointeeType()->getContainedAutoType())
+return;
 
   // Be conservative for cases where we construct an array without any
   // initalization.

Modified: clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp?rev=347551&r1=347550&r2=347551&view=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp (original)
+++ clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp Mon Nov 
26 04:42:08 2018
@@ -341,6 +341,9 @@ void initialization(int T, Base b) {
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
   // CHECK-FIXES: PE1 = std::make_unique();
 
+  // No warnings for `auto` new expression.
+  PE1.reset(new auto(E()));
+
   
//
   //  NOTE: For initlializer-list constructors, the check only gives warnings,
   //  and no fixes are generated.


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


[PATCH] D54832: [clang-tidy] No fixes for auto new expression in smart check

2018-11-26 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE347551: [clang-tidy] No warning for auto new expression in 
smart check (authored by hokein, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D54832?vs=175227&id=175228#toc

Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54832

Files:
  clang-tidy/modernize/MakeSmartPtrCheck.cpp
  test/clang-tidy/modernize-make-unique.cpp


Index: test/clang-tidy/modernize-make-unique.cpp
===
--- test/clang-tidy/modernize-make-unique.cpp
+++ test/clang-tidy/modernize-make-unique.cpp
@@ -341,6 +341,9 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
   // CHECK-FIXES: PE1 = std::make_unique();
 
+  // No warnings for `auto` new expression.
+  PE1.reset(new auto(E()));
+
   
//
   //  NOTE: For initlializer-list constructors, the check only gives warnings,
   //  and no fixes are generated.
Index: clang-tidy/modernize/MakeSmartPtrCheck.cpp
===
--- clang-tidy/modernize/MakeSmartPtrCheck.cpp
+++ clang-tidy/modernize/MakeSmartPtrCheck.cpp
@@ -120,6 +120,9 @@
 
   if (New->getNumPlacementArgs() != 0)
 return;
+  // Skip when this is a new-expression with `auto`, e.g. new auto(1)
+  if (New->getType()->getPointeeType()->getContainedAutoType())
+return;
 
   // Be conservative for cases where we construct an array without any
   // initalization.


Index: test/clang-tidy/modernize-make-unique.cpp
===
--- test/clang-tidy/modernize-make-unique.cpp
+++ test/clang-tidy/modernize-make-unique.cpp
@@ -341,6 +341,9 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
   // CHECK-FIXES: PE1 = std::make_unique();
 
+  // No warnings for `auto` new expression.
+  PE1.reset(new auto(E()));
+
   //
   //  NOTE: For initlializer-list constructors, the check only gives warnings,
   //  and no fixes are generated.
Index: clang-tidy/modernize/MakeSmartPtrCheck.cpp
===
--- clang-tidy/modernize/MakeSmartPtrCheck.cpp
+++ clang-tidy/modernize/MakeSmartPtrCheck.cpp
@@ -120,6 +120,9 @@
 
   if (New->getNumPlacementArgs() != 0)
 return;
+  // Skip when this is a new-expression with `auto`, e.g. new auto(1)
+  if (New->getType()->getPointeeType()->getContainedAutoType())
+return;
 
   // Be conservative for cases where we construct an array without any
   // initalization.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D53488: [clang-tidy] Improving narrowing conversions

2018-11-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

I think we're almost there -- I had a few outstanding questions about the 
config options in the tests and making sure we cover all the cases.




Comment at: 
test/clang-tidy/cppcoreguidelines-narrowing-conversions-castingliterals-option.cpp:3
+// RUN: -config="{CheckOptions: [ \
+// RUN:   {key: 
"cppcoreguidelines-narrowing-conversions.WarnOnFloatingPointNarrowingConversion",
 value: 0}, \
+// RUN:   {key: "cppcoreguidelines-narrowing-conversions.PedanticMode", value: 
1} \

No need for this setting?



Comment at: 
test/clang-tidy/cppcoreguidelines-narrowing-conversions-long-is-32bits.cpp:2-5
+// RUN: -config="{CheckOptions: [ \
+// RUN:   {key: 
"cppcoreguidelines-narrowing-conversions.WarnOnFloatingPointNarrowingConversion",
 value: 0}, \
+// RUN:   {key: "cppcoreguidelines-narrowing-conversions.PedanticMode", value: 
0} \
+// RUN: ]}" \

No need for any of these settings?



Comment at: 
test/clang-tidy/cppcoreguidelines-narrowing-conversions-narrowingfloatingpoint-option.cpp:2-5
+// RUN: -config="{CheckOptions: [ \
+// RUN:   {key: 
"cppcoreguidelines-narrowing-conversions.WarnOnFloatingPointNarrowingConversion",
 value: 1}, \
+// RUN:   {key: "cppcoreguidelines-narrowing-conversions.PedanticMode", value: 
0} \
+// RUN: ]}" \

You can drop these lines, I believe, because they match the default values.



Comment at: 
test/clang-tidy/cppcoreguidelines-narrowing-conversions-unsigned-char.cpp:2-5
+// RUN: -config="{CheckOptions: [ \
+// RUN:   {key: 
"cppcoreguidelines-narrowing-conversions.WarnOnFloatingPointNarrowingConversion",
 value: 0}, \
+// RUN:   {key: "cppcoreguidelines-narrowing-conversions.PedanticMode", value: 
0} \
+// RUN: ]}" \

No need for these settings?


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D53488



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


[PATCH] D54799: [clangd][WIP] textDocument/CursorInfo method

2018-11-26 Thread Jan Korous via Phabricator via cfe-commits
jkorous marked 8 inline comments as done.
jkorous added a comment.

Thank you very much for the review Sam!

I am going to write proper unit tests and then just wait for Alex and Ben to 
take a look.




Comment at: clangd/XRefs.cpp:785
+}
+Results.emplace_back(std::move(NewSymbol));
+  }

sammccall wrote:
> nit: push_back (and below)
Sure, no problem. I have to admit I thought these two are the same but I guess 
you pointed this out because there's a functional difference. I'd appreciate if 
you could advise where can I learn the details.


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

https://reviews.llvm.org/D54799



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


[PATCH] D54799: [clangd][WIP] textDocument/CursorInfo method

2018-11-26 Thread Jan Korous via Phabricator via cfe-commits
jkorous updated this revision to Diff 175229.
jkorous marked an inline comment as done.
jkorous added a comment.

Addressed comments from the reivew.


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

https://reviews.llvm.org/D54799

Files:
  clangd/CMakeLists.txt
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/Protocol.cpp
  clangd/Protocol.h
  clangd/XRefs.cpp
  clangd/XRefs.h
  clangd/index/Index.cpp
  clangd/index/Index.h
  clangd/index/SymbolID.cpp
  clangd/index/SymbolID.h
  test/clangd/symbol-info.test

Index: test/clangd/symbol-info.test
===
--- /dev/null
+++ test/clangd/symbol-info.test
@@ -0,0 +1,46 @@
+# RUN: clangd -lit-test < %s | FileCheck %s
+{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
+---
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///simple.cpp","languageId":"cpp","version":1,"text":"void foo(); int main() { foo(); }\n"}}}
+---
+{"jsonrpc":"2.0","id":1,"method":"textDocument/symbolInfo","params":{"textDocument":{"uri":"test:///simple.cpp"},"position":{"line":0,"character":27}}}
+#  CHECK:"containerName": null,
+# CHECK-NEXT:"id": "CA2EBE44A1D76D2A1547D47BC6D51EBF",
+# CHECK-NEXT:"name": "foo",
+# CHECK-NEXT:"usr": "c:@F@foo#"
+---
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///nested-decl.cpp","languageId":"cpp","version":1,"text":"namespace nnn { struct aaa {}; void foo() { aaa a; }; }"}}}
+---
+{"jsonrpc":"2.0","id":1,"method":"textDocument/symbolInfo","params":{"textDocument":{"uri":"test:///nested-decl.cpp"},"position":{"line":0,"character":46}}}
+#  CHECK:"containerName": "nnn::",
+# CHECK-NEXT:"id": "20237FF18EB405D842456DC5D578426D",
+# CHECK-NEXT:"name": "aaa",
+# CHECK-NEXT:"usr": "c:@N@nnn@S@aaa"
+---
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///reference.cpp","languageId":"cpp","version":1,"text":"int value; void foo(int) {} void bar() { foo(value); }"}}}
+---
+{"jsonrpc":"2.0","id":1,"method":"textDocument/symbolInfo","params":{"textDocument":{"uri":"test:///reference.cpp"},"position":{"line":0,"character":48}}}
+#  CHECK:"containerName": null,
+# CHECK-NEXT:"id": "844613FB2393C9D40A2AFF25D5D316A1",
+# CHECK-NEXT:"name": "value",
+# CHECK-NEXT:"usr": "c:@value"
+---
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///local.cpp","languageId":"cpp","version":1,"text":"void foo() { int aaa; int bbb = aaa; }"}}}
+---
+{"jsonrpc":"2.0","id":1,"method":"textDocument/symbolInfo","params":{"textDocument":{"uri":"test:///local.cpp"},"position":{"line":0,"character":33}}}
+#  CHECK:"containerName": "foo",
+# CHECK-NEXT:"id": "C05589F2664B06F392C2C438568E55E0",
+# CHECK-NEXT:"name": "aaa",
+# CHECK-NEXT:"usr": "c:local.cpp@13@F@foo#@aaa"
+---
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///macro.cpp","languageId":"cpp","version":1,"text":"#define MACRO 5\nint i = MACRO;"}}}
+---
+{"jsonrpc":"2.0","id":1,"method":"textDocument/symbolInfo","params":{"textDocument":{"uri":"test:///macro.cpp"},"position":{"line":1,"character":11}}}
+#  CHECK:"containerName": null,
+# CHECK-NEXT:"id": "29EB506CBDF1BA6D1B6EC203FF03B384",
+# CHECK-NEXT:"name": "MACRO",
+# CHECK-NEXT:"usr": "c:macro.cpp@24@macro@MACRO"
+---
+{"jsonrpc":"2.0","id":3,"method":"shutdown"}
+---
+{"jsonrpc":"2.0","method":"exit"}
Index: clangd/index/SymbolID.h
===
--- /dev/null
+++ clangd/index/SymbolID.h
@@ -0,0 +1,67 @@
+//===--- SymbolID.h --*- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_SYMBOLID_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_SYMBOLID_H
+
+#include "llvm/ADT/Hashing.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Error.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+#include 
+
+namespace clang {
+namespace clangd {
+
+// The class identifies a particular C++ symbol (class, function, method, etc).
+//
+// As USRs (Unified Symbol Resolution) could be large, especially for functions
+// with long type arguments, SymbolID is using truncated SHA1(USR) values to
+// guarantee the uniqueness of symbols while using a relatively small amount of
+// memory (vs storing USRs directly).
+//
+// SymbolID can be used as key in the symbol indexes to lookup the symbol.
+class SymbolID {
+public

[PATCH] D54799: [clangd][WIP] textDocument/CursorInfo method

2018-11-26 Thread Jan Korous via Phabricator via cfe-commits
jkorous updated this revision to Diff 175230.
jkorous added a comment.

Removed empty line noise and fixed doxygen annotation.


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

https://reviews.llvm.org/D54799

Files:
  clangd/CMakeLists.txt
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/Protocol.cpp
  clangd/Protocol.h
  clangd/XRefs.cpp
  clangd/XRefs.h
  clangd/index/Index.cpp
  clangd/index/Index.h
  clangd/index/SymbolID.cpp
  clangd/index/SymbolID.h
  test/clangd/symbol-info.test

Index: test/clangd/symbol-info.test
===
--- /dev/null
+++ test/clangd/symbol-info.test
@@ -0,0 +1,46 @@
+# RUN: clangd -lit-test < %s | FileCheck %s
+{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
+---
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///simple.cpp","languageId":"cpp","version":1,"text":"void foo(); int main() { foo(); }\n"}}}
+---
+{"jsonrpc":"2.0","id":1,"method":"textDocument/symbolInfo","params":{"textDocument":{"uri":"test:///simple.cpp"},"position":{"line":0,"character":27}}}
+#  CHECK:"containerName": null,
+# CHECK-NEXT:"id": "CA2EBE44A1D76D2A1547D47BC6D51EBF",
+# CHECK-NEXT:"name": "foo",
+# CHECK-NEXT:"usr": "c:@F@foo#"
+---
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///nested-decl.cpp","languageId":"cpp","version":1,"text":"namespace nnn { struct aaa {}; void foo() { aaa a; }; }"}}}
+---
+{"jsonrpc":"2.0","id":1,"method":"textDocument/symbolInfo","params":{"textDocument":{"uri":"test:///nested-decl.cpp"},"position":{"line":0,"character":46}}}
+#  CHECK:"containerName": "nnn::",
+# CHECK-NEXT:"id": "20237FF18EB405D842456DC5D578426D",
+# CHECK-NEXT:"name": "aaa",
+# CHECK-NEXT:"usr": "c:@N@nnn@S@aaa"
+---
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///reference.cpp","languageId":"cpp","version":1,"text":"int value; void foo(int) {} void bar() { foo(value); }"}}}
+---
+{"jsonrpc":"2.0","id":1,"method":"textDocument/symbolInfo","params":{"textDocument":{"uri":"test:///reference.cpp"},"position":{"line":0,"character":48}}}
+#  CHECK:"containerName": null,
+# CHECK-NEXT:"id": "844613FB2393C9D40A2AFF25D5D316A1",
+# CHECK-NEXT:"name": "value",
+# CHECK-NEXT:"usr": "c:@value"
+---
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///local.cpp","languageId":"cpp","version":1,"text":"void foo() { int aaa; int bbb = aaa; }"}}}
+---
+{"jsonrpc":"2.0","id":1,"method":"textDocument/symbolInfo","params":{"textDocument":{"uri":"test:///local.cpp"},"position":{"line":0,"character":33}}}
+#  CHECK:"containerName": "foo",
+# CHECK-NEXT:"id": "C05589F2664B06F392C2C438568E55E0",
+# CHECK-NEXT:"name": "aaa",
+# CHECK-NEXT:"usr": "c:local.cpp@13@F@foo#@aaa"
+---
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///macro.cpp","languageId":"cpp","version":1,"text":"#define MACRO 5\nint i = MACRO;"}}}
+---
+{"jsonrpc":"2.0","id":1,"method":"textDocument/symbolInfo","params":{"textDocument":{"uri":"test:///macro.cpp"},"position":{"line":1,"character":11}}}
+#  CHECK:"containerName": null,
+# CHECK-NEXT:"id": "29EB506CBDF1BA6D1B6EC203FF03B384",
+# CHECK-NEXT:"name": "MACRO",
+# CHECK-NEXT:"usr": "c:macro.cpp@24@macro@MACRO"
+---
+{"jsonrpc":"2.0","id":3,"method":"shutdown"}
+---
+{"jsonrpc":"2.0","method":"exit"}
Index: clangd/index/SymbolID.h
===
--- /dev/null
+++ clangd/index/SymbolID.h
@@ -0,0 +1,67 @@
+//===--- SymbolID.h --*- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_SYMBOLID_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_SYMBOLID_H
+
+#include "llvm/ADT/Hashing.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Error.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+#include 
+
+namespace clang {
+namespace clangd {
+
+// The class identifies a particular C++ symbol (class, function, method, etc).
+//
+// As USRs (Unified Symbol Resolution) could be large, especially for functions
+// with long type arguments, SymbolID is using truncated SHA1(USR) values to
+// guarantee the uniqueness of symbols while using a relatively small amount of
+// memory (vs storing USRs directly).
+//
+// SymbolID can be used as key in the symbol indexes to lookup the symbol.
+class SymbolID {
+public:
+  SymbolID() = defau

[PATCH] D53488: [clang-tidy] Improving narrowing conversions

2018-11-26 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet updated this revision to Diff 175231.
gchatelet marked 4 inline comments as done.
gchatelet added a comment.

- Removed redundant options in regression tests


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D53488

Files:
  clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
  clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/cppcoreguidelines-narrowing-conversions.rst
  test/clang-tidy/cppcoreguidelines-narrowing-conversions-long-is-32bits.cpp
  
test/clang-tidy/cppcoreguidelines-narrowing-conversions-narrowingfloatingpoint-option.cpp
  
test/clang-tidy/cppcoreguidelines-narrowing-conversions-pedanticmode-option.cpp
  test/clang-tidy/cppcoreguidelines-narrowing-conversions-unsigned-char.cpp
  test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp

Index: test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp
===
--- test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp
+++ test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp
@@ -1,4 +1,8 @@
-// RUN: %check_clang_tidy %s cppcoreguidelines-narrowing-conversions %t
+// RUN: %check_clang_tidy %s cppcoreguidelines-narrowing-conversions %t \
+// RUN: -config="{CheckOptions: [ \
+// RUN:   {key: "cppcoreguidelines-narrowing-conversions.WarnOnFloatingPointNarrowingConversion", value: 0}, \
+// RUN: ]}" \
+// RUN: -- -target x86_64-unknown-linux -fsigned-char
 
 float ceil(float);
 namespace std {
@@ -9,47 +13,282 @@
 namespace floats {
 
 struct ConvertsToFloat {
-  operator float() const { return 0.5; }
+  operator float() const { return 0.5f; }
 };
 
-float operator "" _Pa(unsigned long long);
+float operator"" _float(unsigned long long);
 
-void not_ok(double d) {
+void narrow_fp_to_int_not_ok(double d) {
   int i = 0;
   i = d;
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
   i = 0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from constant 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i = static_cast(d);
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i = ConvertsToFloat();
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
-  i = 15_Pa;
+  i = 15_float;
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
-}
-
-void not_ok_binary_ops(double d) {
-  int i = 0;
+  i += d;
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
   i += 0.5;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: narrowing conversion from constant 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
   i += 0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
-  i += d;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
-  // We warn on the following even though it's not dangerous because there is no
-  // reason to use a double literal here.
-  // TODO(courbet): Provide an automatic fix.
-  i += 2.0;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
-  i += 2.0f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
-
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: narrowing conversion from constant 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i *= 0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: narrowing conversion from constant 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i /= 0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: narrowing conversion from constant 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i += (double)0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning

[PATCH] D54799: [clangd][WIP] textDocument/SymbolInfo method

2018-11-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

LG from my side.
If you have unit tests in the next couple of days, happy to take a look, 
otherwise go ahead once Alex/Ben are happy.

(I'm at work today/tomorrow and then I'm going to be away through new year's, 
so don't wait for me)




Comment at: clangd/ClangdServer.cpp:529
+
+  WorkScheduler.runWithAST("CursorInfo", File, Bind(Action, std::move(CB)));
+}

sammccall wrote:
> nit: SymbolInfo
(This still says CursorInfo in the runWithAST call)



Comment at: clangd/ClangdServer.h:204
 
+  /// Get symbol info for given position.
+  void symbolInfo(PathRef File, Position Pos,

Maybe mention "clangd extension" here.
We should really set up some more structured docs for these one day, but a 
comment is something.



Comment at: clangd/Protocol.cpp:429
+  return json::Object{
+  {"name", P.name},
+  {"containerName", P.containerName},

sammccall wrote:
> for each of the attributes that can be logically absent, we should probably 
> serialize it conditionally (or serialize it as null).
> 
> We're usually happy enough to use sentinel values like "" to mean missing 
> internally, but we try not to send them over the wire.
> (SymbolInformation isn't a great example unfortunately...)
elsewhere we tend to write:

```
json::Object Result{
 ... mandatory fields ...
};
```
if (!P.name.empty())
  Result["name"] = P.name;
```

etc. I find this a little bit more readable than the ternary expressions (due 
to the need for conversions) but up to you.



Comment at: clangd/XRefs.cpp:785
+}
+Results.emplace_back(std::move(NewSymbol));
+  }

jkorous wrote:
> sammccall wrote:
> > nit: push_back (and below)
> Sure, no problem. I have to admit I thought these two are the same but I 
> guess you pointed this out because there's a functional difference. I'd 
> appreciate if you could advise where can I learn the details.
Here the behavior is identical, so this is really a style thing.

`emplace_back` is a more powerful function, with semantics "make a new 
element": it will forward *any* argument list to a constructor of Symbol, 
selected by overload resolution.

`push_back` is a more constrained function, with semantics "insert this 
element": it takes one Symbol and forwards it to the move constructor (or copy 
constructor, as appropriate).

They're equivalent here because `emplace_back` can select the move-constructor 
when passed a single `Symbol&&`. But it communicates intent less clearly, so 
humans have a harder time (harder to understand the code) as does the compiler 
(error messages are worse).


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

https://reviews.llvm.org/D54799



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


[PATCH] D53488: [clang-tidy] Improving narrowing conversions

2018-11-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM!


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D53488



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


[PATCH] D54878: [clangd] NFC: Eliminate the unused variable warning.

2018-11-26 Thread Henry Wong via Phabricator via cfe-commits
MTC updated this revision to Diff 175232.
MTC added a comment.

Use more concise form.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54878

Files:
  clangd/AST.cpp


Index: clangd/AST.cpp
===
--- clangd/AST.cpp
+++ clangd/AST.cpp
@@ -95,11 +95,11 @@
 return Out.str();
   }
   // The name was empty, so present an anonymous entity.
-  if (llvm::dyn_cast(&ND))
+  if (isa(ND))
 return "(anonymous namespace)";
   if (auto *Cls = llvm::dyn_cast(&ND))
 return ("(anonymous " + Cls->getKindName() + ")").str();
-  if (llvm::dyn_cast(&ND))
+  if (isa(ND))
 return "(anonymous enum)";
   return "(anonymous)";
 }


Index: clangd/AST.cpp
===
--- clangd/AST.cpp
+++ clangd/AST.cpp
@@ -95,11 +95,11 @@
 return Out.str();
   }
   // The name was empty, so present an anonymous entity.
-  if (llvm::dyn_cast(&ND))
+  if (isa(ND))
 return "(anonymous namespace)";
   if (auto *Cls = llvm::dyn_cast(&ND))
 return ("(anonymous " + Cls->getKindName() + ")").str();
-  if (llvm::dyn_cast(&ND))
+  if (isa(ND))
 return "(anonymous enum)";
   return "(anonymous)";
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r347554 - [clangd] Fix missing include from r347538 - fix windows buildbots

2018-11-26 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Mon Nov 26 05:35:02 2018
New Revision: 347554

URL: http://llvm.org/viewvc/llvm-project?rev=347554&view=rev
Log:
[clangd] Fix missing include from r347538 - fix windows buildbots

Modified:
clang-tools-extra/trunk/clangd/index/Background.cpp

Modified: clang-tools-extra/trunk/clangd/index/Background.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Background.cpp?rev=347554&r1=347553&r2=347554&view=diff
==
--- clang-tools-extra/trunk/clangd/index/Background.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Background.cpp Mon Nov 26 05:35:02 2018
@@ -26,6 +26,7 @@
 #include "llvm/Support/SHA1.h"
 
 #include 
+#include 
 #include 
 #include 
 #include 


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


[PATCH] D54425: [AArch64] Add aarch64_vector_pcs function attribute to Clang

2018-11-26 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen added a comment.

Just to double check before committing, @aaron.ballman are you happy with the 
tests?


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

https://reviews.llvm.org/D54425



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


[PATCH] D53488: [clang-tidy] Improving narrowing conversions

2018-11-26 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet added a comment.

In D53488#1307834 , @aaron.ballman 
wrote:

> LGTM!


Thx ! \O/


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D53488



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


[PATCH] D54878: [clangd] NFC: Prefer `isa<>` to `dyn_cast<>` to do the checking.

2018-11-26 Thread Henry Wong via Phabricator via cfe-commits
MTC added a comment.

In D54878#1307726 , @ilya-biryukov 
wrote:

> But given that `isa<>` are still better than `dyn_cast<>`, this change might 
> still be worth landing.


We can land this change this time or do the cleaning job in other patches in 
the future, it's all up to you guys, the active clangd contributors.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54878



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


[PATCH] D54425: [AArch64] Add aarch64_vector_pcs function attribute to Clang

2018-11-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D54425#1307838 , @sdesmalen wrote:

> Just to double check before committing, @aaron.ballman are you happy with the 
> tests?


The tests LGTM, but there are still some unresolved comments from @rjmccall 
that should be handled before committing.


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

https://reviews.llvm.org/D54425



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


[PATCH] D54300: [clangd] Respect shouldIndexFile when collecting symbols.

2018-11-26 Thread Eric Liu via Phabricator via cfe-commits
ioeric added inline comments.



Comment at: clangd/index/SymbolCollector.cpp:386
   const Symbol *BasicSymbol = Symbols.find(*ID);
-  if (!BasicSymbol) // Regardless of role, ND is the canonical declaration.
-BasicSymbol = addDeclaration(*ND, std::move(*ID));
-  else if (isPreferredDeclaration(OriginalDecl, Roles))
-// If OriginalDecl is preferred, replace the existing canonical
-// declaration (e.g. a class forward declaration). There should be at most
-// one duplicate as we expect to see only one preferred declaration per
-// TU, because in practice they are definitions.
-BasicSymbol = addDeclaration(OriginalDecl, std::move(*ID));
-
-  if (Roles & static_cast(index::SymbolRole::Definition))
-addDefinition(OriginalDecl, *BasicSymbol);
+  auto shouldIndexSymbol = [&](SourceLocation TargetLoc) {
+return shouldIndexFile(SM, SM.getFileID(TargetLoc), Opts,

`shouldIndexLoc` seems more accurate?



Comment at: clangd/index/SymbolCollector.cpp:392
+  if (!BasicSymbol) {
+auto DeclSLoc = findNameLoc(ND);
+if (shouldIndexSymbol(DeclSLoc))

`DeclSLoc` is a bit confusing (SLoc is used somewhere else). Maybe `DeclSymLoc` 
or simply `DeclLoc`?



Comment at: clangd/index/SymbolCollector.cpp:397
+  }
+  if (isPreferredDeclaration(OriginalDecl, Roles)) {
+auto DeclSLoc = findNameLoc(&OriginalDecl);

We would be doing redundant work if `OriginalDecl == ND`?



Comment at: clangd/index/SymbolCollector.cpp:409
+auto DefLoc = findNameLoc(&OriginalDecl);
+if (!shouldIndexSymbol(DefLoc) && !BasicSymbol)
+  return true;

Could you document here why we are also checking `!BasicSymbol ` here? 



Comment at: clangd/index/SymbolCollector.cpp:571
 const Symbol *SymbolCollector::addDeclaration(const NamedDecl &ND,
+  SourceLocation DeclSLoc,
   SymbolID ID) {

nit: `s/DeclSLoc/DeclLoc`? and maybe add documentation about why we need this?



Comment at: unittests/clangd/SymbolCollectorTests.cpp:598
+  Pair(findSymbol(Symbols, "Foo2").ID,
+   RefsInFiles(Files({IndexedHeaderURI}))),
+  Pair(findSymbol(Symbols, "Foo3").ID,

I think making `RefsInFile` take a single file and using it in combination with 
`anyOf`/`allOf` would be more straightforward.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54300



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


[PATCH] D54894: [clangd] Enable auto-index behind a flag.

2018-11-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: kadircet.
Herald added subscribers: cfe-commits, arphaman, jkorous, MaskRay, ioeric, 
ilya-biryukov.

Ownership and configuration:
The auto-index (background index) is maintained by ClangdServer, like Dynamic.
(This means ClangdServer will be able to enqueue preamble indexing in future).
For now it's enabled by a simple boolean flag in ClangdServer::Options, but
we probably want to eventually allow injecting the storage strategy.

New 'sync' command:
In order to meaningfully test the integration (not just unit-test components)
we need a way for tests to ensure the asynchronous index reads/writes occur
before a certain point.
Because these tests and assertions are few, I think exposing an explicit "sync"
command for use in tests is simpler than allowing threading to be completely
disabled in the background index (as we do for TUScheduler).

Bugs:
I fixed a couple of trivial bugs I found while testing, but there's one I can't.
JSONCompilationDatabase::getAllFiles() may return relative paths, and currently
we trigger an assertion that assumes they are absolute.
There's no efficient way to resolve them (you have to retrieve the corresponding
command and then resolve against its directory property). In general I think
this behavior is broken and we should fix it in JSONCompilationDatabase and
require CompilationDatabase::getAllFiles() to be absolute.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D54894

Files:
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/GlobalCompilationDatabase.cpp
  clangd/index/BackgroundIndexStorage.cpp
  clangd/tool/ClangdMain.cpp
  test/clangd/Inputs/background-index/compile_commands.json
  test/clangd/Inputs/background-index/definition.jsonrpc
  test/clangd/Inputs/background-index/foo.cpp
  test/clangd/Inputs/background-index/foo.h
  test/clangd/background-index.test

Index: test/clangd/background-index.test
===
--- /dev/null
+++ test/clangd/background-index.test
@@ -0,0 +1,21 @@
+# We need to splice paths into file:// URIs for this test.
+# UNSUPPORTED: win32
+
+# Use a copy of inputs, as we'll mutate it (as will the background index).
+# RUN: rm -rf %t
+# RUN: cp -r %S/Inputs/background-index %t
+# Need to embed the correct temp path in the actual JSON-RPC requests.
+# RUN: sed -i -e "s|DIRECTORY|%t|" %t/*
+
+# We're editing bar.cpp, which includes foo.h.
+# foo() is declared in foo.h and defined in foo.cpp.
+# The background index should allow us to go-to-definition on foo().
+# RUN: clangd -background-index -lit-test < %t/definition.jsonrpc | FileCheck %t/definition.jsonrpc
+
+# Test that the index is writing files in the expected location.
+# RUN: ls %t/.clangd-index/foo.cpp.*.idx
+
+# Test the index is read from disk: delete code and restart clangd.
+# This test currently fails as we don't read the index yet.
+# RUN: rm %t/foo.cpp
+# RUN: clangd -background-index -lit-test < %t/definition.jsonrpc | not FileCheck %t/definition.jsonrpc
Index: test/clangd/Inputs/background-index/foo.h
===
--- /dev/null
+++ test/clangd/Inputs/background-index/foo.h
@@ -0,0 +1,4 @@
+#ifndef FOO_H
+#define FOO_H
+int foo();
+#endif
Index: test/clangd/Inputs/background-index/foo.cpp
===
--- /dev/null
+++ test/clangd/Inputs/background-index/foo.cpp
@@ -0,0 +1,2 @@
+#include "foo.h"
+int foo() { return 42; }
Index: test/clangd/Inputs/background-index/definition.jsonrpc
===
--- /dev/null
+++ test/clangd/Inputs/background-index/definition.jsonrpc
@@ -0,0 +1,51 @@
+{
+  "jsonrpc": "2.0",
+  "id": 0,
+  "method": "initialize",
+  "params": {
+"processId": 123,
+"rootPath": "clangd",
+"capabilities": {},
+"trace": "off"
+  }
+}
+---
+{
+  "jsonrpc": "2.0",
+  "method": "textDocument/didOpen",
+  "params": {
+"textDocument": {
+  "uri": "file://DIRECTORY/bar.cpp",
+  "languageId": "cpp",
+  "version": 1,
+  "text": "#include \"foo.h\"\nint main(){\nreturn foo();\n}"
+}
+  }
+}
+---
+{
+  "jsonrpc": "2.0",
+  "id": 1,
+  "method": "sync",
+  "params": null
+}
+---
+{
+  "jsonrpc": "2.0",
+  "id": 2,
+  "method": "textDocument/definition",
+  "params": {
+"textDocument": {
+  "uri": "file://DIRECTORY/bar.cpp"
+},
+"position": {
+  "line": 2,
+  "character": 8
+}
+  }
+}
+# CHECK: "uri": "file://DIRECTORY/foo.cpp"
+---
+{"jsonrpc":"2.0","id":3,"method":"shutdown"}
+---
+{"jsonrpc":"2.0","method":"exit"}
Index: test/clangd/Inputs/background-index/compile_commands.json
===
--- /dev/null
+++ test/clangd/Inputs/background-index/compile_commands.json
@@ -0,0 +1,5 @@
+[{
+  "directory": "DIREC

[PATCH] D54425: [AArch64] Add aarch64_vector_pcs function attribute to Clang

2018-11-26 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen updated this revision to Diff 175236.
sdesmalen added a comment.

- resolved editorial comments.


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

https://reviews.llvm.org/D54425

Files:
  include/clang-c/Index.h
  include/clang/Basic/Attr.td
  include/clang/Basic/AttrDocs.td
  include/clang/Basic/Specifiers.h
  lib/AST/ItaniumMangle.cpp
  lib/AST/Type.cpp
  lib/AST/TypePrinter.cpp
  lib/Basic/Targets/AArch64.cpp
  lib/CodeGen/CGCall.cpp
  lib/CodeGen/CGDebugInfo.cpp
  lib/Sema/SemaDeclAttr.cpp
  lib/Sema/SemaType.cpp
  test/CodeGen/aarch64-vpcs.c
  test/Sema/aarch64-vpcs.c
  test/Sema/callingconv.c
  tools/libclang/CXType.cpp

Index: tools/libclang/CXType.cpp
===
--- tools/libclang/CXType.cpp
+++ tools/libclang/CXType.cpp
@@ -651,6 +651,7 @@
   TCALLINGCONV(X86Pascal);
   TCALLINGCONV(X86RegCall);
   TCALLINGCONV(X86VectorCall);
+  TCALLINGCONV(AArch64VectorCall);
   TCALLINGCONV(Win64);
   TCALLINGCONV(X86_64SysV);
   TCALLINGCONV(AAPCS);
Index: test/Sema/callingconv.c
===
--- test/Sema/callingconv.c
+++ test/Sema/callingconv.c
@@ -51,6 +51,8 @@
 int __attribute__((pcs("aapcs-vfp"))) pcs6(void); // expected-warning {{calling convention 'pcs' ignored for this target}}
 int __attribute__((pcs("foo"))) pcs7(void); // expected-error {{invalid PCS type}}
 
+int __attribute__((aarch64_vector_pcs)) aavpcs(void); // expected-warning {{calling convention 'aarch64_vector_pcs' ignored for this target}}
+
 // PR6361
 void ctest3();
 void __attribute__((cdecl)) ctest3() {}
Index: test/Sema/aarch64-vpcs.c
===
--- /dev/null
+++ test/Sema/aarch64-vpcs.c
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -verify %s
+
+typedef __attribute__((aarch64_vector_pcs)) int invalid_typedef; // expected-warning {{'aarch64_vector_pcs' only applies to function types; type here is 'int'}}
+
+void __attribute__((aarch64_vector_pcs(0))) foo0(void); // expected-error {{'aarch64_vector_pcs' attribute takes no arguments}}
+
+void __attribute__((aarch64_vector_pcs, preserve_all)) foo1(void); // expected-error {{not compatible}}
+
+void __attribute__((cdecl)) foo2(void);// expected-note {{previous declaration is here}}
+void __attribute__((aarch64_vector_pcs)) foo2(void) {} // expected-error {{function declared 'aarch64_vector_pcs' here was previously declared 'cdecl'}}
+
+void foo3(void);   // expected-note {{previous declaration is here}}
+void __attribute__((aarch64_vector_pcs)) foo3(void) {} // expected-error {{function declared 'aarch64_vector_pcs' here was previously declared without calling convention}}
+
+typedef int (*fn_ty)(void);
+typedef int __attribute__((aarch64_vector_pcs)) (*aavpcs_fn_ty)(void);
+void foo4(fn_ty ptr1, aavpcs_fn_ty ptr2) {
+  ptr1 = ptr2; // expected-warning {{incompatible function pointer types}}
+}
Index: test/CodeGen/aarch64-vpcs.c
===
--- /dev/null
+++ test/CodeGen/aarch64-vpcs.c
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -emit-llvm -o - %s | FileCheck %s -check-prefix=CHECKC
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -emit-llvm -x c++ -o - %s | FileCheck %s -check-prefix=CHECKCXX
+// RUN: %clang_cc1 -triple i686-pc-linux-gnu -verify %s
+
+void __attribute__((aarch64_vector_pcs)) f(int *); // expected-warning {{calling convention 'aarch64_vector_pcs' ignored for this target}}
+
+// CHECKC: define void @g(
+// CHECKCXX: define void @_Z1gPi(
+void g(int *a) {
+
+// CHECKC: call aarch64_vector_pcs void @f(
+// CHECKCXX: call aarch64_vector_pcs void @_Z1fPi
+  f(a);
+}
+
+// CHECKC: declare aarch64_vector_pcs void @f(
+// CHECKCXX: declare aarch64_vector_pcs void @_Z1fPi
+
+void __attribute__((aarch64_vector_pcs)) h(int *a){ // expected-warning {{calling convention 'aarch64_vector_pcs' ignored for this target}}
+// CHECKC: define aarch64_vector_pcs void @h(
+// CHECKCXX: define aarch64_vector_pcs void @_Z1hPi(
+  f(a);
+}
Index: lib/Sema/SemaType.cpp
===
--- lib/Sema/SemaType.cpp
+++ lib/Sema/SemaType.cpp
@@ -116,6 +116,7 @@
   case ParsedAttr::AT_Pascal:  \
   case ParsedAttr::AT_SwiftCall:   \
   case ParsedAttr::AT_VectorCall:  \
+  case ParsedAttr::AT_AArch64VectorPcs:\
   case ParsedAttr::AT_MSABI:   \
   case ParsedAttr::AT_SysVABI: \
   case ParsedAttr::AT_Pcs: \
@@ -6653,6 +6654,8 @@
 return createSimpleAttr(Ctx, Attr);
   ca

[PATCH] D54866: Cleanups in IdentifierInfo following the removal of PTH

2018-11-26 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

This looks right to me.  Note the PTH removal is still waiting approval.




Comment at: include/clang/Basic/IdentifierTable.h:119
 
+  IdentifierInfo()
+  : TokenID(tok::identifier), ObjCOrBuiltinID(0), HasMacro(false),

Instead of putting these in an initializer, can you default-init each of them 
inline, then make this =default?


Repository:
  rC Clang

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

https://reviews.llvm.org/D54866



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


[PATCH] D54866: Cleanups in IdentifierInfo following the removal of PTH

2018-11-26 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno marked an inline comment as done.
riccibruno added inline comments.



Comment at: include/clang/Basic/IdentifierTable.h:119
 
+  IdentifierInfo()
+  : TokenID(tok::identifier), ObjCOrBuiltinID(0), HasMacro(false),

erichkeane wrote:
> Instead of putting these in an initializer, can you default-init each of them 
> inline, then make this =default?
Nope, you cannot default-init bit-fields (at least not until c++20)


Repository:
  rC Clang

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

https://reviews.llvm.org/D54866



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


[PATCH] D54894: [clangd] Enable auto-index behind a flag.

2018-11-26 Thread Eric Liu via Phabricator via cfe-commits
ioeric added a comment.

lgtm (will let @kadircet stamp )




Comment at: test/clangd/background-index.test:19
+# Test the index is read from disk: delete code and restart clangd.
+# This test currently fails as we don't read the index yet.
+# RUN: rm %t/foo.cpp

Maybe make this a FIXME?


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54894



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


[PATCH] D54866: Cleanups in IdentifierInfo following the removal of PTH

2018-11-26 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: include/clang/Basic/IdentifierTable.h:119
 
+  IdentifierInfo()
+  : TokenID(tok::identifier), ObjCOrBuiltinID(0), HasMacro(false),

riccibruno wrote:
> erichkeane wrote:
> > Instead of putting these in an initializer, can you default-init each of 
> > them inline, then make this =default?
> Nope, you cannot default-init bit-fields (at least not until c++20)
Ugg, you're right.  I hate bitfields.


Repository:
  rC Clang

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

https://reviews.llvm.org/D54866



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


[PATCH] D54866: Cleanups in IdentifierInfo following the removal of PTH

2018-11-26 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno marked an inline comment as done.
riccibruno added inline comments.



Comment at: include/clang/Basic/IdentifierTable.h:119
 
+  IdentifierInfo()
+  : TokenID(tok::identifier), ObjCOrBuiltinID(0), HasMacro(false),

erichkeane wrote:
> riccibruno wrote:
> > erichkeane wrote:
> > > Instead of putting these in an initializer, can you default-init each of 
> > > them inline, then make this =default?
> > Nope, you cannot default-init bit-fields (at least not until c++20)
> Ugg, you're right.  I hate bitfields.
Happy monday morning :)


Repository:
  rC Clang

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

https://reviews.llvm.org/D54866



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


r347555 - Create a diagnostic group for warn_call_to_pure_virtual_member_function_from_ctor_dtor, so it can be turned into an error using Werror

2018-11-26 Thread Sylvestre Ledru via cfe-commits
Author: sylvestre
Date: Mon Nov 26 06:29:48 2018
New Revision: 347555

URL: http://llvm.org/viewvc/llvm-project?rev=347555&view=rev
Log:
Create a diagnostic group for 
warn_call_to_pure_virtual_member_function_from_ctor_dtor, so it can be turned 
into an error using Werror

Summary: Patch by Arnaud Bienner

Reviewers: davide, rsmith, jkorous

Reviewed By: jkorous

Subscribers: jkorous, sylvestre.ledru, cfe-commits

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

Modified:
cfe/trunk/include/clang/Basic/DiagnosticGroups.td
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/test/Misc/warning-flags.c
cfe/trunk/test/SemaCXX/warn-pure-virtual-call-from-ctor-dtor.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticGroups.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticGroups.td?rev=347555&r1=347554&r2=347555&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticGroups.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticGroups.td Mon Nov 26 06:29:48 2018
@@ -287,6 +287,7 @@ def ExpansionToDefined : DiagGroup<"expa
 def FlagEnum : DiagGroup<"flag-enum">;
 def IncrementBool : DiagGroup<"increment-bool", [DeprecatedIncrementBool]>;
 def InfiniteRecursion : DiagGroup<"infinite-recursion">;
+def PureVirtualCallFromCtorDtor: 
DiagGroup<"call-to-pure-virtual-from-ctor-dtor">;
 def GNUImaginaryConstant : DiagGroup<"gnu-imaginary-constant">;
 def IgnoredQualifiers : DiagGroup<"ignored-qualifiers">;
 def : DiagGroup<"import">;

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=347555&r1=347554&r2=347555&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Mon Nov 26 06:29:48 
2018
@@ -1659,7 +1659,7 @@ def err_member_function_call_bad_type :
 def warn_call_to_pure_virtual_member_function_from_ctor_dtor : Warning<
   "call to pure virtual member function %0 has undefined behavior; "
   "overrides of %0 in subclasses are not available in the "
-  "%select{constructor|destructor}1 of %2">;
+  "%select{constructor|destructor}1 of %2">, 
InGroup;
 
 def select_special_member_kind : TextSubstitution<
   "%select{default constructor|copy constructor|move constructor|"

Modified: cfe/trunk/test/Misc/warning-flags.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Misc/warning-flags.c?rev=347555&r1=347554&r2=347555&view=diff
==
--- cfe/trunk/test/Misc/warning-flags.c (original)
+++ cfe/trunk/test/Misc/warning-flags.c Mon Nov 26 06:29:48 2018
@@ -18,7 +18,7 @@ This test serves two purposes:
 
 The list of warnings below should NEVER grow.  It should gradually shrink to 0.
 
-CHECK: Warnings without flags (76):
+CHECK: Warnings without flags (75):
 CHECK-NEXT:   ext_excess_initializers
 CHECK-NEXT:   ext_excess_initializers_in_char_array_initializer
 CHECK-NEXT:   ext_expected_semi_decl_list
@@ -40,7 +40,6 @@ CHECK-NEXT:   warn_accessor_property_typ
 CHECK-NEXT:   warn_arcmt_nsalloc_realloc
 CHECK-NEXT:   warn_asm_label_on_auto_decl
 CHECK-NEXT:   warn_c_kext
-CHECK-NEXT:   warn_call_to_pure_virtual_member_function_from_ctor_dtor
 CHECK-NEXT:   warn_call_wrong_number_of_arguments
 CHECK-NEXT:   warn_case_empty_range
 CHECK-NEXT:   warn_char_constant_too_large

Modified: cfe/trunk/test/SemaCXX/warn-pure-virtual-call-from-ctor-dtor.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/warn-pure-virtual-call-from-ctor-dtor.cpp?rev=347555&r1=347554&r2=347555&view=diff
==
--- cfe/trunk/test/SemaCXX/warn-pure-virtual-call-from-ctor-dtor.cpp (original)
+++ cfe/trunk/test/SemaCXX/warn-pure-virtual-call-from-ctor-dtor.cpp Mon Nov 26 
06:29:48 2018
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 %s -fsyntax-only -verify
+// RUN: %clang_cc1 %s -fsyntax-only -verify 
-Wcall-to-pure-virtual-from-ctor-dtor
 struct A {
   A() { f(); } // expected-warning {{call to pure virtual member function 'f' 
has undefined behavior; overrides of 'f' in subclasses are not available in the 
constructor of 'A'}}
   ~A() { f(); } // expected-warning {{call to pure virtual member function 'f' 
has undefined behavior; overrides of 'f' in subclasses are not available in the 
destructor of 'A'}}


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


[PATCH] D53697: [ASTImporter][Structural Eq] Check for isBeingDefined

2018-11-26 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 175241.
martong added a comment.

- Get data of CXXRecordDecl only if set


Repository:
  rC Clang

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

https://reviews.llvm.org/D53697

Files:
  lib/AST/ASTImporter.cpp
  lib/AST/ASTStructuralEquivalence.cpp
  unittests/AST/ASTImporterTest.cpp


Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -3725,6 +3725,45 @@
   EXPECT_EQ(To1->getPreviousDecl(), To0);
 }
 
+TEST_P(ASTImporterTestBase,
+ImportShouldNotReportFalseODRErrorWhenRecordIsBeingDefined) {
+  {
+Decl *FromTU = getTuDecl(
+R"(
+template 
+struct B;
+)",
+Lang_CXX, "input0.cc");
+auto *FromD = FirstDeclMatcher().match(
+FromTU, classTemplateDecl(hasName("B")));
+
+Import(FromD, Lang_CXX);
+  }
+
+  {
+Decl *FromTU = getTuDecl(
+R"(
+template 
+struct B {
+  void f();
+  B* b;
+};
+)",
+Lang_CXX, "input1.cc");
+FunctionDecl *FromD = FirstDeclMatcher().match(
+FromTU, functionDecl(hasName("f")));
+Import(FromD, Lang_CXX);
+auto *FromCTD = FirstDeclMatcher().match(
+FromTU, classTemplateDecl(hasName("B")));
+auto *ToCTD = cast(Import(FromCTD, Lang_CXX));
+EXPECT_TRUE(ToCTD->isThisDeclarationADefinition());
+
+// We expect no (ODR) warning during the import.
+auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
+EXPECT_EQ(0u, ToTU->getASTContext().getDiagnostics().getNumWarnings());
+  }
+}
+
 INSTANTIATE_TEST_CASE_P(ParameterizedTests, DeclContextTest,
 ::testing::Values(ArgVector()), );
 
Index: lib/AST/ASTStructuralEquivalence.cpp
===
--- lib/AST/ASTStructuralEquivalence.cpp
+++ lib/AST/ASTStructuralEquivalence.cpp
@@ -1016,7 +1016,8 @@
 return false;
 
   // Compare the definitions of these two records. If either or both are
-  // incomplete, we assume that they are equivalent.
+  // incomplete (i.e. it is a forward decl), we assume that they are
+  // equivalent.
   D1 = D1->getDefinition();
   D2 = D2->getDefinition();
   if (!D1 || !D2)
@@ -1031,6 +1032,11 @@
 if (D1->hasExternalLexicalStorage() || D2->hasExternalLexicalStorage())
   return true;
 
+  // If one definition is currently being defined, we do not compare for
+  // equality and we assume that the decls are equal.
+  if (D1->isBeingDefined() || D2->isBeingDefined())
+return true;
+
   if (auto *D1CXX = dyn_cast(D1)) {
 if (auto *D2CXX = dyn_cast(D2)) {
   if (D1CXX->hasExternalLexicalStorage() &&
Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -1740,8 +1740,9 @@
 return Err;
 
   // Add base classes.
-  if (auto *ToCXX = dyn_cast(To)) {
-auto *FromCXX = cast(From);
+  auto *ToCXX = dyn_cast(To);
+  auto *FromCXX = dyn_cast(From);
+  if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
 
 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();


Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -3725,6 +3725,45 @@
   EXPECT_EQ(To1->getPreviousDecl(), To0);
 }
 
+TEST_P(ASTImporterTestBase,
+ImportShouldNotReportFalseODRErrorWhenRecordIsBeingDefined) {
+  {
+Decl *FromTU = getTuDecl(
+R"(
+template 
+struct B;
+)",
+Lang_CXX, "input0.cc");
+auto *FromD = FirstDeclMatcher().match(
+FromTU, classTemplateDecl(hasName("B")));
+
+Import(FromD, Lang_CXX);
+  }
+
+  {
+Decl *FromTU = getTuDecl(
+R"(
+template 
+struct B {
+  void f();
+  B* b;
+};
+)",
+Lang_CXX, "input1.cc");
+FunctionDecl *FromD = FirstDeclMatcher().match(
+FromTU, functionDecl(hasName("f")));
+Import(FromD, Lang_CXX);
+auto *FromCTD = FirstDeclMatcher().match(
+FromTU, classTemplateDecl(hasName("B")));
+auto *ToCTD = cast(Import(FromCTD, Lang_CXX));
+EXPECT_TRUE(ToCTD->isThisDeclarationADefinition());
+
+// We expect no (ODR) warning during the import.
+auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
+EXPECT_EQ(0u, ToTU->getASTContext().getDiagnostics().getNumWarnings());
+  }
+}
+
 INSTANTIATE_TEST_CASE_P(ParameterizedTests, DeclContextTest,
 ::testing::Values(ArgVector()), );
 
Index: lib/AST/ASTStructuralEquivalence.cpp
==

[PATCH] D53807: Create a diagnostic group for warn_call_to_pure_virtual_member_function_from_ctor_dtor, so it can be turned into an error using Werror

2018-11-26 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC347555: Create a diagnostic group for 
warn_call_to_pure_virtual_member_function_from_ct… (authored by sylvestre, 
committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D53807?vs=171502&id=175242#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D53807

Files:
  include/clang/Basic/DiagnosticGroups.td
  include/clang/Basic/DiagnosticSemaKinds.td
  test/Misc/warning-flags.c
  test/SemaCXX/warn-pure-virtual-call-from-ctor-dtor.cpp


Index: include/clang/Basic/DiagnosticGroups.td
===
--- include/clang/Basic/DiagnosticGroups.td
+++ include/clang/Basic/DiagnosticGroups.td
@@ -287,6 +287,7 @@
 def FlagEnum : DiagGroup<"flag-enum">;
 def IncrementBool : DiagGroup<"increment-bool", [DeprecatedIncrementBool]>;
 def InfiniteRecursion : DiagGroup<"infinite-recursion">;
+def PureVirtualCallFromCtorDtor: 
DiagGroup<"call-to-pure-virtual-from-ctor-dtor">;
 def GNUImaginaryConstant : DiagGroup<"gnu-imaginary-constant">;
 def IgnoredQualifiers : DiagGroup<"ignored-qualifiers">;
 def : DiagGroup<"import">;
Index: include/clang/Basic/DiagnosticSemaKinds.td
===
--- include/clang/Basic/DiagnosticSemaKinds.td
+++ include/clang/Basic/DiagnosticSemaKinds.td
@@ -1659,7 +1659,7 @@
 def warn_call_to_pure_virtual_member_function_from_ctor_dtor : Warning<
   "call to pure virtual member function %0 has undefined behavior; "
   "overrides of %0 in subclasses are not available in the "
-  "%select{constructor|destructor}1 of %2">;
+  "%select{constructor|destructor}1 of %2">, 
InGroup;
 
 def select_special_member_kind : TextSubstitution<
   "%select{default constructor|copy constructor|move constructor|"
Index: test/Misc/warning-flags.c
===
--- test/Misc/warning-flags.c
+++ test/Misc/warning-flags.c
@@ -18,7 +18,7 @@
 
 The list of warnings below should NEVER grow.  It should gradually shrink to 0.
 
-CHECK: Warnings without flags (76):
+CHECK: Warnings without flags (75):
 CHECK-NEXT:   ext_excess_initializers
 CHECK-NEXT:   ext_excess_initializers_in_char_array_initializer
 CHECK-NEXT:   ext_expected_semi_decl_list
@@ -40,7 +40,6 @@
 CHECK-NEXT:   warn_arcmt_nsalloc_realloc
 CHECK-NEXT:   warn_asm_label_on_auto_decl
 CHECK-NEXT:   warn_c_kext
-CHECK-NEXT:   warn_call_to_pure_virtual_member_function_from_ctor_dtor
 CHECK-NEXT:   warn_call_wrong_number_of_arguments
 CHECK-NEXT:   warn_case_empty_range
 CHECK-NEXT:   warn_char_constant_too_large
Index: test/SemaCXX/warn-pure-virtual-call-from-ctor-dtor.cpp
===
--- test/SemaCXX/warn-pure-virtual-call-from-ctor-dtor.cpp
+++ test/SemaCXX/warn-pure-virtual-call-from-ctor-dtor.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 %s -fsyntax-only -verify
+// RUN: %clang_cc1 %s -fsyntax-only -verify 
-Wcall-to-pure-virtual-from-ctor-dtor
 struct A {
   A() { f(); } // expected-warning {{call to pure virtual member function 'f' 
has undefined behavior; overrides of 'f' in subclasses are not available in the 
constructor of 'A'}}
   ~A() { f(); } // expected-warning {{call to pure virtual member function 'f' 
has undefined behavior; overrides of 'f' in subclasses are not available in the 
destructor of 'A'}}


Index: include/clang/Basic/DiagnosticGroups.td
===
--- include/clang/Basic/DiagnosticGroups.td
+++ include/clang/Basic/DiagnosticGroups.td
@@ -287,6 +287,7 @@
 def FlagEnum : DiagGroup<"flag-enum">;
 def IncrementBool : DiagGroup<"increment-bool", [DeprecatedIncrementBool]>;
 def InfiniteRecursion : DiagGroup<"infinite-recursion">;
+def PureVirtualCallFromCtorDtor: DiagGroup<"call-to-pure-virtual-from-ctor-dtor">;
 def GNUImaginaryConstant : DiagGroup<"gnu-imaginary-constant">;
 def IgnoredQualifiers : DiagGroup<"ignored-qualifiers">;
 def : DiagGroup<"import">;
Index: include/clang/Basic/DiagnosticSemaKinds.td
===
--- include/clang/Basic/DiagnosticSemaKinds.td
+++ include/clang/Basic/DiagnosticSemaKinds.td
@@ -1659,7 +1659,7 @@
 def warn_call_to_pure_virtual_member_function_from_ctor_dtor : Warning<
   "call to pure virtual member function %0 has undefined behavior; "
   "overrides of %0 in subclasses are not available in the "
-  "%select{constructor|destructor}1 of %2">;
+  "%select{constructor|destructor}1 of %2">, InGroup;
 
 def select_special_member_kind : TextSubstitution<
   "%select{default constructor|copy constructor|move constructor|"
Index: test/Misc/warning-flags.c
===
--- test/Misc/warning-flags.c
+++ test/Misc/warning-flags.c
@@ -18,7 +18,7 @@
 
 The list of warnings bel

[PATCH] D53697: [ASTImporter][Structural Eq] Check for isBeingDefined

2018-11-26 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

I have reproduced the issue on MacOS, fixed it and updated the patch 
accordingly.
Soon I will commit and will monitor if any build bots are being broken.


Repository:
  rC Clang

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

https://reviews.llvm.org/D53697



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


[PATCH] D54878: [clangd] NFC: Prefer `isa<>` to `dyn_cast<>` to do the checking.

2018-11-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

In D54878#1307845 , @MTC wrote:

> We can land this change this time or do the cleaning job in other patches in 
> the future, it's all up to you guys, the active clangd contributors :).


Please land this, it's a useful cleanup.
Unless you'd prefer to not spend any more time on this, in which case I'd just 
land it for you :-)


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54878



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


[PATCH] D52274: [clangd] Collect and store expected types in the index

2018-11-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clangd/index/Index.h:283
 
+  /// Type of the symbol, used for scoring purposes.
+  llvm::StringRef Type;

either call this OpaqueType or point at in in the comment?

I'd put this below the `ReturnType` string too, it seems out of place here. But 
up to you.



Comment at: clangd/index/SymbolCollector.cpp:591
+  llvm::Optional Type;
+  if (S.Flags & Symbol::IndexedForCodeCompletion)
+Type = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion);

nit: like this?
```
if (indexed for code completion)
 if (auto T = ...)
   S.Type = T->raw();
```


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D52274



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


r347556 - [PowerPC] Vector load/store builtins overstate alignment of pointers

2018-11-26 Thread Nemanja Ivanovic via cfe-commits
Author: nemanjai
Date: Mon Nov 26 06:35:38 2018
New Revision: 347556

URL: http://llvm.org/viewvc/llvm-project?rev=347556&view=rev
Log:
[PowerPC] Vector load/store builtins overstate alignment of pointers

A number of builtins in altivec.h load/store vectors from pointers to scalar
types. Currently they just cast the pointer to a vector pointer, but expressions
like that have the alignment of the target type. Of course, the input pointer
did not have that alignment so this triggers UBSan (and rightly so).

This resolves https://bugs.llvm.org/show_bug.cgi?id=39704

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

Modified:
cfe/trunk/lib/Headers/altivec.h
cfe/trunk/test/CodeGen/builtins-ppc-altivec.c
cfe/trunk/test/CodeGen/builtins-ppc-quadword.c
cfe/trunk/test/CodeGen/builtins-ppc-vsx.c

Modified: cfe/trunk/lib/Headers/altivec.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Headers/altivec.h?rev=347556&r1=347555&r2=347556&view=diff
==
--- cfe/trunk/lib/Headers/altivec.h (original)
+++ cfe/trunk/lib/Headers/altivec.h Mon Nov 26 06:35:38 2018
@@ -16355,67 +16355,82 @@ vec_revb(vector unsigned __int128 __a) {
 
 /* vec_xl */
 
+typedef vector signed char unaligned_vec_schar __attribute__((aligned(1)));
+typedef vector unsigned char unaligned_vec_uchar __attribute__((aligned(1)));
+typedef vector signed short unaligned_vec_sshort __attribute__((aligned(1)));
+typedef vector unsigned short unaligned_vec_ushort __attribute__((aligned(1)));
+typedef vector signed int unaligned_vec_sint __attribute__((aligned(1)));
+typedef vector unsigned int unaligned_vec_uint __attribute__((aligned(1)));
+typedef vector float unaligned_vec_float __attribute__((aligned(1)));
+
 static inline __ATTRS_o_ai vector signed char vec_xl(signed long long __offset,
  signed char *__ptr) {
-  return *(vector signed char *)(__ptr + __offset);
+  return *(unaligned_vec_schar *)(__ptr + __offset);
 }
 
 static inline __ATTRS_o_ai vector unsigned char
 vec_xl(signed long long __offset, unsigned char *__ptr) {
-  return *(vector unsigned char *)(__ptr + __offset);
+  return *(unaligned_vec_uchar*)(__ptr + __offset);
 }
 
 static inline __ATTRS_o_ai vector signed short vec_xl(signed long long 
__offset,
   signed short *__ptr) {
-  return *(vector signed short *)(__ptr + __offset);
+  return *(unaligned_vec_sshort *)(__ptr + __offset);
 }
 
 static inline __ATTRS_o_ai vector unsigned short
 vec_xl(signed long long __offset, unsigned short *__ptr) {
-  return *(vector unsigned short *)(__ptr + __offset);
+  return *(unaligned_vec_ushort *)(__ptr + __offset);
 }
 
 static inline __ATTRS_o_ai vector signed int vec_xl(signed long long __offset,
 signed int *__ptr) {
-  return *(vector signed int *)(__ptr + __offset);
+  return *(unaligned_vec_sint *)(__ptr + __offset);
 }
 
 static inline __ATTRS_o_ai vector unsigned int vec_xl(signed long long 
__offset,
   unsigned int *__ptr) {
-  return *(vector unsigned int *)(__ptr + __offset);
+  return *(unaligned_vec_uint *)(__ptr + __offset);
 }
 
 static inline __ATTRS_o_ai vector float vec_xl(signed long long __offset,
float *__ptr) {
-  return *(vector float *)(__ptr + __offset);
+  return *(unaligned_vec_float *)(__ptr + __offset);
 }
 
 #ifdef __VSX__
+typedef vector signed long long unaligned_vec_sll __attribute__((aligned(1)));
+typedef vector unsigned long long unaligned_vec_ull 
__attribute__((aligned(1)));
+typedef vector double unaligned_vec_double __attribute__((aligned(1)));
+
 static inline __ATTRS_o_ai vector signed long long
 vec_xl(signed long long __offset, signed long long *__ptr) {
-  return *(vector signed long long *)(__ptr + __offset);
+  return *(unaligned_vec_sll *)(__ptr + __offset);
 }
 
 static inline __ATTRS_o_ai vector unsigned long long
 vec_xl(signed long long __offset, unsigned long long *__ptr) {
-  return *(vector unsigned long long *)(__ptr + __offset);
+  return *(unaligned_vec_ull *)(__ptr + __offset);
 }
 
 static inline __ATTRS_o_ai vector double vec_xl(signed long long __offset,
 double *__ptr) {
-  return *(vector double *)(__ptr + __offset);
+  return *(unaligned_vec_double *)(__ptr + __offset);
 }
 #endif
 
 #if defined(__POWER8_VECTOR__) && defined(__powerpc64__)
+typedef vector signed __int128 unaligned_vec_si128 __attribute__((aligned(1)));
+typedef vector unsigned __int128 unaligned_vec_ui128
+__attribute__((aligned(1)));
 static inline __ATTRS_o_ai vector signed __int128
 vec_xl(signed long long __offset, signed __int128 *__ptr) {
-  return *(vector signed __int128 *)(__ptr + __offset);
+  return *(unaligned_vec_si128 *)(__ptr + __offset);
 }
 
 sta

[PATCH] D54787: [PowerPC] Vector load/store builtins overstate alignment of pointers

2018-11-26 Thread Nemanja Ivanovic via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL347556: [PowerPC] Vector load/store builtins overstate 
alignment of pointers (authored by nemanjai, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D54787?vs=174899&id=175243#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D54787

Files:
  cfe/trunk/lib/Headers/altivec.h
  cfe/trunk/test/CodeGen/builtins-ppc-altivec.c
  cfe/trunk/test/CodeGen/builtins-ppc-quadword.c
  cfe/trunk/test/CodeGen/builtins-ppc-vsx.c

Index: cfe/trunk/test/CodeGen/builtins-ppc-quadword.c
===
--- cfe/trunk/test/CodeGen/builtins-ppc-quadword.c
+++ cfe/trunk/test/CodeGen/builtins-ppc-quadword.c
@@ -205,45 +205,45 @@
 
   /* vec_xl */
   res_vlll = vec_xl(param_sll, ¶m_lll);
-  // CHECK: load <1 x i128>, <1 x i128>* %{{[0-9]+}}, align 16
-  // CHECK-LE: load <1 x i128>, <1 x i128>* %{{[0-9]+}}, align 16
+  // CHECK: load <1 x i128>, <1 x i128>* %{{[0-9]+}}, align 1
+  // CHECK-LE: load <1 x i128>, <1 x i128>* %{{[0-9]+}}, align 1
   // CHECK-PPC: error: call to 'vec_xl' is ambiguous
 
   res_vulll = vec_xl(param_sll, ¶m_ulll);
-  // CHECK: load <1 x i128>, <1 x i128>* %{{[0-9]+}}, align 16
-  // CHECK-LE: load <1 x i128>, <1 x i128>* %{{[0-9]+}}, align 16
+  // CHECK: load <1 x i128>, <1 x i128>* %{{[0-9]+}}, align 1
+  // CHECK-LE: load <1 x i128>, <1 x i128>* %{{[0-9]+}}, align 1
   // CHECK-PPC: error: call to 'vec_xl' is ambiguous
 
   /* vec_xst */
vec_xst(vlll, param_sll, ¶m_lll);
-  // CHECK: store <1 x i128> %{{[0-9]+}}, <1 x i128>* %{{[0-9]+}}, align 16
-  // CHECK-LE: store <1 x i128> %{{[0-9]+}}, <1 x i128>* %{{[0-9]+}}, align 16
+  // CHECK: store <1 x i128> %{{[0-9]+}}, <1 x i128>* %{{[0-9]+}}, align 1
+  // CHECK-LE: store <1 x i128> %{{[0-9]+}}, <1 x i128>* %{{[0-9]+}}, align 1
   // CHECK-PPC: error: call to 'vec_xst' is ambiguous
 
vec_xst(vulll, param_sll, ¶m_ulll);
-  // CHECK: store <1 x i128> %{{[0-9]+}}, <1 x i128>* %{{[0-9]+}}, align 16
-  // CHECK-LE: store <1 x i128> %{{[0-9]+}}, <1 x i128>* %{{[0-9]+}}, align 16
+  // CHECK: store <1 x i128> %{{[0-9]+}}, <1 x i128>* %{{[0-9]+}}, align 1
+  // CHECK-LE: store <1 x i128> %{{[0-9]+}}, <1 x i128>* %{{[0-9]+}}, align 1
   // CHECK-PPC: error: call to 'vec_xst' is ambiguous
 
   /* vec_xl_be */
   res_vlll = vec_xl_be(param_sll, ¶m_lll);
-  // CHECK: load <1 x i128>, <1 x i128>* %{{[0-9]+}}, align 16
-  // CHECK-LE: load <1 x i128>, <1 x i128>* %{{[0-9]+}}, align 16
+  // CHECK: load <1 x i128>, <1 x i128>* %{{[0-9]+}}, align 1
+  // CHECK-LE: load <1 x i128>, <1 x i128>* %{{[0-9]+}}, align 1
   // CHECK-PPC: error: call to 'vec_xl' is ambiguous
 
   res_vulll = vec_xl_be(param_sll, ¶m_ulll);
-  // CHECK: load <1 x i128>, <1 x i128>* %{{[0-9]+}}, align 16
-  // CHECK-LE: load <1 x i128>, <1 x i128>* %{{[0-9]+}}, align 16
+  // CHECK: load <1 x i128>, <1 x i128>* %{{[0-9]+}}, align 1
+  // CHECK-LE: load <1 x i128>, <1 x i128>* %{{[0-9]+}}, align 1
   // CHECK-PPC: error: call to 'vec_xl' is ambiguous
 
   /* vec_xst_be  */
vec_xst_be(vlll, param_sll, ¶m_lll);
-  // CHECK: store <1 x i128> %{{[0-9]+}}, <1 x i128>* %{{[0-9]+}}, align 16
-  // CHECK-LE: store <1 x i128> %{{[0-9]+}}, <1 x i128>* %{{[0-9]+}}, align 16
+  // CHECK: store <1 x i128> %{{[0-9]+}}, <1 x i128>* %{{[0-9]+}}, align 1
+  // CHECK-LE: store <1 x i128> %{{[0-9]+}}, <1 x i128>* %{{[0-9]+}}, align 1
   // CHECK-PPC: error: call to 'vec_xst' is ambiguous
 
vec_xst_be(vulll, param_sll, ¶m_ulll);
-  // CHECK: store <1 x i128> %{{[0-9]+}}, <1 x i128>* %{{[0-9]+}}, align 16
-  // CHECK-LE: store <1 x i128> %{{[0-9]+}}, <1 x i128>* %{{[0-9]+}}, align 16
+  // CHECK: store <1 x i128> %{{[0-9]+}}, <1 x i128>* %{{[0-9]+}}, align 1
+  // CHECK-LE: store <1 x i128> %{{[0-9]+}}, <1 x i128>* %{{[0-9]+}}, align 1
   // CHECK-PPC: error: call to 'vec_xst' is ambiguous
 }
Index: cfe/trunk/test/CodeGen/builtins-ppc-vsx.c
===
--- cfe/trunk/test/CodeGen/builtins-ppc-vsx.c
+++ cfe/trunk/test/CodeGen/builtins-ppc-vsx.c
@@ -1638,51 +1638,51 @@
 // CHECK-LE: @llvm.ppc.altivec.vsro
 
 res_vsll = vec_xl(sll, asll);
-// CHECK: load <2 x i64>, <2 x i64>* %{{[0-9]+}}, align 16
-// CHECK-LE: load <2 x i64>, <2 x i64>* %{{[0-9]+}}, align 16
+// CHECK: load <2 x i64>, <2 x i64>* %{{[0-9]+}}, align 1
+// CHECK-LE: load <2 x i64>, <2 x i64>* %{{[0-9]+}}, align 1
 
 res_vull = vec_xl(sll, aull);
-// CHECK: load <2 x i64>, <2 x i64>* %{{[0-9]+}}, align 16
-// CHECK-LE: load <2 x i64>, <2 x i64>* %{{[0-9]+}}, align 16
+// CHECK: load <2 x i64>, <2 x i64>* %{{[0-9]+}}, align 1
+// CHECK-LE: load <2 x i64>, <2 x i64>* %{{[0-9]+}}, align 1
 
 res_vd = vec_xl(sll, ad);
-// CHECK: load <2 x double>, <2 x double>* %{{[0-9]+}}, align 16
-// CHECK-LE: load <2 x double>, <2 x dou

[PATCH] D54547: PTH-- Remove feature entirely-

2018-11-26 Thread Erich Keane via Phabricator via cfe-commits
erichkeane marked 2 inline comments as done.
erichkeane added inline comments.



Comment at: include/clang/Lex/Preprocessor.h:396
+  /// This is an alias for CurLexer.
   PreprocessorLexer *CurPPLexer = nullptr;
 

riccibruno wrote:
> Would it make sense to remove this alias now that it
> will always refer to `CurLexer` ?
There seems to be some logic around this that I'm not totally sure about 
dealing with IsFileLexer.  


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

https://reviews.llvm.org/D54547



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


[PATCH] D52276: [clangd] Add type boosting in code completion

2018-11-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

You may want to add a FIXME in SymbolIndex to include opaque type in fuzzyfind 
request.




Comment at: clangd/CodeComplete.cpp:1504
+if (PreferredType)
+  Relevance.HadContextType |= true;
 

`|=` true is more traditionally known as `= true` :-)
(and below)



Comment at: clangd/Quality.cpp:418
 
+  OS << formatv("\tSema provided preferred type: {0}\n", S.HadContextType);
+  OS << formatv("\tSymbol had type: {0}\n", S.HadSymbolType);

Consider combining these: "Type matched preferred: {0} (Context type: {1}, 
Symbol type: {2}"


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D52276



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


[PATCH] D54547: PTH-- Remove feature entirely-

2018-11-26 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno added inline comments.



Comment at: include/clang/Lex/Preprocessor.h:396
+  /// This is an alias for CurLexer.
   PreprocessorLexer *CurPPLexer = nullptr;
 

erichkeane wrote:
> riccibruno wrote:
> > Would it make sense to remove this alias now that it
> > will always refer to `CurLexer` ?
> There seems to be some logic around this that I'm not totally sure about 
> dealing with IsFileLexer.  
Sounds fine to me. Someone more familiar with this can
always come back later and rework this.


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

https://reviews.llvm.org/D54547



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


[PATCH] D54894: [clangd] Enable auto-index behind a flag.

2018-11-26 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

Sorry for the bugs, thanks for the fixes :D




Comment at: clangd/ClangdServer.cpp:515
+if (BackgroundIdx)
+  BackgroundIdx->blockUntilIdleForTest();
+return true;

Should we change `BackgroundIndex`s signature to indicate success failure? Not 
sure it can block but just in case something weird happens.



Comment at: test/clangd/background-index.test:13
+# The background index should allow us to go-to-definition on foo().
+# RUN: clangd -background-index -lit-test < %t/definition.jsonrpc | FileCheck 
%t/definition.jsonrpc
+

shouldn't this one be running ?



Comment at: test/clangd/background-index.test:16
+# Test that the index is writing files in the expected location.
+# RUN: ls %t/.clangd-index/foo.cpp.*.idx
+

and this


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54894



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


[PATCH] D52274: [clangd] Collect and store expected types in the index

2018-11-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov marked 3 inline comments as done.
ilya-biryukov added inline comments.



Comment at: clangd/index/Index.h:283
 
+  /// Type of the symbol, used for scoring purposes.
+  llvm::StringRef Type;

sammccall wrote:
> either call this OpaqueType or point at in in the comment?
> 
> I'd put this below the `ReturnType` string too, it seems out of place here. 
> But up to you.
- Added a comment. OpaqueType would clash with the type name, something I'd 
prefer to avoid.
- Moved to live after `ReturnType`. I initially thought it'd be nice to keep 
them apart, since `ReturnType` is for showing it to the users and `Type` is for 
scoring. Now that I think about it does not look like a good idea, since 
keeping them apart means the user might read the comment for one of them, but 
not the other and end up inferring the other one on their own.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D52274



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


[PATCH] D54894: [clangd] Enable auto-index behind a flag.

2018-11-26 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: test/clangd/background-index.test:16
+# Test that the index is writing files in the expected location.
+# RUN: ls %t/.clangd-index/foo.cpp.*.idx
+

kadircet wrote:
> and this
also I suppose we might wanna delete this file after test ends(if the temp 
directory is not already deleted at exit)


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54894



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


[PATCH] D52274: [clangd] Collect and store expected types in the index

2018-11-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 175246.
ilya-biryukov marked an inline comment as done.
ilya-biryukov added a comment.

- Bump the RIFF version number
- Place the Type field after the ReturnType
- Address other comments


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D52274

Files:
  clangd/index/Index.h
  clangd/index/Serialization.cpp
  clangd/index/SymbolCollector.cpp
  clangd/index/YAMLSerialization.cpp


Index: clangd/index/YAMLSerialization.cpp
===
--- clangd/index/YAMLSerialization.cpp
+++ clangd/index/YAMLSerialization.cpp
@@ -197,6 +197,7 @@
 IO.mapOptional("CompletionSnippetSuffix", Sym.CompletionSnippetSuffix);
 IO.mapOptional("Documentation", Sym.Documentation);
 IO.mapOptional("ReturnType", Sym.ReturnType);
+IO.mapOptional("Type", Sym.Type);
 IO.mapOptional("IncludeHeaders", Sym.IncludeHeaders);
   }
 };
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -587,6 +587,11 @@
   if (!Include.empty())
 S.IncludeHeaders.emplace_back(Include, 1);
 
+  if (S.Flags & Symbol::IndexedForCodeCompletion) {
+if (auto T = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion))
+  S.Type = T->raw();
+  }
+
   S.Origin = Opts.Origin;
   if (ND.getAvailability() == AR_Deprecated)
 S.Flags |= Symbol::Deprecated;
Index: clangd/index/Serialization.cpp
===
--- clangd/index/Serialization.cpp
+++ clangd/index/Serialization.cpp
@@ -264,6 +264,7 @@
   writeVar(Strings.index(Sym.CompletionSnippetSuffix), OS);
   writeVar(Strings.index(Sym.Documentation), OS);
   writeVar(Strings.index(Sym.ReturnType), OS);
+  writeVar(Strings.index(Sym.Type), OS);
 
   auto WriteInclude = [&](const Symbol::IncludeHeaderWithReferences &Include) {
 writeVar(Strings.index(Include.IncludeHeader), OS);
@@ -290,6 +291,7 @@
   Sym.CompletionSnippetSuffix = Data.consumeString(Strings);
   Sym.Documentation = Data.consumeString(Strings);
   Sym.ReturnType = Data.consumeString(Strings);
+  Sym.Type = Data.consumeString(Strings);
   Sym.IncludeHeaders.resize(Data.consumeVar());
   for (auto &I : Sym.IncludeHeaders) {
 I.IncludeHeader = Data.consumeString(Strings);
@@ -339,7 +341,7 @@
 // The current versioning scheme is simple - non-current versions are rejected.
 // If you make a breaking change, bump this version number to invalidate stored
 // data. Later we may want to support some backward compatibility.
-constexpr static uint32_t Version = 7;
+constexpr static uint32_t Version = 8;
 
 Expected readRIFF(StringRef Data) {
   auto RIFF = riff::readFile(Data);
Index: clangd/index/Index.h
===
--- clangd/index/Index.h
+++ clangd/index/Index.h
@@ -10,12 +10,14 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_H
 
+#include "ExpectedTypes.h"
 #include "clang/Index/IndexSymbol.h"
 #include "clang/Lex/Lexer.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
@@ -242,6 +244,10 @@
   /// e.g. return type of a function, or type of a variable.
   llvm::StringRef ReturnType;
 
+  /// Raw representation of the OpaqueType of the symbol, used for scoring
+  /// purposes.
+  llvm::StringRef Type;
+
   struct IncludeHeaderWithReferences {
 IncludeHeaderWithReferences() = default;
 
@@ -300,6 +306,7 @@
   CB(S.CompletionSnippetSuffix);
   CB(S.Documentation);
   CB(S.ReturnType);
+  CB(S.Type);
   auto RawCharPointerCB = [&CB](const char *&P) {
 llvm::StringRef S(P);
 CB(S);


Index: clangd/index/YAMLSerialization.cpp
===
--- clangd/index/YAMLSerialization.cpp
+++ clangd/index/YAMLSerialization.cpp
@@ -197,6 +197,7 @@
 IO.mapOptional("CompletionSnippetSuffix", Sym.CompletionSnippetSuffix);
 IO.mapOptional("Documentation", Sym.Documentation);
 IO.mapOptional("ReturnType", Sym.ReturnType);
+IO.mapOptional("Type", Sym.Type);
 IO.mapOptional("IncludeHeaders", Sym.IncludeHeaders);
   }
 };
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -587,6 +587,11 @@
   if (!Include.empty())
 S.IncludeHeaders.emplace_back(Include, 1);
 
+  if (S.Flags & Symbol::IndexedForCodeCompletion) {
+if (auto T = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion))
+  S.Type = T->raw();
+  }
+
   S.Origin = Opts.Or

[PATCH] D54894: [clangd] Enable auto-index behind a flag.

2018-11-26 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: test/clangd/background-index.test:13
+# The background index should allow us to go-to-definition on foo().
+# RUN: clangd -background-index -lit-test < %t/definition.jsonrpc | FileCheck 
%t/definition.jsonrpc
+

kadircet wrote:
> shouldn't this one be running ?
Argh, sorry somehow I got confused and thought these were commented-out.. NVM


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54894



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


[PATCH] D54894: [clangd] Enable auto-index behind a flag.

2018-11-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 175249.
sammccall marked an inline comment as done.
sammccall added a comment.

Make blockUntilIdleForTest() accept a timeout, update comment.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54894

Files:
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/GlobalCompilationDatabase.cpp
  clangd/index/Background.cpp
  clangd/index/Background.h
  clangd/index/BackgroundIndexStorage.cpp
  clangd/tool/ClangdMain.cpp
  test/clangd/Inputs/background-index/compile_commands.json
  test/clangd/Inputs/background-index/definition.jsonrpc
  test/clangd/Inputs/background-index/foo.cpp
  test/clangd/Inputs/background-index/foo.h
  test/clangd/background-index.test
  unittests/clangd/BackgroundIndexTests.cpp

Index: unittests/clangd/BackgroundIndexTests.cpp
===
--- unittests/clangd/BackgroundIndexTests.cpp
+++ unittests/clangd/BackgroundIndexTests.cpp
@@ -90,7 +90,7 @@
   Cmd.CommandLine = {"clang++", "-DA=1", testPath("root/A.cc")};
   CDB.setCompileCommand(testPath("root"), Cmd);
 
-  Idx.blockUntilIdleForTest();
+  ASSERT_TRUE(Idx.blockUntilIdleForTest());
   EXPECT_THAT(
   runFuzzyFind(Idx, ""),
   UnorderedElementsAre(Named("common"), Named("A_CC"),
@@ -100,7 +100,7 @@
   Cmd.CommandLine = {"clang++", Cmd.Filename};
   CDB.setCompileCommand(testPath("root"), Cmd);
 
-  Idx.blockUntilIdleForTest();
+  ASSERT_TRUE(Idx.blockUntilIdleForTest());
   // B_CC is dropped as we don't collect symbols from A.h in this compilation.
   EXPECT_THAT(runFuzzyFind(Idx, ""),
   UnorderedElementsAre(Named("common"), Named("A_CC"),
@@ -141,7 +141,7 @@
 BackgroundIndex Idx(Context::empty(), "", FS, CDB,
 [&](llvm::StringRef) { return &MSS; });
 CDB.setCompileCommand(testPath("root"), Cmd);
-Idx.blockUntilIdleForTest();
+ASSERT_TRUE(Idx.blockUntilIdleForTest());
   }
   EXPECT_EQ(CacheHits, 0U);
   EXPECT_EQ(Storage.size(), 2U);
Index: test/clangd/background-index.test
===
--- /dev/null
+++ test/clangd/background-index.test
@@ -0,0 +1,21 @@
+# We need to splice paths into file:// URIs for this test.
+# UNSUPPORTED: win32
+
+# Use a copy of inputs, as we'll mutate it (as will the background index).
+# RUN: rm -rf %t
+# RUN: cp -r %S/Inputs/background-index %t
+# Need to embed the correct temp path in the actual JSON-RPC requests.
+# RUN: sed -i -e "s|DIRECTORY|%t|" %t/*
+
+# We're editing bar.cpp, which includes foo.h.
+# foo() is declared in foo.h and defined in foo.cpp.
+# The background index should allow us to go-to-definition on foo().
+# RUN: clangd -background-index -lit-test < %t/definition.jsonrpc | FileCheck %t/definition.jsonrpc
+
+# Test that the index is writing files in the expected location.
+# RUN: ls %t/.clangd-index/foo.cpp.*.idx
+
+# Test the index is read from disk: delete code and restart clangd.
+# FIXME: This test currently fails as we don't read the index yet.
+# RUN: rm %t/foo.cpp
+# RUN: clangd -background-index -lit-test < %t/definition.jsonrpc | not FileCheck %t/definition.jsonrpc
Index: test/clangd/Inputs/background-index/foo.h
===
--- /dev/null
+++ test/clangd/Inputs/background-index/foo.h
@@ -0,0 +1,4 @@
+#ifndef FOO_H
+#define FOO_H
+int foo();
+#endif
Index: test/clangd/Inputs/background-index/foo.cpp
===
--- /dev/null
+++ test/clangd/Inputs/background-index/foo.cpp
@@ -0,0 +1,2 @@
+#include "foo.h"
+int foo() { return 42; }
Index: test/clangd/Inputs/background-index/definition.jsonrpc
===
--- /dev/null
+++ test/clangd/Inputs/background-index/definition.jsonrpc
@@ -0,0 +1,51 @@
+{
+  "jsonrpc": "2.0",
+  "id": 0,
+  "method": "initialize",
+  "params": {
+"processId": 123,
+"rootPath": "clangd",
+"capabilities": {},
+"trace": "off"
+  }
+}
+---
+{
+  "jsonrpc": "2.0",
+  "method": "textDocument/didOpen",
+  "params": {
+"textDocument": {
+  "uri": "file://DIRECTORY/bar.cpp",
+  "languageId": "cpp",
+  "version": 1,
+  "text": "#include \"foo.h\"\nint main(){\nreturn foo();\n}"
+}
+  }
+}
+---
+{
+  "jsonrpc": "2.0",
+  "id": 1,
+  "method": "sync",
+  "params": null
+}
+---
+{
+  "jsonrpc": "2.0",
+  "id": 2,
+  "method": "textDocument/definition",
+  "params": {
+"textDocument": {
+  "uri": "file://DIRECTORY/bar.cpp"
+},
+"position": {
+  "line": 2,
+  "character": 8
+}
+  }
+}
+# CHECK: "uri": "file://DIRECTORY/foo.cpp"
+---
+{"jsonrpc":"2.0","id":3,"method":"shutdown"}
+---
+{"jsonrpc":"2.0","method":"exit"}
Index: test/clangd/Inputs/background-index/compile_commands.json
===

[PATCH] D40988: Clang-format: add finer-grained options for putting all arguments on one line

2018-11-26 Thread Russell McClellan via Phabricator via cfe-commits
russellmcc added a comment.

Bump!  Thanks again for your consideration


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

https://reviews.llvm.org/D40988



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


[PATCH] D45478: [clangd] Merge symbols in global-sym-builder on the go

2018-11-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov abandoned this revision.
ilya-biryukov added a comment.
Herald added subscribers: kadircet, arphaman.

This landed as a different change.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D45478



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


r347558 - [Index] Expose USR generation for types

2018-11-26 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Nov 26 07:24:48 2018
New Revision: 347558

URL: http://llvm.org/viewvc/llvm-project?rev=347558&view=rev
Log:
[Index] Expose USR generation for types

Summary: Used in clangd.

Reviewers: sammccall, ioeric

Reviewed By: sammccall

Subscribers: kadircet, cfe-commits

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

Modified:
cfe/trunk/include/clang/Index/USRGeneration.h
cfe/trunk/lib/Index/USRGeneration.cpp

Modified: cfe/trunk/include/clang/Index/USRGeneration.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Index/USRGeneration.h?rev=347558&r1=347557&r2=347558&view=diff
==
--- cfe/trunk/include/clang/Index/USRGeneration.h (original)
+++ cfe/trunk/include/clang/Index/USRGeneration.h Mon Nov 26 07:24:48 2018
@@ -14,11 +14,13 @@
 #include "llvm/ADT/StringRef.h"
 
 namespace clang {
+class ASTContext;
 class Decl;
 class MacroDefinitionRecord;
 class Module;
 class SourceLocation;
 class SourceManager;
+class QualType;
 
 namespace index {
 
@@ -71,6 +73,11 @@ bool generateUSRForMacro(const MacroDefi
 bool generateUSRForMacro(StringRef MacroName, SourceLocation Loc,
  const SourceManager &SM, SmallVectorImpl &Buf);
 
+/// Generates a USR for a type.
+///
+/// \return true on error, false on success.
+bool generateUSRForType(QualType T, ASTContext &Ctx, SmallVectorImpl 
&Buf);
+
 /// Generate a USR for a module, including the USR prefix.
 /// \returns true on error, false on success.
 bool generateFullUSRForModule(const Module *Mod, raw_ostream &OS);
@@ -87,6 +94,7 @@ bool generateUSRFragmentForModule(const
 /// \returns true on error, false on success.
 bool generateUSRFragmentForModuleName(StringRef ModName, raw_ostream &OS);
 
+
 } // namespace index
 } // namespace clang
 

Modified: cfe/trunk/lib/Index/USRGeneration.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Index/USRGeneration.cpp?rev=347558&r1=347557&r2=347558&view=diff
==
--- cfe/trunk/lib/Index/USRGeneration.cpp (original)
+++ cfe/trunk/lib/Index/USRGeneration.cpp Mon Nov 26 07:24:48 2018
@@ -1105,6 +1105,17 @@ bool clang::index::generateUSRForMacro(S
   return false;
 }
 
+bool clang::index::generateUSRForType(QualType T, ASTContext &Ctx,
+  SmallVectorImpl &Buf) {
+  if (T.isNull())
+return true;
+  T = T.getCanonicalType();
+
+  USRGenerator UG(&Ctx, Buf);
+  UG.VisitType(T);
+  return UG.ignoreResults();
+}
+
 bool clang::index::generateFullUSRForModule(const Module *Mod,
 raw_ostream &OS) {
   if (!Mod->Parent)


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


[PATCH] D52275: [Index] Expose USR generation for types

2018-11-26 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC347558: [Index] Expose USR generation for types (authored by 
ibiryukov, committed by ).
Herald added a subscriber: arphaman.

Changed prior to commit:
  https://reviews.llvm.org/D52275?vs=166167&id=175252#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D52275

Files:
  include/clang/Index/USRGeneration.h
  lib/Index/USRGeneration.cpp


Index: lib/Index/USRGeneration.cpp
===
--- lib/Index/USRGeneration.cpp
+++ lib/Index/USRGeneration.cpp
@@ -1105,6 +1105,17 @@
   return false;
 }
 
+bool clang::index::generateUSRForType(QualType T, ASTContext &Ctx,
+  SmallVectorImpl &Buf) {
+  if (T.isNull())
+return true;
+  T = T.getCanonicalType();
+
+  USRGenerator UG(&Ctx, Buf);
+  UG.VisitType(T);
+  return UG.ignoreResults();
+}
+
 bool clang::index::generateFullUSRForModule(const Module *Mod,
 raw_ostream &OS) {
   if (!Mod->Parent)
Index: include/clang/Index/USRGeneration.h
===
--- include/clang/Index/USRGeneration.h
+++ include/clang/Index/USRGeneration.h
@@ -14,11 +14,13 @@
 #include "llvm/ADT/StringRef.h"
 
 namespace clang {
+class ASTContext;
 class Decl;
 class MacroDefinitionRecord;
 class Module;
 class SourceLocation;
 class SourceManager;
+class QualType;
 
 namespace index {
 
@@ -71,6 +73,11 @@
 bool generateUSRForMacro(StringRef MacroName, SourceLocation Loc,
  const SourceManager &SM, SmallVectorImpl &Buf);
 
+/// Generates a USR for a type.
+///
+/// \return true on error, false on success.
+bool generateUSRForType(QualType T, ASTContext &Ctx, SmallVectorImpl 
&Buf);
+
 /// Generate a USR for a module, including the USR prefix.
 /// \returns true on error, false on success.
 bool generateFullUSRForModule(const Module *Mod, raw_ostream &OS);
@@ -87,6 +94,7 @@
 /// \returns true on error, false on success.
 bool generateUSRFragmentForModuleName(StringRef ModName, raw_ostream &OS);
 
+
 } // namespace index
 } // namespace clang
 


Index: lib/Index/USRGeneration.cpp
===
--- lib/Index/USRGeneration.cpp
+++ lib/Index/USRGeneration.cpp
@@ -1105,6 +1105,17 @@
   return false;
 }
 
+bool clang::index::generateUSRForType(QualType T, ASTContext &Ctx,
+  SmallVectorImpl &Buf) {
+  if (T.isNull())
+return true;
+  T = T.getCanonicalType();
+
+  USRGenerator UG(&Ctx, Buf);
+  UG.VisitType(T);
+  return UG.ignoreResults();
+}
+
 bool clang::index::generateFullUSRForModule(const Module *Mod,
 raw_ostream &OS) {
   if (!Mod->Parent)
Index: include/clang/Index/USRGeneration.h
===
--- include/clang/Index/USRGeneration.h
+++ include/clang/Index/USRGeneration.h
@@ -14,11 +14,13 @@
 #include "llvm/ADT/StringRef.h"
 
 namespace clang {
+class ASTContext;
 class Decl;
 class MacroDefinitionRecord;
 class Module;
 class SourceLocation;
 class SourceManager;
+class QualType;
 
 namespace index {
 
@@ -71,6 +73,11 @@
 bool generateUSRForMacro(StringRef MacroName, SourceLocation Loc,
  const SourceManager &SM, SmallVectorImpl &Buf);
 
+/// Generates a USR for a type.
+///
+/// \return true on error, false on success.
+bool generateUSRForType(QualType T, ASTContext &Ctx, SmallVectorImpl &Buf);
+
 /// Generate a USR for a module, including the USR prefix.
 /// \returns true on error, false on success.
 bool generateFullUSRForModule(const Module *Mod, raw_ostream &OS);
@@ -87,6 +94,7 @@
 /// \returns true on error, false on success.
 bool generateUSRFragmentForModuleName(StringRef ModName, raw_ostream &OS);
 
+
 } // namespace index
 } // namespace clang
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r347559 - [clangd] Initial implementation of expected types

2018-11-26 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Nov 26 07:25:20 2018
New Revision: 347559

URL: http://llvm.org/viewvc/llvm-project?rev=347559&view=rev
Log:
[clangd] Initial implementation of expected types

Summary:
Provides facilities to model the C++ conversion rules without the AST.
The introduced representation can be stored in the index and used to
implement type-based ranking improvements for index-based completions.

Reviewers: sammccall, ioeric

Reviewed By: sammccall

Subscribers: malaperle, mgorny, MaskRay, jkorous, arphaman, kadircet, 
cfe-commits

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

Added:
clang-tools-extra/trunk/clangd/ExpectedTypes.cpp
clang-tools-extra/trunk/clangd/ExpectedTypes.h
clang-tools-extra/trunk/unittests/clangd/ExpectedTypeTest.cpp
Modified:
clang-tools-extra/trunk/clangd/CMakeLists.txt
clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt

Modified: clang-tools-extra/trunk/clangd/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CMakeLists.txt?rev=347559&r1=347558&r2=347559&view=diff
==
--- clang-tools-extra/trunk/clangd/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clangd/CMakeLists.txt Mon Nov 26 07:25:20 2018
@@ -19,6 +19,7 @@ add_clang_library(clangDaemon
   Context.cpp
   Diagnostics.cpp
   DraftStore.cpp
+  ExpectedTypes.cpp
   FindSymbols.cpp
   FileDistance.cpp
   FS.cpp

Added: clang-tools-extra/trunk/clangd/ExpectedTypes.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ExpectedTypes.cpp?rev=347559&view=auto
==
--- clang-tools-extra/trunk/clangd/ExpectedTypes.cpp (added)
+++ clang-tools-extra/trunk/clangd/ExpectedTypes.cpp Mon Nov 26 07:25:20 2018
@@ -0,0 +1,80 @@
+#include "ExpectedTypes.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Type.h"
+#include "clang/Index/USRGeneration.h"
+#include "clang/Sema/CodeCompleteConsumer.h"
+#include "llvm/ADT/STLExtras.h"
+
+using namespace llvm;
+
+namespace clang {
+namespace clangd {
+namespace {
+
+static const Type *toEquivClass(ASTContext &Ctx, QualType T) {
+  if (T.isNull() || T->isDependentType())
+return nullptr;
+  // Drop references, we do not handle reference inits properly anyway.
+  T = T.getCanonicalType().getNonReferenceType();
+  // Numeric types are the simplest case.
+  if (T->isBooleanType())
+return Ctx.BoolTy.getTypePtr();
+  if (T->isIntegerType() && !T->isEnumeralType())
+return Ctx.IntTy.getTypePtr(); // All integers are equivalent.
+  if (T->isFloatingType() && !T->isComplexType())
+return Ctx.FloatTy.getTypePtr(); // All floats are equivalent.
+
+  // Do some simple transformations.
+  if (T->isArrayType()) // Decay arrays to pointers.
+return Ctx.getPointerType(QualType(T->getArrayElementTypeNoTypeQual(), 0))
+.getTypePtr();
+  // Drop the qualifiers and return the resulting type.
+  // FIXME: also drop qualifiers from pointer types, e.g. 'const T* => T*'
+  return T.getTypePtr();
+}
+
+static Optional typeOfCompletion(const CodeCompletionResult &R) {
+  auto *VD = dyn_cast_or_null(R.Declaration);
+  if (!VD)
+return None; // We handle only variables and functions below.
+  auto T = VD->getType();
+  if (auto FuncT = T->getAs()) {
+// Functions are a special case. They are completed as 'foo()' and we want
+// to match their return type rather than the function type itself.
+// FIXME(ibiryukov): in some cases, we might want to avoid completing `()`
+// after the function name, e.g. `std::cout << std::endl`.
+return FuncT->getReturnType();
+  }
+  return T;
+}
+} // namespace
+
+Optional OpaqueType::encode(ASTContext &Ctx, QualType T) {
+  if (T.isNull())
+return None;
+  const Type *C = toEquivClass(Ctx, T);
+  if (!C)
+return None;
+  SmallString<128> Encoded;
+  if (index::generateUSRForType(QualType(C, 0), Ctx, Encoded))
+return None;
+  return OpaqueType(Encoded.str());
+}
+
+OpaqueType::OpaqueType(std::string Data) : Data(std::move(Data)) {}
+
+Optional OpaqueType::fromType(ASTContext &Ctx, QualType Type) {
+  return encode(Ctx, Type);
+}
+
+Optional
+OpaqueType::fromCompletionResult(ASTContext &Ctx,
+ const CodeCompletionResult &R) {
+  auto T = typeOfCompletion(R);
+  if (!T)
+return None;
+  return encode(Ctx, *T);
+}
+
+} // namespace clangd
+} // namespace clang

Added: clang-tools-extra/trunk/clangd/ExpectedTypes.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ExpectedTypes.h?rev=347559&view=auto
==
--- clang-tools-extra/trunk/clangd/ExpectedTypes.h (added)
+++ clang-tools-extra/trunk/clangd/ExpectedTypes.h Mon Nov 26 07:25:20 2018
@@ -0,0 +1,65 @@
+//===--- ExpectedTypes.h - Simplified C++ types -*- 
C++-*--===//
+//
+//

[PATCH] D52273: [clangd] Initial implementation of expected types

2018-11-26 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL347559: [clangd] Initial implementation of expected types 
(authored by ibiryukov, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

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

https://reviews.llvm.org/D52273

Files:
  clang-tools-extra/trunk/clangd/CMakeLists.txt
  clang-tools-extra/trunk/clangd/ExpectedTypes.cpp
  clang-tools-extra/trunk/clangd/ExpectedTypes.h
  clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt
  clang-tools-extra/trunk/unittests/clangd/ExpectedTypeTest.cpp

Index: clang-tools-extra/trunk/unittests/clangd/ExpectedTypeTest.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/ExpectedTypeTest.cpp
+++ clang-tools-extra/trunk/unittests/clangd/ExpectedTypeTest.cpp
@@ -0,0 +1,157 @@
+//===-- ExpectedTypeTest.cpp  ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "ClangdUnit.h"
+#include "ExpectedTypes.h"
+#include "TestTU.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "llvm/ADT/StringRef.h"
+#include "gmock/gmock-matchers.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+using namespace llvm;
+
+namespace clang {
+namespace clangd {
+namespace {
+
+using ::testing::Field;
+using ::testing::Matcher;
+using ::testing::SizeIs;
+using ::testing::UnorderedElementsAreArray;
+
+class ExpectedTypeConversionTest : public ::testing::Test {
+protected:
+  void build(StringRef Code) {
+assert(!AST && "AST built twice");
+AST = TestTU::withCode(Code).build();
+  }
+
+  const ValueDecl *decl(StringRef Name) {
+return &cast(findDecl(*AST, Name));
+  }
+
+  QualType typeOf(StringRef Name) {
+return decl(Name)->getType().getCanonicalType();
+  }
+
+  /// An overload for convenience.
+  Optional fromCompletionResult(const ValueDecl *D) {
+return OpaqueType::fromCompletionResult(
+ASTCtx(), CodeCompletionResult(D, CCP_Declaration));
+  }
+
+  /// A set of DeclNames whose type match each other computed by
+  /// OpaqueType::fromCompletionResult.
+  using EquivClass = std::set;
+
+  Matcher>
+  ClassesAre(ArrayRef Classes) {
+using MapEntry = std::map::value_type;
+
+std::vector> Elements;
+Elements.reserve(Classes.size());
+for (auto &Cls : Classes)
+  Elements.push_back(Field(&MapEntry::second, Cls));
+return UnorderedElementsAreArray(Elements);
+  }
+
+  // Groups \p Decls into equivalence classes based on the result of
+  // 'OpaqueType::fromCompletionResult'.
+  std::map
+  buildEquivClasses(ArrayRef DeclNames) {
+std::map Classes;
+for (StringRef Name : DeclNames) {
+  auto Type = OpaqueType::fromType(ASTCtx(), typeOf(Name));
+  Classes[Type->raw()].insert(Name);
+}
+return Classes;
+  }
+
+  ASTContext &ASTCtx() { return AST->getASTContext(); }
+
+private:
+  // Set after calling build().
+  Optional AST;
+};
+
+TEST_F(ExpectedTypeConversionTest, BasicTypes) {
+  build(R"cpp(
+// ints.
+bool b;
+int i;
+unsigned int ui;
+long long ll;
+
+// floats.
+float f;
+double d;
+
+// pointers
+int* iptr;
+bool* bptr;
+
+// user-defined types.
+struct X {};
+X user_type;
+  )cpp");
+
+  EXPECT_THAT(buildEquivClasses({"b", "i", "ui", "ll", "f", "d", "iptr", "bptr",
+ "user_type"}),
+  ClassesAre({{"b"},
+  {"i", "ui", "ll"},
+  {"f", "d"},
+  {"iptr"},
+  {"bptr"},
+  {"user_type"}}));
+}
+
+TEST_F(ExpectedTypeConversionTest, ReferencesDontMatter) {
+  build(R"cpp(
+int noref;
+int & ref = noref;
+const int & const_ref = noref;
+int && rv_ref = 10;
+  )cpp");
+
+  EXPECT_THAT(buildEquivClasses({"noref", "ref", "const_ref", "rv_ref"}),
+  SizeIs(1));
+}
+
+TEST_F(ExpectedTypeConversionTest, ArraysDecay) {
+  build(R"cpp(
+ int arr[2];
+ int (&arr_ref)[2] = arr;
+ int *ptr;
+  )cpp");
+
+  EXPECT_THAT(buildEquivClasses({"arr", "arr_ref", "ptr"}), SizeIs(1));
+}
+
+TEST_F(ExpectedTypeConversionTest, FunctionReturns) {
+  build(R"cpp(
+ int returns_int();
+ int* returns_ptr();
+
+ int int_;
+ int* int_ptr;
+  )cpp");
+
+  OpaqueType IntTy = *OpaqueType::fromType(ASTCtx(), typeOf("int_"));
+  EXPECT_EQ(fromCompletionResult(decl("returns_int")), IntTy);
+
+  OpaqueType IntPtrTy = *OpaqueType::fromType(ASTCtx(), typeOf("int_ptr"));
+  EXPECT_EQ(fromCompletionResult(decl("returns_ptr")), IntPtrTy);
+}
+
+} // namespace
+} // namespace clangd
+} // namespace

[PATCH] D54898: Set MustBuildLookupTable on PrimaryContext in ExternalASTMerger

2018-11-26 Thread Raphael Isemann via Phabricator via cfe-commits
teemperor created this revision.
teemperor added reviewers: martong, a.sidorin.
teemperor added a project: LLDB.
Herald added subscribers: cfe-commits, rnkovacs.

`MustBuildLookupTable` must always be called on a primary context as we 
otherwise
trigger an assert, but we don't ensure that this will always happen in our code 
right now.

This patch explicitly requests the primary context when doing this call as this 
shouldn't break
anything (as calling `getPrimaryContext` on a context which is its own primary 
context is a no-op) 
but will catch these rare cases where we somehow operate on a declaration 
context that is
not its own primary context.

See also D54863 .


Repository:
  rC Clang

https://reviews.llvm.org/D54898

Files:
  lib/AST/ExternalASTMerger.cpp


Index: lib/AST/ExternalASTMerger.cpp
===
--- lib/AST/ExternalASTMerger.cpp
+++ lib/AST/ExternalASTMerger.cpp
@@ -144,14 +144,14 @@
 }
 if (auto *ToTag = dyn_cast(To)) {
   ToTag->setHasExternalLexicalStorage();
-  ToTag->setMustBuildLookupTable();
+  ToTag->getPrimaryContext()->setMustBuildLookupTable();
   assert(Parent.CanComplete(ToTag));
 } else if (auto *ToNamespace = dyn_cast(To)) {
   ToNamespace->setHasExternalVisibleStorage();
   assert(Parent.CanComplete(ToNamespace));
 } else if (auto *ToContainer = dyn_cast(To)) {
   ToContainer->setHasExternalLexicalStorage();
-  ToContainer->setMustBuildLookupTable();
+  ToContainer->getPrimaryContext()->setMustBuildLookupTable();
   assert(Parent.CanComplete(ToContainer));
 }
 return To;


Index: lib/AST/ExternalASTMerger.cpp
===
--- lib/AST/ExternalASTMerger.cpp
+++ lib/AST/ExternalASTMerger.cpp
@@ -144,14 +144,14 @@
 }
 if (auto *ToTag = dyn_cast(To)) {
   ToTag->setHasExternalLexicalStorage();
-  ToTag->setMustBuildLookupTable();
+  ToTag->getPrimaryContext()->setMustBuildLookupTable();
   assert(Parent.CanComplete(ToTag));
 } else if (auto *ToNamespace = dyn_cast(To)) {
   ToNamespace->setHasExternalVisibleStorage();
   assert(Parent.CanComplete(ToNamespace));
 } else if (auto *ToContainer = dyn_cast(To)) {
   ToContainer->setHasExternalLexicalStorage();
-  ToContainer->setMustBuildLookupTable();
+  ToContainer->getPrimaryContext()->setMustBuildLookupTable();
   assert(Parent.CanComplete(ToContainer));
 }
 return To;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52274: [clangd] Collect and store expected types in the index

2018-11-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 175254.
ilya-biryukov added a comment.

- Remove unused #include


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D52274

Files:
  clangd/index/Index.h
  clangd/index/Serialization.cpp
  clangd/index/SymbolCollector.cpp
  clangd/index/YAMLSerialization.cpp


Index: clangd/index/YAMLSerialization.cpp
===
--- clangd/index/YAMLSerialization.cpp
+++ clangd/index/YAMLSerialization.cpp
@@ -197,6 +197,7 @@
 IO.mapOptional("CompletionSnippetSuffix", Sym.CompletionSnippetSuffix);
 IO.mapOptional("Documentation", Sym.Documentation);
 IO.mapOptional("ReturnType", Sym.ReturnType);
+IO.mapOptional("Type", Sym.Type);
 IO.mapOptional("IncludeHeaders", Sym.IncludeHeaders);
   }
 };
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -587,6 +587,11 @@
   if (!Include.empty())
 S.IncludeHeaders.emplace_back(Include, 1);
 
+  if (S.Flags & Symbol::IndexedForCodeCompletion) {
+if (auto T = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion))
+  S.Type = T->raw();
+  }
+
   S.Origin = Opts.Origin;
   if (ND.getAvailability() == AR_Deprecated)
 S.Flags |= Symbol::Deprecated;
Index: clangd/index/Serialization.cpp
===
--- clangd/index/Serialization.cpp
+++ clangd/index/Serialization.cpp
@@ -264,6 +264,7 @@
   writeVar(Strings.index(Sym.CompletionSnippetSuffix), OS);
   writeVar(Strings.index(Sym.Documentation), OS);
   writeVar(Strings.index(Sym.ReturnType), OS);
+  writeVar(Strings.index(Sym.Type), OS);
 
   auto WriteInclude = [&](const Symbol::IncludeHeaderWithReferences &Include) {
 writeVar(Strings.index(Include.IncludeHeader), OS);
@@ -290,6 +291,7 @@
   Sym.CompletionSnippetSuffix = Data.consumeString(Strings);
   Sym.Documentation = Data.consumeString(Strings);
   Sym.ReturnType = Data.consumeString(Strings);
+  Sym.Type = Data.consumeString(Strings);
   Sym.IncludeHeaders.resize(Data.consumeVar());
   for (auto &I : Sym.IncludeHeaders) {
 I.IncludeHeader = Data.consumeString(Strings);
@@ -339,7 +341,7 @@
 // The current versioning scheme is simple - non-current versions are rejected.
 // If you make a breaking change, bump this version number to invalidate stored
 // data. Later we may want to support some backward compatibility.
-constexpr static uint32_t Version = 7;
+constexpr static uint32_t Version = 8;
 
 Expected readRIFF(StringRef Data) {
   auto RIFF = riff::readFile(Data);
Index: clangd/index/Index.h
===
--- clangd/index/Index.h
+++ clangd/index/Index.h
@@ -10,6 +10,7 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_H
 
+#include "ExpectedTypes.h"
 #include "clang/Index/IndexSymbol.h"
 #include "clang/Lex/Lexer.h"
 #include "llvm/ADT/DenseMap.h"
@@ -242,6 +243,10 @@
   /// e.g. return type of a function, or type of a variable.
   llvm::StringRef ReturnType;
 
+  /// Raw representation of the OpaqueType of the symbol, used for scoring
+  /// purposes.
+  llvm::StringRef Type;
+
   struct IncludeHeaderWithReferences {
 IncludeHeaderWithReferences() = default;
 
@@ -300,6 +305,7 @@
   CB(S.CompletionSnippetSuffix);
   CB(S.Documentation);
   CB(S.ReturnType);
+  CB(S.Type);
   auto RawCharPointerCB = [&CB](const char *&P) {
 llvm::StringRef S(P);
 CB(S);


Index: clangd/index/YAMLSerialization.cpp
===
--- clangd/index/YAMLSerialization.cpp
+++ clangd/index/YAMLSerialization.cpp
@@ -197,6 +197,7 @@
 IO.mapOptional("CompletionSnippetSuffix", Sym.CompletionSnippetSuffix);
 IO.mapOptional("Documentation", Sym.Documentation);
 IO.mapOptional("ReturnType", Sym.ReturnType);
+IO.mapOptional("Type", Sym.Type);
 IO.mapOptional("IncludeHeaders", Sym.IncludeHeaders);
   }
 };
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -587,6 +587,11 @@
   if (!Include.empty())
 S.IncludeHeaders.emplace_back(Include, 1);
 
+  if (S.Flags & Symbol::IndexedForCodeCompletion) {
+if (auto T = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion))
+  S.Type = T->raw();
+  }
+
   S.Origin = Opts.Origin;
   if (ND.getAvailability() == AR_Deprecated)
 S.Flags |= Symbol::Deprecated;
Index: clangd/index/Serialization.cpp
===
--- clangd/index/Serialization.cpp
+++ clangd/index/Serialization.cpp
@@ -264,6 +264,7 @@
   writeVar(Strings.index(Sym.CompletionSnippetSuffix), OS);
   writeVar(

[clang-tools-extra] r347560 - [clangd] Collect and store expected types in the index

2018-11-26 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Nov 26 07:29:14 2018
New Revision: 347560

URL: http://llvm.org/viewvc/llvm-project?rev=347560&view=rev
Log:
[clangd] Collect and store expected types in the index

Summary:
And add a hidden option to control whether the types are collected.
For experiments, will be removed when expected types implementation
is stabilized.

The index size is almost unchanged, e.g. the YAML index for all clangd
sources increased from 53MB to 54MB.

Reviewers: ioeric, sammccall

Reviewed By: sammccall

Subscribers: MaskRay, jkorous, arphaman, kadircet, cfe-commits

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

Modified:
clang-tools-extra/trunk/clangd/index/Index.h
clang-tools-extra/trunk/clangd/index/Serialization.cpp
clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp

Modified: clang-tools-extra/trunk/clangd/index/Index.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Index.h?rev=347560&r1=347559&r2=347560&view=diff
==
--- clang-tools-extra/trunk/clangd/index/Index.h (original)
+++ clang-tools-extra/trunk/clangd/index/Index.h Mon Nov 26 07:29:14 2018
@@ -10,6 +10,7 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_H
 
+#include "ExpectedTypes.h"
 #include "clang/Index/IndexSymbol.h"
 #include "clang/Lex/Lexer.h"
 #include "llvm/ADT/DenseMap.h"
@@ -242,6 +243,10 @@ struct Symbol {
   /// e.g. return type of a function, or type of a variable.
   llvm::StringRef ReturnType;
 
+  /// Raw representation of the OpaqueType of the symbol, used for scoring
+  /// purposes.
+  llvm::StringRef Type;
+
   struct IncludeHeaderWithReferences {
 IncludeHeaderWithReferences() = default;
 
@@ -300,6 +305,7 @@ template  void visitS
   CB(S.CompletionSnippetSuffix);
   CB(S.Documentation);
   CB(S.ReturnType);
+  CB(S.Type);
   auto RawCharPointerCB = [&CB](const char *&P) {
 llvm::StringRef S(P);
 CB(S);

Modified: clang-tools-extra/trunk/clangd/index/Serialization.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Serialization.cpp?rev=347560&r1=347559&r2=347560&view=diff
==
--- clang-tools-extra/trunk/clangd/index/Serialization.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Serialization.cpp Mon Nov 26 07:29:14 
2018
@@ -264,6 +264,7 @@ void writeSymbol(const Symbol &Sym, cons
   writeVar(Strings.index(Sym.CompletionSnippetSuffix), OS);
   writeVar(Strings.index(Sym.Documentation), OS);
   writeVar(Strings.index(Sym.ReturnType), OS);
+  writeVar(Strings.index(Sym.Type), OS);
 
   auto WriteInclude = [&](const Symbol::IncludeHeaderWithReferences &Include) {
 writeVar(Strings.index(Include.IncludeHeader), OS);
@@ -290,6 +291,7 @@ Symbol readSymbol(Reader &Data, ArrayRef
   Sym.CompletionSnippetSuffix = Data.consumeString(Strings);
   Sym.Documentation = Data.consumeString(Strings);
   Sym.ReturnType = Data.consumeString(Strings);
+  Sym.Type = Data.consumeString(Strings);
   Sym.IncludeHeaders.resize(Data.consumeVar());
   for (auto &I : Sym.IncludeHeaders) {
 I.IncludeHeader = Data.consumeString(Strings);
@@ -339,7 +341,7 @@ std::pair> re
 // The current versioning scheme is simple - non-current versions are rejected.
 // If you make a breaking change, bump this version number to invalidate stored
 // data. Later we may want to support some backward compatibility.
-constexpr static uint32_t Version = 7;
+constexpr static uint32_t Version = 8;
 
 Expected readRIFF(StringRef Data) {
   auto RIFF = riff::readFile(Data);

Modified: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp?rev=347560&r1=347559&r2=347560&view=diff
==
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp Mon Nov 26 
07:29:14 2018
@@ -587,6 +587,11 @@ const Symbol *SymbolCollector::addDeclar
   if (!Include.empty())
 S.IncludeHeaders.emplace_back(Include, 1);
 
+  if (S.Flags & Symbol::IndexedForCodeCompletion) {
+if (auto T = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion))
+  S.Type = T->raw();
+  }
+
   S.Origin = Opts.Origin;
   if (ND.getAvailability() == AR_Deprecated)
 S.Flags |= Symbol::Deprecated;

Modified: clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp?rev=347560&r1=347559&r2=347560&view=diff
==
--- clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp (original)
+++ clang-to

[PATCH] D52274: [clangd] Collect and store expected types in the index

2018-11-26 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL347560: [clangd] Collect and store expected types in the 
index (authored by ibiryukov, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

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

https://reviews.llvm.org/D52274

Files:
  clang-tools-extra/trunk/clangd/index/Index.h
  clang-tools-extra/trunk/clangd/index/Serialization.cpp
  clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
  clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp


Index: clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
===
--- clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
+++ clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
@@ -197,6 +197,7 @@
 IO.mapOptional("CompletionSnippetSuffix", Sym.CompletionSnippetSuffix);
 IO.mapOptional("Documentation", Sym.Documentation);
 IO.mapOptional("ReturnType", Sym.ReturnType);
+IO.mapOptional("Type", Sym.Type);
 IO.mapOptional("IncludeHeaders", Sym.IncludeHeaders);
   }
 };
Index: clang-tools-extra/trunk/clangd/index/Serialization.cpp
===
--- clang-tools-extra/trunk/clangd/index/Serialization.cpp
+++ clang-tools-extra/trunk/clangd/index/Serialization.cpp
@@ -264,6 +264,7 @@
   writeVar(Strings.index(Sym.CompletionSnippetSuffix), OS);
   writeVar(Strings.index(Sym.Documentation), OS);
   writeVar(Strings.index(Sym.ReturnType), OS);
+  writeVar(Strings.index(Sym.Type), OS);
 
   auto WriteInclude = [&](const Symbol::IncludeHeaderWithReferences &Include) {
 writeVar(Strings.index(Include.IncludeHeader), OS);
@@ -290,6 +291,7 @@
   Sym.CompletionSnippetSuffix = Data.consumeString(Strings);
   Sym.Documentation = Data.consumeString(Strings);
   Sym.ReturnType = Data.consumeString(Strings);
+  Sym.Type = Data.consumeString(Strings);
   Sym.IncludeHeaders.resize(Data.consumeVar());
   for (auto &I : Sym.IncludeHeaders) {
 I.IncludeHeader = Data.consumeString(Strings);
@@ -339,7 +341,7 @@
 // The current versioning scheme is simple - non-current versions are rejected.
 // If you make a breaking change, bump this version number to invalidate stored
 // data. Later we may want to support some backward compatibility.
-constexpr static uint32_t Version = 7;
+constexpr static uint32_t Version = 8;
 
 Expected readRIFF(StringRef Data) {
   auto RIFF = riff::readFile(Data);
Index: clang-tools-extra/trunk/clangd/index/Index.h
===
--- clang-tools-extra/trunk/clangd/index/Index.h
+++ clang-tools-extra/trunk/clangd/index/Index.h
@@ -10,6 +10,7 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_H
 
+#include "ExpectedTypes.h"
 #include "clang/Index/IndexSymbol.h"
 #include "clang/Lex/Lexer.h"
 #include "llvm/ADT/DenseMap.h"
@@ -242,6 +243,10 @@
   /// e.g. return type of a function, or type of a variable.
   llvm::StringRef ReturnType;
 
+  /// Raw representation of the OpaqueType of the symbol, used for scoring
+  /// purposes.
+  llvm::StringRef Type;
+
   struct IncludeHeaderWithReferences {
 IncludeHeaderWithReferences() = default;
 
@@ -300,6 +305,7 @@
   CB(S.CompletionSnippetSuffix);
   CB(S.Documentation);
   CB(S.ReturnType);
+  CB(S.Type);
   auto RawCharPointerCB = [&CB](const char *&P) {
 llvm::StringRef S(P);
 CB(S);
Index: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
===
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
@@ -587,6 +587,11 @@
   if (!Include.empty())
 S.IncludeHeaders.emplace_back(Include, 1);
 
+  if (S.Flags & Symbol::IndexedForCodeCompletion) {
+if (auto T = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion))
+  S.Type = T->raw();
+  }
+
   S.Origin = Opts.Origin;
   if (ND.getAvailability() == AR_Deprecated)
 S.Flags |= Symbol::Deprecated;


Index: clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
===
--- clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
+++ clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
@@ -197,6 +197,7 @@
 IO.mapOptional("CompletionSnippetSuffix", Sym.CompletionSnippetSuffix);
 IO.mapOptional("Documentation", Sym.Documentation);
 IO.mapOptional("ReturnType", Sym.ReturnType);
+IO.mapOptional("Type", Sym.Type);
 IO.mapOptional("IncludeHeaders", Sym.IncludeHeaders);
   }
 };
Index: clang-tools-extra/trunk/clangd/index/Serialization.cpp
===
--- clang-tools-extra/trunk/clangd/index/Serialization.cpp
+++ clang-tools-extra/trunk/clangd/index/Serialization.cpp
@@ -

[PATCH] D52276: [clangd] Add type boosting in code completion

2018-11-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 175257.
ilya-biryukov marked 2 inline comments as done.
ilya-biryukov added a comment.

- Address comments


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D52276

Files:
  clangd/CodeComplete.cpp
  clangd/Quality.cpp
  clangd/Quality.h

Index: clangd/Quality.h
===
--- clangd/Quality.h
+++ clangd/Quality.h
@@ -28,6 +28,7 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_QUALITY_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_QUALITY_H
 
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "clang/Sema/CodeCompleteConsumer.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -122,6 +123,13 @@
   // Whether symbol is an instance member of a class.
   bool IsInstanceMember = false;
 
+  // Whether clang provided a preferred type in the completion context.
+  bool HadContextType = false;
+  // Whether a source completion item or a symbol had a type information.
+  bool HadSymbolType = false;
+  // Whether the item matches the type expected in the completion context.
+  bool TypeMatchesPreferred = false;
+
   void merge(const CodeCompletionResult &SemaResult);
   void merge(const Symbol &IndexResult);
 
Index: clangd/Quality.cpp
===
--- clangd/Quality.cpp
+++ clangd/Quality.cpp
@@ -369,6 +369,9 @@
 }
   }
 
+  if (TypeMatchesPreferred)
+Score *= 5.0;
+
   // Penalize non-instance members when they are accessed via a class instance.
   if (!IsInstanceMember &&
   (Context == CodeCompletionContext::CCC_DotMemberAccess ||
@@ -412,6 +415,10 @@
 OS << formatv("\tIndex scope boost: {0}\n",
   scopeBoost(*S.ScopeProximityMatch, S.SymbolScope));
 
+  OS << formatv(
+  "\tType matched preferred: {0} (Context type: {1}, Symbol type: {2}\n",
+  S.TypeMatchesPreferred, S.HadContextType, S.HadSymbolType);
+
   return OS;
 }
 
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -24,6 +24,7 @@
 #include "CodeCompletionStrings.h"
 #include "Compiler.h"
 #include "Diagnostics.h"
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "FuzzyMatch.h"
 #include "Headers.h"
@@ -1225,6 +1226,7 @@
   std::vector QueryScopes; // Initialized once Sema runs.
   // Initialized once QueryScopes is initialized, if there are scopes.
   Optional ScopeProximity;
+  llvm::Optional PreferredType; // Initialized once Sema runs.
   // Whether to query symbols from any scope. Initialized once Sema runs.
   bool AllScopes = false;
   // Include-insertion and proximity scoring rely on the include structure.
@@ -1302,9 +1304,12 @@
   Inserter.reset(); // Make sure this doesn't out-live Clang.
   SPAN_ATTACH(Tracer, "sema_completion_kind",
   getCompletionKindString(Recorder->CCContext.getKind()));
-  log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2})",
+  log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
+  "expected type {3}",
   getCompletionKindString(Recorder->CCContext.getKind()),
-  join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes);
+  join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
+  PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
+: "");
 });
 
 Recorder = RecorderOwner.get();
@@ -1354,6 +1359,9 @@
 getQueryScopes(Recorder->CCContext, *Recorder->CCSema, Opts);
 if (!QueryScopes.empty())
   ScopeProximity.emplace(QueryScopes);
+PreferredType =
+OpaqueType::fromType(Recorder->CCSema->getASTContext(),
+ Recorder->CCContext.getPreferredType());
 // Sema provides the needed context to query the index.
 // FIXME: in addition to querying for extra/overlapping symbols, we should
 //explicitly request symbols corresponding to Sema results.
@@ -1492,6 +1500,8 @@
 Relevance.FileProximityMatch = FileProximity.getPointer();
 if (ScopeProximity)
   Relevance.ScopeProximityMatch = ScopeProximity.getPointer();
+if (PreferredType)
+  Relevance.HadContextType = true;
 
 auto &First = Bundle.front();
 if (auto FuzzyScore = fuzzyScore(First))
@@ -1506,10 +1516,24 @@
 Relevance.merge(*Candidate.IndexResult);
 Origin |= Candidate.IndexResult->Origin;
 FromIndex = true;
+if (!Candidate.IndexResult->Type.empty())
+  Relevance.HadSymbolType |= true;
+if (PreferredType &&
+PreferredType->raw() == Candidate.IndexResult->Type) {
+  Relevance.TypeMatchesPreferred = true;
+}
   }
   if (Candidate.SemaResult) {
 Quality.merge(*Candidate.SemaResult);
 Relevance.merge(*Candidate.SemaResult);
+ 

[PATCH] D54900: [Sema] Avoid CallExpr::setNumArgs in Sema::BuildCallToObjectOfClassType

2018-11-26 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno created this revision.
riccibruno added reviewers: rsmith, aaron.ballman.
riccibruno added a project: clang.
Herald added subscribers: cfe-commits, dexonsmith, inglorion, mehdi_amini.

`CallExpr::setNumArgs` is the only thing that prevents storing the arguments
of a call expression in a trailing array since it might resize the argument 
array.
`setNumArgs` is only called in 3 places in `Sema`, and for all of them it is
possible to avoid it.

This deals with the call to `setNumArgs` in `BuildCallToObjectOfClassType`.
Instead of constructing the `CXXOperatorCallExpr` first and later calling
`setNumArgs` if we have default arguments, we first construct a large
enough `SmallVector`, do the promotion/check of the arguments, and
then construct the `CXXOperatorCallExpr`.

Incidentally this also avoid reallocating the arguments when the
call operator has default arguments but this is not the primary goal.


Repository:
  rC Clang

https://reviews.llvm.org/D54900

Files:
  lib/Sema/SemaOverload.cpp


Index: lib/Sema/SemaOverload.cpp
===
--- lib/Sema/SemaOverload.cpp
+++ lib/Sema/SemaOverload.cpp
@@ -13257,29 +13257,14 @@
   if (NewFn.isInvalid())
 return true;
 
+  // The number of arguments slots to allocate in the call.
+  // If we have default arguments we need to allocate space for them
+  // as well. We additionally need one more slot for the object parameter.
+  unsigned NumArgsSlots = 1 + std::max(Args.size(), NumParams);
+
   // Build the full argument list for the method call (the implicit object
   // parameter is placed at the beginning of the list).
-  SmallVector MethodArgs(Args.size() + 1);
-  MethodArgs[0] = Object.get();
-  std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
-
-  // Once we've built TheCall, all of the expressions are properly
-  // owned.
-  QualType ResultTy = Method->getReturnType();
-  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
-  ResultTy = ResultTy.getNonLValueExprType(Context);
-
-  CXXOperatorCallExpr *TheCall = new (Context)
-  CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
-  VK, RParenLoc, FPOptions());
-
-  if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
-return true;
-
-  // We may have default arguments. If so, we need to allocate more
-  // slots in the call for them.
-  if (Args.size() < NumParams)
-TheCall->setNumArgs(Context, NumParams + 1);
+  SmallVector MethodArgs(NumArgsSlots);
 
   bool IsError = false;
 
@@ -13291,7 +13276,7 @@
 IsError = true;
   else
 Object = ObjRes;
-  TheCall->setArg(0, Object.get());
+  MethodArgs[0] = Object.get();
 
   // Check the argument types.
   for (unsigned i = 0; i != NumParams; i++) {
@@ -13320,7 +13305,7 @@
   Arg = DefArg.getAs();
 }
 
-TheCall->setArg(i + 1, Arg);
+MethodArgs[i+1] = Arg;
   }
 
   // If this is a variadic call, handle args passed through "...".
@@ -13330,14 +13315,27 @@
   ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], 
VariadicMethod,
 nullptr);
   IsError |= Arg.isInvalid();
-  TheCall->setArg(i + 1, Arg.get());
+  MethodArgs[i+1] = Arg.get();
 }
   }
 
-  if (IsError) return true;
+  if (IsError)
+return true;
 
   DiagnoseSentinelCalls(Method, LParenLoc, Args);
 
+  // Once we've built TheCall, all of the expressions are properly owned.
+  QualType ResultTy = Method->getReturnType();
+  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
+  ResultTy = ResultTy.getNonLValueExprType(Context);
+
+  CXXOperatorCallExpr *TheCall = new (Context)
+  CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
+  VK, RParenLoc, FPOptions());
+
+  if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
+return true;
+
   if (CheckFunctionCall(Method, TheCall, Proto))
 return true;
 


Index: lib/Sema/SemaOverload.cpp
===
--- lib/Sema/SemaOverload.cpp
+++ lib/Sema/SemaOverload.cpp
@@ -13257,29 +13257,14 @@
   if (NewFn.isInvalid())
 return true;
 
+  // The number of arguments slots to allocate in the call.
+  // If we have default arguments we need to allocate space for them
+  // as well. We additionally need one more slot for the object parameter.
+  unsigned NumArgsSlots = 1 + std::max(Args.size(), NumParams);
+
   // Build the full argument list for the method call (the implicit object
   // parameter is placed at the beginning of the list).
-  SmallVector MethodArgs(Args.size() + 1);
-  MethodArgs[0] = Object.get();
-  std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
-
-  // Once we've built TheCall, all of the expressions are properly
-  // owned.
-  QualType ResultTy = Method->getReturnType();
-  ExprValueKind VK = Expr::getValueKindForType(ResultTy)

[PATCH] D54894: [clangd] Enable auto-index behind a flag.

2018-11-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked an inline comment as done.
sammccall added inline comments.



Comment at: test/clangd/background-index.test:16
+# Test that the index is writing files in the expected location.
+# RUN: ls %t/.clangd-index/foo.cpp.*.idx
+

kadircet wrote:
> kadircet wrote:
> > and this
> also I suppose we might wanna delete this file after test ends(if the temp 
> directory is not already deleted at exit)
Convention is that tests are responsible for cleaning up the temp directory 
*before* they run, but not after.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54894



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


[PATCH] D52276: [clangd] Add type boosting in code completion

2018-11-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 175258.
ilya-biryukov added a comment.

- Add a FIXME to FuzzyFindRequest


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D52276

Files:
  clangd/CodeComplete.cpp
  clangd/Quality.cpp
  clangd/Quality.h
  clangd/index/Index.h

Index: clangd/index/Index.h
===
--- clangd/index/Index.h
+++ clangd/index/Index.h
@@ -494,6 +494,8 @@
   /// Paths should be absolute.
   std::vector ProximityPaths;
 
+  // FIXME(ibiryukov): add expected type to the request.
+
   bool operator==(const FuzzyFindRequest &Req) const {
 return std::tie(Query, Scopes, Limit, RestrictForCodeCompletion,
 ProximityPaths) ==
Index: clangd/Quality.h
===
--- clangd/Quality.h
+++ clangd/Quality.h
@@ -28,6 +28,7 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_QUALITY_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_QUALITY_H
 
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "clang/Sema/CodeCompleteConsumer.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -122,6 +123,13 @@
   // Whether symbol is an instance member of a class.
   bool IsInstanceMember = false;
 
+  // Whether clang provided a preferred type in the completion context.
+  bool HadContextType = false;
+  // Whether a source completion item or a symbol had a type information.
+  bool HadSymbolType = false;
+  // Whether the item matches the type expected in the completion context.
+  bool TypeMatchesPreferred = false;
+
   void merge(const CodeCompletionResult &SemaResult);
   void merge(const Symbol &IndexResult);
 
Index: clangd/Quality.cpp
===
--- clangd/Quality.cpp
+++ clangd/Quality.cpp
@@ -369,6 +369,9 @@
 }
   }
 
+  if (TypeMatchesPreferred)
+Score *= 5.0;
+
   // Penalize non-instance members when they are accessed via a class instance.
   if (!IsInstanceMember &&
   (Context == CodeCompletionContext::CCC_DotMemberAccess ||
@@ -412,6 +415,10 @@
 OS << formatv("\tIndex scope boost: {0}\n",
   scopeBoost(*S.ScopeProximityMatch, S.SymbolScope));
 
+  OS << formatv(
+  "\tType matched preferred: {0} (Context type: {1}, Symbol type: {2}\n",
+  S.TypeMatchesPreferred, S.HadContextType, S.HadSymbolType);
+
   return OS;
 }
 
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -24,6 +24,7 @@
 #include "CodeCompletionStrings.h"
 #include "Compiler.h"
 #include "Diagnostics.h"
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "FuzzyMatch.h"
 #include "Headers.h"
@@ -1225,6 +1226,7 @@
   std::vector QueryScopes; // Initialized once Sema runs.
   // Initialized once QueryScopes is initialized, if there are scopes.
   Optional ScopeProximity;
+  llvm::Optional PreferredType; // Initialized once Sema runs.
   // Whether to query symbols from any scope. Initialized once Sema runs.
   bool AllScopes = false;
   // Include-insertion and proximity scoring rely on the include structure.
@@ -1302,9 +1304,12 @@
   Inserter.reset(); // Make sure this doesn't out-live Clang.
   SPAN_ATTACH(Tracer, "sema_completion_kind",
   getCompletionKindString(Recorder->CCContext.getKind()));
-  log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2})",
+  log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
+  "expected type {3}",
   getCompletionKindString(Recorder->CCContext.getKind()),
-  join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes);
+  join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
+  PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
+: "");
 });
 
 Recorder = RecorderOwner.get();
@@ -1354,6 +1359,9 @@
 getQueryScopes(Recorder->CCContext, *Recorder->CCSema, Opts);
 if (!QueryScopes.empty())
   ScopeProximity.emplace(QueryScopes);
+PreferredType =
+OpaqueType::fromType(Recorder->CCSema->getASTContext(),
+ Recorder->CCContext.getPreferredType());
 // Sema provides the needed context to query the index.
 // FIXME: in addition to querying for extra/overlapping symbols, we should
 //explicitly request symbols corresponding to Sema results.
@@ -1492,6 +1500,8 @@
 Relevance.FileProximityMatch = FileProximity.getPointer();
 if (ScopeProximity)
   Relevance.ScopeProximityMatch = ScopeProximity.getPointer();
+if (PreferredType)
+  Relevance.HadContextType = true;
 
 auto &First = Bundle.front();
 if (auto FuzzyScore = fuzzyScore(First))
@@ -1506,10 +1516,24 @@
 Relevance.merge(*Candidate.IndexResult);
 Origin |= Candidate.

[clang-tools-extra] r347562 - [clangd] Add type boosting in code completion

2018-11-26 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Nov 26 07:38:01 2018
New Revision: 347562

URL: http://llvm.org/viewvc/llvm-project?rev=347562&view=rev
Log:
[clangd] Add type boosting in code completion

Reviewers: sammccall, ioeric

Reviewed By: sammccall

Subscribers: MaskRay, jkorous, arphaman, kadircet, cfe-commits

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

Modified:
clang-tools-extra/trunk/clangd/CodeComplete.cpp
clang-tools-extra/trunk/clangd/Quality.cpp
clang-tools-extra/trunk/clangd/Quality.h
clang-tools-extra/trunk/clangd/index/Index.h

Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=347562&r1=347561&r2=347562&view=diff
==
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Mon Nov 26 07:38:01 2018
@@ -24,6 +24,7 @@
 #include "CodeCompletionStrings.h"
 #include "Compiler.h"
 #include "Diagnostics.h"
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "FuzzyMatch.h"
 #include "Headers.h"
@@ -1225,6 +1226,7 @@ class CodeCompleteFlow {
   std::vector QueryScopes; // Initialized once Sema runs.
   // Initialized once QueryScopes is initialized, if there are scopes.
   Optional ScopeProximity;
+  llvm::Optional PreferredType; // Initialized once Sema runs.
   // Whether to query symbols from any scope. Initialized once Sema runs.
   bool AllScopes = false;
   // Include-insertion and proximity scoring rely on the include structure.
@@ -1302,9 +1304,12 @@ public:
   Inserter.reset(); // Make sure this doesn't out-live Clang.
   SPAN_ATTACH(Tracer, "sema_completion_kind",
   getCompletionKindString(Recorder->CCContext.getKind()));
-  log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2})",
+  log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), 
"
+  "expected type {3}",
   getCompletionKindString(Recorder->CCContext.getKind()),
-  join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes);
+  join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
+  PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
+: "");
 });
 
 Recorder = RecorderOwner.get();
@@ -1354,6 +1359,9 @@ private:
 getQueryScopes(Recorder->CCContext, *Recorder->CCSema, Opts);
 if (!QueryScopes.empty())
   ScopeProximity.emplace(QueryScopes);
+PreferredType =
+OpaqueType::fromType(Recorder->CCSema->getASTContext(),
+ Recorder->CCContext.getPreferredType());
 // Sema provides the needed context to query the index.
 // FIXME: in addition to querying for extra/overlapping symbols, we should
 //explicitly request symbols corresponding to Sema results.
@@ -1492,6 +1500,8 @@ private:
 Relevance.FileProximityMatch = FileProximity.getPointer();
 if (ScopeProximity)
   Relevance.ScopeProximityMatch = ScopeProximity.getPointer();
+if (PreferredType)
+  Relevance.HadContextType = true;
 
 auto &First = Bundle.front();
 if (auto FuzzyScore = fuzzyScore(First))
@@ -1506,10 +1516,24 @@ private:
 Relevance.merge(*Candidate.IndexResult);
 Origin |= Candidate.IndexResult->Origin;
 FromIndex = true;
+if (!Candidate.IndexResult->Type.empty())
+  Relevance.HadSymbolType |= true;
+if (PreferredType &&
+PreferredType->raw() == Candidate.IndexResult->Type) {
+  Relevance.TypeMatchesPreferred = true;
+}
   }
   if (Candidate.SemaResult) {
 Quality.merge(*Candidate.SemaResult);
 Relevance.merge(*Candidate.SemaResult);
+if (PreferredType) {
+  if (auto CompletionType = OpaqueType::fromCompletionResult(
+  Recorder->CCSema->getASTContext(), *Candidate.SemaResult)) {
+Relevance.HadSymbolType |= true;
+if (PreferredType == CompletionType)
+  Relevance.TypeMatchesPreferred = true;
+  }
+}
 Origin |= SymbolOrigin::AST;
   }
 }

Modified: clang-tools-extra/trunk/clangd/Quality.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Quality.cpp?rev=347562&r1=347561&r2=347562&view=diff
==
--- clang-tools-extra/trunk/clangd/Quality.cpp (original)
+++ clang-tools-extra/trunk/clangd/Quality.cpp Mon Nov 26 07:38:01 2018
@@ -369,6 +369,9 @@ float SymbolRelevanceSignals::evaluate()
 }
   }
 
+  if (TypeMatchesPreferred)
+Score *= 5.0;
+
   // Penalize non-instance members when they are accessed via a class instance.
   if (!IsInstanceMember &&
   (Context == CodeCompletionContext::CCC_DotMemberAccess ||
@@ -412,6 +415,10 @@ raw_ostream &operator<<(r

[PATCH] D52276: [clangd] Add type boosting in code completion

2018-11-26 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE347562: [clangd] Add type boosting in code completion 
(authored by ibiryukov, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D52276?vs=175258&id=175260#toc

Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D52276

Files:
  clangd/CodeComplete.cpp
  clangd/Quality.cpp
  clangd/Quality.h
  clangd/index/Index.h

Index: clangd/Quality.h
===
--- clangd/Quality.h
+++ clangd/Quality.h
@@ -28,6 +28,7 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_QUALITY_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_QUALITY_H
 
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "clang/Sema/CodeCompleteConsumer.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -122,6 +123,13 @@
   // Whether symbol is an instance member of a class.
   bool IsInstanceMember = false;
 
+  // Whether clang provided a preferred type in the completion context.
+  bool HadContextType = false;
+  // Whether a source completion item or a symbol had a type information.
+  bool HadSymbolType = false;
+  // Whether the item matches the type expected in the completion context.
+  bool TypeMatchesPreferred = false;
+
   void merge(const CodeCompletionResult &SemaResult);
   void merge(const Symbol &IndexResult);
 
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -24,6 +24,7 @@
 #include "CodeCompletionStrings.h"
 #include "Compiler.h"
 #include "Diagnostics.h"
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "FuzzyMatch.h"
 #include "Headers.h"
@@ -1225,6 +1226,7 @@
   std::vector QueryScopes; // Initialized once Sema runs.
   // Initialized once QueryScopes is initialized, if there are scopes.
   Optional ScopeProximity;
+  llvm::Optional PreferredType; // Initialized once Sema runs.
   // Whether to query symbols from any scope. Initialized once Sema runs.
   bool AllScopes = false;
   // Include-insertion and proximity scoring rely on the include structure.
@@ -1302,9 +1304,12 @@
   Inserter.reset(); // Make sure this doesn't out-live Clang.
   SPAN_ATTACH(Tracer, "sema_completion_kind",
   getCompletionKindString(Recorder->CCContext.getKind()));
-  log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2})",
+  log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
+  "expected type {3}",
   getCompletionKindString(Recorder->CCContext.getKind()),
-  join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes);
+  join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
+  PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
+: "");
 });
 
 Recorder = RecorderOwner.get();
@@ -1354,6 +1359,9 @@
 getQueryScopes(Recorder->CCContext, *Recorder->CCSema, Opts);
 if (!QueryScopes.empty())
   ScopeProximity.emplace(QueryScopes);
+PreferredType =
+OpaqueType::fromType(Recorder->CCSema->getASTContext(),
+ Recorder->CCContext.getPreferredType());
 // Sema provides the needed context to query the index.
 // FIXME: in addition to querying for extra/overlapping symbols, we should
 //explicitly request symbols corresponding to Sema results.
@@ -1492,6 +1500,8 @@
 Relevance.FileProximityMatch = FileProximity.getPointer();
 if (ScopeProximity)
   Relevance.ScopeProximityMatch = ScopeProximity.getPointer();
+if (PreferredType)
+  Relevance.HadContextType = true;
 
 auto &First = Bundle.front();
 if (auto FuzzyScore = fuzzyScore(First))
@@ -1506,10 +1516,24 @@
 Relevance.merge(*Candidate.IndexResult);
 Origin |= Candidate.IndexResult->Origin;
 FromIndex = true;
+if (!Candidate.IndexResult->Type.empty())
+  Relevance.HadSymbolType |= true;
+if (PreferredType &&
+PreferredType->raw() == Candidate.IndexResult->Type) {
+  Relevance.TypeMatchesPreferred = true;
+}
   }
   if (Candidate.SemaResult) {
 Quality.merge(*Candidate.SemaResult);
 Relevance.merge(*Candidate.SemaResult);
+if (PreferredType) {
+  if (auto CompletionType = OpaqueType::fromCompletionResult(
+  Recorder->CCSema->getASTContext(), *Candidate.SemaResult)) {
+Relevance.HadSymbolType |= true;
+if (PreferredType == CompletionType)
+  Relevance.TypeMatchesPreferred = true;
+  }
+}
 Origin |= SymbolOrigin::AST;
   }
 }
Index: clangd/Quality.cpp
===
--- clangd/Quality.cpp
+++ clangd/Quality.cpp
@@ -369,6 +369,9 @@
 }
   }
 
+  i

[clang-tools-extra] r347563 - [clangd] Fix use-after-free with expected types in indexing

2018-11-26 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Nov 26 07:52:16 2018
New Revision: 347563

URL: http://llvm.org/viewvc/llvm-project?rev=347563&view=rev
Log:
[clangd] Fix use-after-free with expected types in indexing

Modified:
clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp

Modified: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp?rev=347563&r1=347562&r2=347563&view=diff
==
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp Mon Nov 26 
07:52:16 2018
@@ -587,9 +587,11 @@ const Symbol *SymbolCollector::addDeclar
   if (!Include.empty())
 S.IncludeHeaders.emplace_back(Include, 1);
 
+  llvm::Optional TypeStorage;
   if (S.Flags & Symbol::IndexedForCodeCompletion) {
-if (auto T = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion))
-  S.Type = T->raw();
+TypeStorage = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion);
+if (TypeStorage)
+  S.Type = TypeStorage->raw();
   }
 
   S.Origin = Opts.Origin;


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


r347564 - [ASTImporter][Structural Eq] Check for isBeingDefined

2018-11-26 Thread Gabor Marton via cfe-commits
Author: martong
Date: Mon Nov 26 07:54:08 2018
New Revision: 347564

URL: http://llvm.org/viewvc/llvm-project?rev=347564&view=rev
Log:
[ASTImporter][Structural Eq] Check for isBeingDefined

Summary:
If one definition is currently being defined, we do not compare for
equality and we assume that the decls are equal.

Reviewers: a_sidorin, a.sidorin, shafik

Reviewed By: a_sidorin

Subscribers: gamesh411, shafik, rnkovacs, dkrupp, Szelethus, cfe-commits

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

Modified:
cfe/trunk/lib/AST/ASTImporter.cpp
cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp
cfe/trunk/unittests/AST/ASTImporterTest.cpp

Modified: cfe/trunk/lib/AST/ASTImporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTImporter.cpp?rev=347564&r1=347563&r2=347564&view=diff
==
--- cfe/trunk/lib/AST/ASTImporter.cpp (original)
+++ cfe/trunk/lib/AST/ASTImporter.cpp Mon Nov 26 07:54:08 2018
@@ -1740,8 +1740,9 @@ Error ASTNodeImporter::ImportDefinition(
 return Err;
 
   // Add base classes.
-  if (auto *ToCXX = dyn_cast(To)) {
-auto *FromCXX = cast(From);
+  auto *ToCXX = dyn_cast(To);
+  auto *FromCXX = dyn_cast(From);
+  if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
 
 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();

Modified: cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp?rev=347564&r1=347563&r2=347564&view=diff
==
--- cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp (original)
+++ cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp Mon Nov 26 07:54:08 2018
@@ -1016,7 +1016,8 @@ static bool IsStructurallyEquivalent(Str
 return false;
 
   // Compare the definitions of these two records. If either or both are
-  // incomplete, we assume that they are equivalent.
+  // incomplete (i.e. it is a forward decl), we assume that they are
+  // equivalent.
   D1 = D1->getDefinition();
   D2 = D2->getDefinition();
   if (!D1 || !D2)
@@ -1031,6 +1032,11 @@ static bool IsStructurallyEquivalent(Str
 if (D1->hasExternalLexicalStorage() || D2->hasExternalLexicalStorage())
   return true;
 
+  // If one definition is currently being defined, we do not compare for
+  // equality and we assume that the decls are equal.
+  if (D1->isBeingDefined() || D2->isBeingDefined())
+return true;
+
   if (auto *D1CXX = dyn_cast(D1)) {
 if (auto *D2CXX = dyn_cast(D2)) {
   if (D1CXX->hasExternalLexicalStorage() &&

Modified: cfe/trunk/unittests/AST/ASTImporterTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/AST/ASTImporterTest.cpp?rev=347564&r1=347563&r2=347564&view=diff
==
--- cfe/trunk/unittests/AST/ASTImporterTest.cpp (original)
+++ cfe/trunk/unittests/AST/ASTImporterTest.cpp Mon Nov 26 07:54:08 2018
@@ -3725,6 +3725,45 @@ TEST_P(ImportFunctionTemplateSpecializat
   EXPECT_EQ(To1->getPreviousDecl(), To0);
 }
 
+TEST_P(ASTImporterTestBase,
+ImportShouldNotReportFalseODRErrorWhenRecordIsBeingDefined) {
+  {
+Decl *FromTU = getTuDecl(
+R"(
+template 
+struct B;
+)",
+Lang_CXX, "input0.cc");
+auto *FromD = FirstDeclMatcher().match(
+FromTU, classTemplateDecl(hasName("B")));
+
+Import(FromD, Lang_CXX);
+  }
+
+  {
+Decl *FromTU = getTuDecl(
+R"(
+template 
+struct B {
+  void f();
+  B* b;
+};
+)",
+Lang_CXX, "input1.cc");
+FunctionDecl *FromD = FirstDeclMatcher().match(
+FromTU, functionDecl(hasName("f")));
+Import(FromD, Lang_CXX);
+auto *FromCTD = FirstDeclMatcher().match(
+FromTU, classTemplateDecl(hasName("B")));
+auto *ToCTD = cast(Import(FromCTD, Lang_CXX));
+EXPECT_TRUE(ToCTD->isThisDeclarationADefinition());
+
+// We expect no (ODR) warning during the import.
+auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
+EXPECT_EQ(0u, ToTU->getASTContext().getDiagnostics().getNumWarnings());
+  }
+}
+
 INSTANTIATE_TEST_CASE_P(ParameterizedTests, DeclContextTest,
 ::testing::Values(ArgVector()), );
 


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


[PATCH] D53697: [ASTImporter][Structural Eq] Check for isBeingDefined

2018-11-26 Thread Gabor Marton via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL347564: [ASTImporter][Structural Eq] Check for 
isBeingDefined (authored by martong, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

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

https://reviews.llvm.org/D53697

Files:
  cfe/trunk/lib/AST/ASTImporter.cpp
  cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp
  cfe/trunk/unittests/AST/ASTImporterTest.cpp


Index: cfe/trunk/lib/AST/ASTImporter.cpp
===
--- cfe/trunk/lib/AST/ASTImporter.cpp
+++ cfe/trunk/lib/AST/ASTImporter.cpp
@@ -1740,8 +1740,9 @@
 return Err;
 
   // Add base classes.
-  if (auto *ToCXX = dyn_cast(To)) {
-auto *FromCXX = cast(From);
+  auto *ToCXX = dyn_cast(To);
+  auto *FromCXX = dyn_cast(From);
+  if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
 
 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
Index: cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp
===
--- cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp
+++ cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp
@@ -1016,7 +1016,8 @@
 return false;
 
   // Compare the definitions of these two records. If either or both are
-  // incomplete, we assume that they are equivalent.
+  // incomplete (i.e. it is a forward decl), we assume that they are
+  // equivalent.
   D1 = D1->getDefinition();
   D2 = D2->getDefinition();
   if (!D1 || !D2)
@@ -1031,6 +1032,11 @@
 if (D1->hasExternalLexicalStorage() || D2->hasExternalLexicalStorage())
   return true;
 
+  // If one definition is currently being defined, we do not compare for
+  // equality and we assume that the decls are equal.
+  if (D1->isBeingDefined() || D2->isBeingDefined())
+return true;
+
   if (auto *D1CXX = dyn_cast(D1)) {
 if (auto *D2CXX = dyn_cast(D2)) {
   if (D1CXX->hasExternalLexicalStorage() &&
Index: cfe/trunk/unittests/AST/ASTImporterTest.cpp
===
--- cfe/trunk/unittests/AST/ASTImporterTest.cpp
+++ cfe/trunk/unittests/AST/ASTImporterTest.cpp
@@ -3725,6 +3725,45 @@
   EXPECT_EQ(To1->getPreviousDecl(), To0);
 }
 
+TEST_P(ASTImporterTestBase,
+ImportShouldNotReportFalseODRErrorWhenRecordIsBeingDefined) {
+  {
+Decl *FromTU = getTuDecl(
+R"(
+template 
+struct B;
+)",
+Lang_CXX, "input0.cc");
+auto *FromD = FirstDeclMatcher().match(
+FromTU, classTemplateDecl(hasName("B")));
+
+Import(FromD, Lang_CXX);
+  }
+
+  {
+Decl *FromTU = getTuDecl(
+R"(
+template 
+struct B {
+  void f();
+  B* b;
+};
+)",
+Lang_CXX, "input1.cc");
+FunctionDecl *FromD = FirstDeclMatcher().match(
+FromTU, functionDecl(hasName("f")));
+Import(FromD, Lang_CXX);
+auto *FromCTD = FirstDeclMatcher().match(
+FromTU, classTemplateDecl(hasName("B")));
+auto *ToCTD = cast(Import(FromCTD, Lang_CXX));
+EXPECT_TRUE(ToCTD->isThisDeclarationADefinition());
+
+// We expect no (ODR) warning during the import.
+auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
+EXPECT_EQ(0u, ToTU->getASTContext().getDiagnostics().getNumWarnings());
+  }
+}
+
 INSTANTIATE_TEST_CASE_P(ParameterizedTests, DeclContextTest,
 ::testing::Values(ArgVector()), );
 


Index: cfe/trunk/lib/AST/ASTImporter.cpp
===
--- cfe/trunk/lib/AST/ASTImporter.cpp
+++ cfe/trunk/lib/AST/ASTImporter.cpp
@@ -1740,8 +1740,9 @@
 return Err;
 
   // Add base classes.
-  if (auto *ToCXX = dyn_cast(To)) {
-auto *FromCXX = cast(From);
+  auto *ToCXX = dyn_cast(To);
+  auto *FromCXX = dyn_cast(From);
+  if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
 
 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
Index: cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp
===
--- cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp
+++ cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp
@@ -1016,7 +1016,8 @@
 return false;
 
   // Compare the definitions of these two records. If either or both are
-  // incomplete, we assume that they are equivalent.
+  // incomplete (i.e. it is a forward decl), we assume that they are
+  // equivalent.
   D1 = D1->getDefinition();
   D2 = D2->getDefinition();
   if (!D1 || !D2)
@@ -1031,6 +1032,11 @@
 if (D1->hasExternalLexicalStorage() || D2->hasExternalLexicalStorage())
   return true;
 
+  // If one definition is currently being defined, we do not compare for
+  /

[clang-tools-extra] r347566 - [clangd] Fix compilation of IndexBenchmark

2018-11-26 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Nov 26 07:58:29 2018
New Revision: 347566

URL: http://llvm.org/viewvc/llvm-project?rev=347566&view=rev
Log:
[clangd] Fix compilation of IndexBenchmark

Modified:
clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp

Modified: clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp?rev=347566&r1=347565&r2=347566&view=diff
==
--- clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp (original)
+++ clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp Mon Nov 26 
07:58:29 2018
@@ -27,11 +27,11 @@ namespace clangd {
 namespace {
 
 std::unique_ptr buildMem() {
-  return loadIndex(IndexFilename, {}, false);
+  return loadIndex(IndexFilename, /*UseDex=*/false);
 }
 
 std::unique_ptr buildDex() {
-  return loadIndex(IndexFilename, {}, true);
+  return loadIndex(IndexFilename, /*UseDex=*/true);
 }
 
 // Reads JSON array of serialized FuzzyFindRequest's from user-provided file.


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


[PATCH] D54901: [Haiku] Support __float128 for Haiku x86 and x86_64

2018-11-26 Thread Alexander von Gluck IV via Phabricator via cfe-commits
kallisti5 created this revision.
kallisti5 added reviewers: chandlerc, joerg, compnerd, kristina, js.
kallisti5 added a project: clang.
Herald added a subscriber: cfe-commits.

A revision on https://reviews.llvm.org/D53696 from another user.


Repository:
  rC Clang

https://reviews.llvm.org/D54901

Files:
  lib/Basic/Targets/OSTargets.h
  test/CodeGenCXX/float128-declarations.cpp


Index: test/CodeGenCXX/float128-declarations.cpp
===
--- test/CodeGenCXX/float128-declarations.cpp
+++ test/CodeGenCXX/float128-declarations.cpp
@@ -16,6 +16,10 @@
 // RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
 // RUN: %clang_cc1 -emit-llvm -triple x86_64-pc-solaris2.11 -std=c++11 \
 // RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
+// RUN: %clang_cc1 -emit-llvm -triple i586-pc-haiku -std=c++11 \
+// RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
+// RUN: %clang_cc1 -emit-llvm -triple x86_64-unknown-haiku -std=c++11 \
+// RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
 //
 /*  Various contexts where type __float128 can appear. The different check
 prefixes are due to different mangling on X86 and different calling
Index: lib/Basic/Targets/OSTargets.h
===
--- lib/Basic/Targets/OSTargets.h
+++ lib/Basic/Targets/OSTargets.h
@@ -257,6 +257,9 @@
 Builder.defineMacro("__HAIKU__");
 Builder.defineMacro("__ELF__");
 DefineStd(Builder, "unix", Opts);
+if (this->HasFloat128) {
+  Builder.defineMacro("__FLOAT128__");
+}
   }
 
 public:
@@ -267,6 +270,14 @@
 this->PtrDiffType = TargetInfo::SignedLong;
 this->ProcessIDType = TargetInfo::SignedLong;
 this->TLSSupported = false;
+switch (Triple.getArch()) {
+default:
+  break;
+case llvm::Triple::x86:
+case llvm::Triple::x86_64:
+  this->HasFloat128 = true;
+  break;
+}
   }
 };
 


Index: test/CodeGenCXX/float128-declarations.cpp
===
--- test/CodeGenCXX/float128-declarations.cpp
+++ test/CodeGenCXX/float128-declarations.cpp
@@ -16,6 +16,10 @@
 // RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
 // RUN: %clang_cc1 -emit-llvm -triple x86_64-pc-solaris2.11 -std=c++11 \
 // RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
+// RUN: %clang_cc1 -emit-llvm -triple i586-pc-haiku -std=c++11 \
+// RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
+// RUN: %clang_cc1 -emit-llvm -triple x86_64-unknown-haiku -std=c++11 \
+// RUN:   %s -o - | FileCheck %s -check-prefix=CHECK-X86
 //
 /*  Various contexts where type __float128 can appear. The different check
 prefixes are due to different mangling on X86 and different calling
Index: lib/Basic/Targets/OSTargets.h
===
--- lib/Basic/Targets/OSTargets.h
+++ lib/Basic/Targets/OSTargets.h
@@ -257,6 +257,9 @@
 Builder.defineMacro("__HAIKU__");
 Builder.defineMacro("__ELF__");
 DefineStd(Builder, "unix", Opts);
+if (this->HasFloat128) {
+  Builder.defineMacro("__FLOAT128__");
+}
   }
 
 public:
@@ -267,6 +270,14 @@
 this->PtrDiffType = TargetInfo::SignedLong;
 this->ProcessIDType = TargetInfo::SignedLong;
 this->TLSSupported = false;
+switch (Triple.getArch()) {
+default:
+  break;
+case llvm::Triple::x86:
+case llvm::Triple::x86_64:
+  this->HasFloat128 = true;
+  break;
+}
   }
 };
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r347567 - [clangd] Enable auto-index behind a flag.

2018-11-26 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Mon Nov 26 08:00:11 2018
New Revision: 347567

URL: http://llvm.org/viewvc/llvm-project?rev=347567&view=rev
Log:
[clangd] Enable auto-index behind a flag.

Summary:
Ownership and configuration:
The auto-index (background index) is maintained by ClangdServer, like Dynamic.
(This means ClangdServer will be able to enqueue preamble indexing in future).
For now it's enabled by a simple boolean flag in ClangdServer::Options, but
we probably want to eventually allow injecting the storage strategy.

New 'sync' command:
In order to meaningfully test the integration (not just unit-test components)
we need a way for tests to ensure the asynchronous index reads/writes occur
before a certain point.
Because these tests and assertions are few, I think exposing an explicit "sync"
command for use in tests is simpler than allowing threading to be completely
disabled in the background index (as we do for TUScheduler).

Bugs:
I fixed a couple of trivial bugs I found while testing, but there's one I can't.
JSONCompilationDatabase::getAllFiles() may return relative paths, and currently
we trigger an assertion that assumes they are absolute.
There's no efficient way to resolve them (you have to retrieve the corresponding
command and then resolve against its directory property). In general I think
this behavior is broken and we should fix it in JSONCompilationDatabase and
require CompilationDatabase::getAllFiles() to be absolute.

Reviewers: kadircet

Subscribers: ilya-biryukov, ioeric, MaskRay, jkorous, arphaman, cfe-commits

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

Added:
clang-tools-extra/trunk/test/clangd/Inputs/background-index/

clang-tools-extra/trunk/test/clangd/Inputs/background-index/compile_commands.json

clang-tools-extra/trunk/test/clangd/Inputs/background-index/definition.jsonrpc
clang-tools-extra/trunk/test/clangd/Inputs/background-index/foo.cpp
clang-tools-extra/trunk/test/clangd/Inputs/background-index/foo.h
clang-tools-extra/trunk/test/clangd/background-index.test
Modified:
clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
clang-tools-extra/trunk/clangd/ClangdLSPServer.h
clang-tools-extra/trunk/clangd/ClangdServer.cpp
clang-tools-extra/trunk/clangd/ClangdServer.h
clang-tools-extra/trunk/clangd/GlobalCompilationDatabase.cpp
clang-tools-extra/trunk/clangd/index/Background.cpp
clang-tools-extra/trunk/clangd/index/Background.h
clang-tools-extra/trunk/clangd/index/BackgroundIndexStorage.cpp
clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp
clang-tools-extra/trunk/unittests/clangd/BackgroundIndexTests.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp?rev=347567&r1=347566&r2=347567&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp Mon Nov 26 08:00:11 2018
@@ -337,6 +337,17 @@ void ClangdLSPServer::onShutdown(const S
   Reply(nullptr);
 }
 
+// sync is a clangd extension: it blocks until all background work completes.
+// It blocks the calling thread, so no messages are processed until it returns!
+void ClangdLSPServer::onSync(const NoParams &Params,
+ Callback Reply) {
+  if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
+Reply(nullptr);
+  else
+Reply(createStringError(llvm::inconvertibleErrorCode(),
+"Not idle after a minute"));
+}
+
 void ClangdLSPServer::onDocumentDidOpen(
 const DidOpenTextDocumentParams &Params) {
   PathRef File = Params.textDocument.uri.file();
@@ -701,6 +712,7 @@ ClangdLSPServer::ClangdLSPServer(class T
   // clang-format off
   MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
   MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
+  MsgHandler->bind("sync", &ClangdLSPServer::onSync);
   MsgHandler->bind("textDocument/rangeFormatting", 
&ClangdLSPServer::onDocumentRangeFormatting);
   MsgHandler->bind("textDocument/onTypeFormatting", 
&ClangdLSPServer::onDocumentOnTypeFormatting);
   MsgHandler->bind("textDocument/formatting", 
&ClangdLSPServer::onDocumentFormatting);

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.h?rev=347567&r1=347566&r2=347567&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.h (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.h Mon Nov 26 08:00:11 2018
@@ -57,6 +57,7 @@ private:
   // Calls have signature void(const Params&, Callback).
   void onInitialize(const InitializeParams &, Callback);
   void onShutdown(const ShutdownParams &, Callback);
+  void onSync(const NoParams &, Callback);
   void onDocumentD

  1   2   >