[PATCH] D60821: [clangd] Emit better error messages when rename fails.

2019-04-18 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/ClangdServer.cpp:57
 public:
+  RefactoringResultCollector(DiagnosticsEngine &DE) : Diags(DE) {}
   void handleError(llvm::Error Err) override {

why inject the DE here (and handle mapping errors both in the caller and here) 
rather than always doing the mapping in the caller?



Comment at: clang-tools-extra/clangd/ClangdServer.cpp:60
 assert(!Result.hasValue());
-// FIXME: figure out a way to return better message for DiagnosticError.
-// clangd uses llvm::toString to convert the Err to string, however, for
-// DiagnosticError, only "clang diagnostic" will be generated.
-Result = std::move(Err);
+if (auto Diag = DiagnosticError::take(Err))
+  Result = toStringError(*Diag, Diags);

I'm confused about this, take() seems to return Optional, 
but you're passing it as a DiagnosticError ... oh, DiagnosticError has a 
constructor from PartialDiagnosticAt.

This seems unneccesarily confusing, just pass the PartialDiagnostic?



Comment at: clang-tools-extra/clangd/ClangdServer.cpp:315
+  auto Error = Rename.takeError();
+  if (auto Diag = DiagnosticError::take(Error)) {
+llvm::cantFail(std::move(Error));

can we avoid this duplication by giving a helper function more responsibilities?
e.g. `llvm::Error expandDiagnostics(llvm::Error, DiagnosticsEngine&)`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60821



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


[PATCH] D60719: Demonstrate how to fix freestanding for memcpy

2019-04-18 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet added a comment.

In D60719#1470632 , @t.p.northover 
wrote:

> > IIUC freestanding environment should not rely on memcpy being present so my 
> > take on it was that by "fixing" freestanding I could have my cake and eat 
> > it too.
>
> The formal situation is that freestanding implementations are only required 
> to provide language support stuff like `va_list`. They're allowed to give 
> more of the standard library if they want though, as implementation defined 
> behaviour.
>
> In practice, everyone I know provides the basic `string.h` functions and the 
> compiler is pretty explicit about relying on them being present for 
> correctness. They're part of the surrounding environment a user is expected 
> to supply (much like the various exception handling callbacks if you want C++ 
> exceptions, but always required).
>
> For the people actually using freestanding I think they're mostly considered 
> important enough that they're implemented in assembly anyway so this isn't 
> really a burden, but...


Ack. "Fixing" freestanding is not the way to go then : )

>> Ultimately I'm interested in implementing libc's mem function in C++. Let's 
>> take memcpy for instance
> 
> Ah, that is an entirely different problem from what I thought you were trying 
> to do. In that case I'm all in favour of some solution, but would start 
> thinking along the lines of `-fno-builtin-memcpy` options (it's possible that 
> already does what you want, but can't get LLVM to form a `memcpy` from quick 
> tests to check).

Thx for taking the time to suggest possible solution, I really appreciate it.

I already tried `-fno-builtin-memcpy`. The semantic of this flag is pretty 
counter intuitive and I'll explain why it doesn't fit my needs.
LLVM is allowed to replace a piece of code that looks like a `memcpy` with an 
IR intrinsic that implements the same semantic. You can see this by inspecting 
the IR here: https://godbolt.org/z/0y1Yqh.
Now if you use `-fno-builtin-memcpy` you're preventing the compiler from 
understanding that this is a memory copy. Look at the IR here: 
https://godbolt.org/z/lnCIIh.
The vectorizer kicks in in this case and the generated code is quite good but 
sometimes the generated code is pretty bad: https://godbolt.org/z/mHpAYe.

Last but not least `-fno-builtin-memcpy`prevents the compiler from 
understanding code constructs as memcpy but does not prevent the compiler from 
generating calls to `memcpy`:

- Using `__builtin_memcpy` still lowers to `@llvm.memcpy` IR intrinsics: 
https://godbolt.org/z/O0sjIl
- Passing big structs by value will lowers to `@llvm.memcpy` IR intrinsics: 
https://godbolt.org/z/4BUDc0

Another solution is needed for my use case, either a new C++ intrinsics 
`__builtin_inline_memcpy` or an attribute that disables generated libc calls, 
compiler could either inline or fail with an error.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60719



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


[PATCH] D60828: [ARM] Fix armv8 features tree and add fp16fml

2019-04-18 Thread Diogo N. Sampaio via Phabricator via cfe-commits
dnsampaio marked 5 inline comments as done.
dnsampaio added inline comments.



Comment at: lib/Basic/Targets/ARM.cpp:443
   HasLegalHalfType = true;
+  HW_FP |= HW_FP_SP | HW_FP_DP | HW_FP_HP;
+  FPU |= VFP4FPU;

ostannard wrote:
> Is it always correct to set HW_FP_DP here, now that MVE can have full fp16 
> without double-precision? I'll add Simon since he's working on that.
If it is V8 and does not have double-precision, isn't that going to use the 
argument `+fp-only-sp` ? That will disable WH_FP_DP  using lines 436 and 456.
```
else if (Feature == "+fp-only-sp") {
HW_FP_remove |= HW_FP_DP;
```
```
HW_FP &= ~HW_FP_remove;
```




Comment at: lib/Basic/Targets/ARM.cpp:444
+  HW_FP |= HW_FP_SP | HW_FP_DP | HW_FP_HP;
+  FPU |= VFP4FPU;
 } else if (Feature == "+dotprod") {

ostannard wrote:
> Should this be FPARMV8, since fullfp16 doesn't apply to earlier 
> architectures? Maybe MVE  complicates this even further?
Correct, it should also add FeatureFPARMv8.
See that this is a accumulative flag, as FPARMv8 implies VFP4FPU, both should 
be set.
 Actually, according the backend, `FeatureFPARMv8 -> FeatureVFP4 -> FeatureVFP3 
-> FeatureVFP2`. From my tests we already set FeatureVFP3, but not FeatureVFP4



Comment at: lib/Basic/Targets/ARM.cpp:446
 } else if (Feature == "+dotprod") {
+  FPU |= NeonFPU;
+  HW_FP |= HW_FP_SP | HW_FP_DP;

ostannard wrote:
> Should this also add FPARMV8?
As well, yes.



Comment at: lib/Basic/Targets/ARM.cpp:452
+  HasLegalHalfType = true;
+  FPU |= VFP4FPU;
+  HW_FP |= HW_FP_SP | HW_FP_DP | HW_FP_HP;

ostannard wrote:
> Again, should this be FPARMV8?
True.



Comment at: test/CodeGen/arm_neon_intrinsics.c:8
+// RUN: %clang -O1 -target armv8a-linux-eabi -march=armv8a+fp16fml\
+// RUN:  -S -emit-llvm -o - %s | FileCheck %s.v8
+

ostannard wrote:
> Does the generate code differ enough to have a second copy of it? Actually, I 
> assume the problem here is that we are not setting the correct preprocessor 
> macros? in which case, it would be better to test them directly, than by 
> re-running this 21kloc test.
That indeed seems a better solution.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60828



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


[PATCH] D60857: [clang-tidy] Address post-commit comments

2019-04-18 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: alexfh.
Herald added a subscriber: xazax.hun.
Herald added a project: clang.
hokein updated this revision to Diff 195692.
hokein added a comment.

Cleanup.


Also add a test to verify clang-tidy only apply the first alternative
fix.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D60857

Files:
  clang-tools-extra/clang-tidy/ClangTidy.cpp
  clang-tools-extra/test/clang-tidy/alternative-fixes.cpp
  clang/include/clang/Tooling/Core/Diagnostic.h

Index: clang/include/clang/Tooling/Core/Diagnostic.h
===
--- clang/include/clang/Tooling/Core/Diagnostic.h
+++ clang/include/clang/Tooling/Core/Diagnostic.h
@@ -93,8 +93,8 @@
   std::vector Diagnostics;
 };
 
-// Get the first fix to apply for this diagnostic.
-// Return nullptr if no fixes attached to the diagnostic.
+/// Get the first fix to apply for this diagnostic.
+/// Returns nullptr if no fixes are attached to the diagnostic.
 const llvm::StringMap *selectFirstFix(const Diagnostic& D);
 
 } // end namespace tooling
Index: clang-tools-extra/test/clang-tidy/alternative-fixes.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/alternative-fixes.cpp
@@ -0,0 +1,15 @@
+// RUN: clang-tidy -checks='-*,llvm-namespace-comment,clang-diagnostic-*' %s -- \
+// RUN: | FileCheck -implicit-check-not='{{warning|error|note}}:' %s
+
+// Verify clang-tidy only applies the first alternative fix.
+// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
+// RUN: clang-tidy -checks='-*,llvm-namespace-comment,clang-diagnostic-*' -fix %t.cpp --
+// RUN: FileCheck -input-file=%t.cpp %s -check-prefix=CHECK-FIX
+void foo(int a) {
+  if (a = 1) {
+  // CHECK: [[@LINE-1]]:9: warning: using the result of an assignment as a condition without parentheses [clang-diagnostic-parentheses]
+  // CHECK: [[@LINE-2]]:9: note: place parentheses around the assignment to silence this warning
+  // CHECK: [[@LINE-3]]:9: note: use '==' to turn this assignment into an equality comparison
+  // CHECK-FIX: if ((a = 1)) {
+  }
+}
Index: clang-tools-extra/clang-tidy/ClangTidy.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidy.cpp
+++ clang-tools-extra/clang-tidy/ClangTidy.cpp
@@ -133,41 +133,40 @@
   for (const auto &Repl : FileAndReplacements.second) {
 ++TotalFixes;
 bool CanBeApplied = false;
-if (Repl.isApplicable()) {
-  SourceLocation FixLoc;
-  SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
-  Files.makeAbsolutePath(FixAbsoluteFilePath);
-  tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
- Repl.getLength(),
- Repl.getReplacementText());
-  Replacements &Replacements = FileReplacements[R.getFilePath()];
-  llvm::Error Err = Replacements.add(R);
-  if (Err) {
-// FIXME: Implement better conflict handling.
-llvm::errs() << "Trying to resolve conflict: "
- << llvm::toString(std::move(Err)) << "\n";
-unsigned NewOffset =
-Replacements.getShiftedCodePosition(R.getOffset());
-unsigned NewLength = Replacements.getShiftedCodePosition(
- R.getOffset() + R.getLength()) -
- NewOffset;
-if (NewLength == R.getLength()) {
-  R = Replacement(R.getFilePath(), NewOffset, NewLength,
-  R.getReplacementText());
-  Replacements = Replacements.merge(tooling::Replacements(R));
-  CanBeApplied = true;
-  ++AppliedFixes;
-} else {
-  llvm::errs()
-  << "Can't resolve conflict, skipping the replacement.\n";
-}
-  } else {
+if (!Repl.isApplicable())
+  continue;
+SourceLocation FixLoc;
+SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
+Files.makeAbsolutePath(FixAbsoluteFilePath);
+tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
+   Repl.getLength(), Repl.getReplacementText());
+Replacements &Replacements = FileReplacements[R.getFilePath()];
+llvm::Error Err = Replacements.add(R);
+if (Err) {
+  // FIXME: Implement better conflict handling.
+  llvm::errs() << "Trying to resolve conflict: "
+   << llvm::toString(std::move(Err)) << "\n";
+  unsigned NewOffset =
+  Replacements.getShiftedCodePosition(R.getOffset());
+  unsigned NewLengt

[PATCH] D60857: [clang-tidy] Address post-commit comments

2019-04-18 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 195692.
hokein added a comment.

Cleanup.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60857

Files:
  clang-tools-extra/clang-tidy/ClangTidy.cpp
  clang-tools-extra/test/clang-tidy/alternative-fixes.cpp
  clang/include/clang/Tooling/Core/Diagnostic.h

Index: clang/include/clang/Tooling/Core/Diagnostic.h
===
--- clang/include/clang/Tooling/Core/Diagnostic.h
+++ clang/include/clang/Tooling/Core/Diagnostic.h
@@ -93,8 +93,8 @@
   std::vector Diagnostics;
 };
 
-// Get the first fix to apply for this diagnostic.
-// Return nullptr if no fixes attached to the diagnostic.
+/// Get the first fix to apply for this diagnostic.
+/// Returns nullptr if no fixes are attached to the diagnostic.
 const llvm::StringMap *selectFirstFix(const Diagnostic& D);
 
 } // end namespace tooling
Index: clang-tools-extra/test/clang-tidy/alternative-fixes.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/alternative-fixes.cpp
@@ -0,0 +1,15 @@
+// RUN: clang-tidy -checks='-*,llvm-namespace-comment,clang-diagnostic-*' %s -- \
+// RUN: | FileCheck -implicit-check-not='{{warning|error|note}}:' %s
+
+// Verify clang-tidy only applies the first alternative fix.
+// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
+// RUN: clang-tidy -checks='-*,llvm-namespace-comment,clang-diagnostic-*' -fix %t.cpp --
+// RUN: FileCheck -input-file=%t.cpp %s -check-prefix=CHECK-FIX
+void foo(int a) {
+  if (a = 1) {
+  // CHECK: [[@LINE-1]]:9: warning: using the result of an assignment as a condition without parentheses [clang-diagnostic-parentheses]
+  // CHECK: [[@LINE-2]]:9: note: place parentheses around the assignment to silence this warning
+  // CHECK: [[@LINE-3]]:9: note: use '==' to turn this assignment into an equality comparison
+  // CHECK-FIX: if ((a = 1)) {
+  }
+}
Index: clang-tools-extra/clang-tidy/ClangTidy.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidy.cpp
+++ clang-tools-extra/clang-tidy/ClangTidy.cpp
@@ -133,41 +133,40 @@
   for (const auto &Repl : FileAndReplacements.second) {
 ++TotalFixes;
 bool CanBeApplied = false;
-if (Repl.isApplicable()) {
-  SourceLocation FixLoc;
-  SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
-  Files.makeAbsolutePath(FixAbsoluteFilePath);
-  tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
- Repl.getLength(),
- Repl.getReplacementText());
-  Replacements &Replacements = FileReplacements[R.getFilePath()];
-  llvm::Error Err = Replacements.add(R);
-  if (Err) {
-// FIXME: Implement better conflict handling.
-llvm::errs() << "Trying to resolve conflict: "
- << llvm::toString(std::move(Err)) << "\n";
-unsigned NewOffset =
-Replacements.getShiftedCodePosition(R.getOffset());
-unsigned NewLength = Replacements.getShiftedCodePosition(
- R.getOffset() + R.getLength()) -
- NewOffset;
-if (NewLength == R.getLength()) {
-  R = Replacement(R.getFilePath(), NewOffset, NewLength,
-  R.getReplacementText());
-  Replacements = Replacements.merge(tooling::Replacements(R));
-  CanBeApplied = true;
-  ++AppliedFixes;
-} else {
-  llvm::errs()
-  << "Can't resolve conflict, skipping the replacement.\n";
-}
-  } else {
+if (!Repl.isApplicable())
+  continue;
+SourceLocation FixLoc;
+SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
+Files.makeAbsolutePath(FixAbsoluteFilePath);
+tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
+   Repl.getLength(), Repl.getReplacementText());
+Replacements &Replacements = FileReplacements[R.getFilePath()];
+llvm::Error Err = Replacements.add(R);
+if (Err) {
+  // FIXME: Implement better conflict handling.
+  llvm::errs() << "Trying to resolve conflict: "
+   << llvm::toString(std::move(Err)) << "\n";
+  unsigned NewOffset =
+  Replacements.getShiftedCodePosition(R.getOffset());
+  unsigned NewLength = Replacements.getShiftedCodePosition(
+   R.getOffset() + R.getLength()) -
+

[PATCH] D60267: [clangd] Support relatedInformation in diagnostics.

2019-04-18 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 9 inline comments as done.
sammccall added inline comments.



Comment at: clangd/Diagnostics.cpp:280
+  Main.relatedInformation->push_back(std::move(RelInfo));
+}
   }

ilya-biryukov wrote:
> NIT: maybe call `OutFn` and return here to avoid checking for 
> `EmitRelatedLocations` again?
> Would arguably make the code simpler, although would require another call to 
> `OutFn(Main)` outside the if branch.
Yeah, I don't really see this as an improvement - it reduces the nesting, but 
makes the relation of conditions to code more confusing, I think.



Comment at: unittests/clangd/DiagnosticsTests.cpp:259
+#ifdef _WIN32
+  "c:\\path\\to\\foo\\bar\\main.cpp",
+#else

ilya-biryukov wrote:
> maybe use `testPath()` here to avoid PP directives?
Done - this requires changing the actual paths but it doesn't seem to matter.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D60267



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


[PATCH] D60827: [rename] Deduplicate symbol occurrences

2019-04-18 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.

Thanks




Comment at: clang-tools-extra/unittests/clangd/ClangdTests.cpp:1160
 
+TEST_F(ClangdVFSTest, NoDuplicatedTextEditsOnRename) {
+  MockFSProvider FS;

maybe put the test under clang/unittests/Rename?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60827



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


[PATCH] D60267: [clangd] Support relatedInformation in diagnostics.

2019-04-18 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 195694.
sammccall marked an inline comment as done.
sammccall added a comment.

Rebase and address comments.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D60267

Files:
  clangd/Diagnostics.cpp
  clangd/Diagnostics.h
  clangd/Protocol.cpp
  clangd/Protocol.h
  unittests/clangd/DiagnosticsTests.cpp

Index: unittests/clangd/DiagnosticsTests.cpp
===
--- unittests/clangd/DiagnosticsTests.cpp
+++ unittests/clangd/DiagnosticsTests.cpp
@@ -8,10 +8,14 @@
 
 #include "Annotations.h"
 #include "ClangdUnit.h"
+#include "Diagnostics.h"
+#include "Protocol.h"
 #include "SourceCode.h"
 #include "TestIndex.h"
+#include "TestFS.h"
 #include "TestTU.h"
 #include "index/MemIndex.h"
+#include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticSema.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include "gmock/gmock.h"
@@ -55,8 +59,12 @@
 
 MATCHER_P(EqualToLSPDiag, LSPDiag,
   "LSP diagnostic " + llvm::to_string(LSPDiag)) {
-  return std::tie(arg.range, arg.severity, arg.message) ==
- std::tie(LSPDiag.range, LSPDiag.severity, LSPDiag.message);
+  if (toJSON(arg) != toJSON(LSPDiag)) {
+*result_listener << llvm::formatv("expected:\n{0:2}\ngot\n{1:2}",
+  toJSON(LSPDiag), toJSON(arg)).str();
+return false;
+  }
+  return true;
 }
 
 MATCHER_P(DiagSource, S, "") { return arg.Source == S; }
@@ -248,6 +256,11 @@
 }
 
 TEST(DiagnosticsTest, ToLSP) {
+  URIForFile MainFile =
+  URIForFile::canonicalize(testPath("foo/bar/main.cpp"), "");
+  URIForFile HeaderFile =
+  URIForFile::canonicalize(testPath("foo/bar/header.h"), "");
+
   clangd::Diag D;
   D.ID = clang::diag::err_enum_class_reference;
   D.Name = "enum_class_reference";
@@ -257,6 +270,7 @@
   D.InsideMainFile = true;
   D.Severity = DiagnosticsEngine::Error;
   D.File = "foo/bar/main.cpp";
+  D.AbsFile = MainFile.file();
 
   clangd::Note NoteInMain;
   NoteInMain.Message = "declared somewhere in the main file";
@@ -264,6 +278,8 @@
   NoteInMain.Severity = DiagnosticsEngine::Remark;
   NoteInMain.File = "../foo/bar/main.cpp";
   NoteInMain.InsideMainFile = true;
+  NoteInMain.AbsFile = MainFile.file();
+
   D.Notes.push_back(NoteInMain);
 
   clangd::Note NoteInHeader;
@@ -272,44 +288,37 @@
   NoteInHeader.Severity = DiagnosticsEngine::Note;
   NoteInHeader.File = "../foo/baz/header.h";
   NoteInHeader.InsideMainFile = false;
+  NoteInHeader.AbsFile = HeaderFile.file();
   D.Notes.push_back(NoteInHeader);
 
   clangd::Fix F;
   F.Message = "do something";
   D.Fixes.push_back(F);
 
-  auto MatchingLSP = [](const DiagBase &D, StringRef Message) {
-clangd::Diagnostic Res;
-Res.range = D.Range;
-Res.severity = getSeverity(D.Severity);
-Res.message = Message;
-return Res;
-  };
-
   // Diagnostics should turn into these:
-  clangd::Diagnostic MainLSP =
-  MatchingLSP(D, R"(Something terrible happened (fix available)
+  clangd::Diagnostic MainLSP;
+  MainLSP.range = D.Range;
+  MainLSP.severity = getSeverity(DiagnosticsEngine::Error);
+  MainLSP.code = "enum_class_reference";
+  MainLSP.source = "clang";
+  MainLSP.message = R"(Something terrible happened (fix available)
 
 main.cpp:6:7: remark: declared somewhere in the main file
 
 ../foo/baz/header.h:10:11:
-note: declared somewhere in the header file)");
+note: declared somewhere in the header file)";
 
-  clangd::Diagnostic NoteInMainLSP =
-  MatchingLSP(NoteInMain, R"(Declared somewhere in the main file
+  clangd::Diagnostic NoteInMainLSP;
+  NoteInMainLSP.range = NoteInMain.Range;
+  NoteInMainLSP.severity = getSeverity(DiagnosticsEngine::Remark);
+  NoteInMainLSP.message = R"(Declared somewhere in the main file
 
-main.cpp:2:3: error: something terrible happened)");
+main.cpp:2:3: error: something terrible happened)";
 
-  // Transform dianostics and check the results.
+  ClangdDiagnosticOptions Opts;
+  // Transform diagnostics and check the results.
   std::vector>> LSPDiags;
-  toLSPDiags(D,
-#ifdef _WIN32
- URIForFile::canonicalize("c:\\path\\to\\foo\\bar\\main.cpp",
-  /*TUPath=*/""),
-#else
-  URIForFile::canonicalize("/path/to/foo/bar/main.cpp", /*TUPath=*/""),
-#endif
- ClangdDiagnosticOptions(),
+  toLSPDiags(D, MainFile, Opts,
  [&](clangd::Diagnostic LSPDiag, ArrayRef Fixes) {
LSPDiags.push_back(
{std::move(LSPDiag),
@@ -324,6 +333,30 @@
   EXPECT_EQ(LSPDiags[0].first.source, "clang");
   EXPECT_EQ(LSPDiags[1].first.code, "");
   EXPECT_EQ(LSPDiags[1].first.source, "");
+
+  // Same thing, but don't flatten notes into the main list.
+  LSPDiags.clear();
+  Opts.EmitRelatedLocations = true;
+  toLSPDiags(D, MainFile, Opts,
+ [&](clangd::Diagnostic LSPDiag, ArrayRef Fixes) {
+   LSPDiags.pus

[PATCH] D60828: [ARM] Fix armv8 features tree and add fp16fml

2019-04-18 Thread Diogo N. Sampaio via Phabricator via cfe-commits
dnsampaio planned changes to this revision.
dnsampaio added a comment.

Waiting for the outcome of D60691 .


Repository:
  rC Clang

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

https://reviews.llvm.org/D60828



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


[PATCH] D60821: [clangd] Emit better error messages when rename fails.

2019-04-18 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 195701.
hokein marked 4 inline comments as done.
hokein added a comment.

Address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60821

Files:
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/test/clangd/rename.test


Index: clang-tools-extra/test/clangd/rename.test
===
--- clang-tools-extra/test/clangd/rename.test
+++ clang-tools-extra/test/clangd/rename.test
@@ -29,7 +29,7 @@
 
{"jsonrpc":"2.0","id":2,"method":"textDocument/rename","params":{"textDocument":{"uri":"test:///foo.cpp"},"position":{"line":0,"character":2},"newName":"bar"}}
 #  CHECK:  "error": {
 # CHECK-NEXT:"code": -32001,
-# CHECK-NEXT:"message": "clang diagnostic"
+# CHECK-NEXT:"message": "there is no symbol at the given location"
 # CHECK-NEXT:  },
 # CHECK-NEXT:  "id": 2,
 # CHECK-NEXT:  "jsonrpc": "2.0"
Index: clang-tools-extra/clangd/ClangdServer.cpp
===
--- clang-tools-extra/clangd/ClangdServer.cpp
+++ clang-tools-extra/clangd/ClangdServer.cpp
@@ -44,15 +44,26 @@
 namespace clangd {
 namespace {
 
+// Expand a DiagnosticError to make it print-friendly (print the detailed
+// message, rather than "clang diagnostic").
+llvm::Error expandDiagnostics(llvm::Error Err, DiagnosticsEngine &DE) {
+  if (auto Diag = DiagnosticError::take(Err)) {
+llvm::cantFail(std::move(Err));
+SmallVector DiagMessage;
+Diag->second.EmitToString(DE, DiagMessage);
+return llvm::make_error(DiagMessage,
+   llvm::inconvertibleErrorCode());
+  }
+  return Err;
+}
+
 class RefactoringResultCollector final
 : public tooling::RefactoringResultConsumer {
 public:
+  RefactoringResultCollector(DiagnosticsEngine &DE) : Diags(DE) {}
   void handleError(llvm::Error Err) override {
 assert(!Result.hasValue());
-// FIXME: figure out a way to return better message for DiagnosticError.
-// clangd uses llvm::toString to convert the Err to string, however, for
-// DiagnosticError, only "clang diagnostic" will be generated.
-Result = std::move(Err);
+Result = expandDiagnostics(std::move(Err), Diags);
   }
 
   // Using the handle(SymbolOccurrences) from parent class.
@@ -63,6 +74,7 @@
 Result = std::move(SourceReplacements);
   }
 
+  DiagnosticsEngine &Diags;
   llvm::Optional> Result;
 };
 
@@ -291,7 +303,8 @@
   return CB(InpAST.takeError());
 auto &AST = InpAST->AST;
 
-RefactoringResultCollector ResultCollector;
+RefactoringResultCollector ResultCollector(
+AST.getASTContext().getDiagnostics());
 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
 SourceLocation SourceLocationBeg =
 clangd::getBeginningOfIdentifier(AST, Pos, SourceMgr.getMainFileID());
@@ -301,7 +314,8 @@
 auto Rename = clang::tooling::RenameOccurrences::initiate(
 Context, SourceRange(SourceLocationBeg), NewName);
 if (!Rename)
-  return CB(Rename.takeError());
+  return CB(expandDiagnostics(Rename.takeError(),
+  AST.getASTContext().getDiagnostics()));
 
 Rename->invoke(ResultCollector, Context);
 


Index: clang-tools-extra/test/clangd/rename.test
===
--- clang-tools-extra/test/clangd/rename.test
+++ clang-tools-extra/test/clangd/rename.test
@@ -29,7 +29,7 @@
 {"jsonrpc":"2.0","id":2,"method":"textDocument/rename","params":{"textDocument":{"uri":"test:///foo.cpp"},"position":{"line":0,"character":2},"newName":"bar"}}
 #  CHECK:  "error": {
 # CHECK-NEXT:"code": -32001,
-# CHECK-NEXT:"message": "clang diagnostic"
+# CHECK-NEXT:"message": "there is no symbol at the given location"
 # CHECK-NEXT:  },
 # CHECK-NEXT:  "id": 2,
 # CHECK-NEXT:  "jsonrpc": "2.0"
Index: clang-tools-extra/clangd/ClangdServer.cpp
===
--- clang-tools-extra/clangd/ClangdServer.cpp
+++ clang-tools-extra/clangd/ClangdServer.cpp
@@ -44,15 +44,26 @@
 namespace clangd {
 namespace {
 
+// Expand a DiagnosticError to make it print-friendly (print the detailed
+// message, rather than "clang diagnostic").
+llvm::Error expandDiagnostics(llvm::Error Err, DiagnosticsEngine &DE) {
+  if (auto Diag = DiagnosticError::take(Err)) {
+llvm::cantFail(std::move(Err));
+SmallVector DiagMessage;
+Diag->second.EmitToString(DE, DiagMessage);
+return llvm::make_error(DiagMessage,
+   llvm::inconvertibleErrorCode());
+  }
+  return Err;
+}
+
 class RefactoringResultCollector final
 : public tooling::RefactoringResultConsumer {
 public:
+  RefactoringResultCollector(DiagnosticsEngine &DE) : Diags(DE) {}
   void handleError(llvm::Error Err) override {
 a

[PATCH] D60821: [clangd] Emit better error messages when rename fails.

2019-04-18 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clangd/ClangdServer.cpp:57
 public:
+  RefactoringResultCollector(DiagnosticsEngine &DE) : Diags(DE) {}
   void handleError(llvm::Error Err) override {

sammccall wrote:
> why inject the DE here (and handle mapping errors both in the caller and 
> here) rather than always doing the mapping in the caller?
We don't have control of the Err caller for this class (the Error is passed via 
the `handleError` interface)...so we need the DE in this class to do the 
expanding.



Comment at: clang-tools-extra/clangd/ClangdServer.cpp:315
+  auto Error = Rename.takeError();
+  if (auto Diag = DiagnosticError::take(Error)) {
+llvm::cantFail(std::move(Error));

sammccall wrote:
> can we avoid this duplication by giving a helper function more 
> responsibilities?
> e.g. `llvm::Error expandDiagnostics(llvm::Error, DiagnosticsEngine&)`?
SG!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60821



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


r358654 - [CUDA][Windows] Restrict long double device functions declarations to Windows

2019-04-18 Thread Evgeny Mankov via cfe-commits
Author: emankov
Date: Thu Apr 18 03:08:55 2019
New Revision: 358654

URL: http://llvm.org/viewvc/llvm-project?rev=358654&view=rev
Log:
[CUDA][Windows] Restrict long double device functions declarations to Windows

As agreed in D60220, make long double declarations unobservable on non-windows 
platforms.

[Testing]
{Windows 10, Ubuntu 16.04.5}/{Visual C++ 2017 15.9.11 & 2019 16.0.1, gcc+ 
5.4.0}/CUDA {8.0, 9.0, 9.1, 9.2, 10.0, 10.1}

Reviewed by: Artem Belevich

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

Modified:
cfe/trunk/lib/Headers/__clang_cuda_cmath.h
cfe/trunk/lib/Headers/__clang_cuda_device_functions.h
cfe/trunk/lib/Headers/__clang_cuda_math_forward_declares.h

Modified: cfe/trunk/lib/Headers/__clang_cuda_cmath.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Headers/__clang_cuda_cmath.h?rev=358654&r1=358653&r2=358654&view=diff
==
--- cfe/trunk/lib/Headers/__clang_cuda_cmath.h (original)
+++ cfe/trunk/lib/Headers/__clang_cuda_cmath.h Thu Apr 18 03:08:55 2019
@@ -64,16 +64,13 @@ __DEVICE__ float frexp(float __arg, int
 #ifndef _MSC_VER
 __DEVICE__ bool isinf(float __x) { return ::__isinff(__x); }
 __DEVICE__ bool isinf(double __x) { return ::__isinf(__x); }
-__DEVICE__ bool isinf(long double __x) { return ::__isinfl(__x); }
 __DEVICE__ bool isfinite(float __x) { return ::__finitef(__x); }
 // For inscrutable reasons, __finite(), the double-precision version of
 // __finitef, does not exist when compiling for MacOS.  __isfinited is 
available
 // everywhere and is just as good.
 __DEVICE__ bool isfinite(double __x) { return ::__isfinited(__x); }
-__DEVICE__ bool isfinite(long double __x) { return ::__finitel(__x); }
 __DEVICE__ bool isnan(float __x) { return ::__isnanf(__x); }
 __DEVICE__ bool isnan(double __x) { return ::__isnan(__x); }
-__DEVICE__ bool isnan(long double __x) { return ::__isnanl(__x); }
 #endif
 
 __DEVICE__ bool isgreater(float __x, float __y) {

Modified: cfe/trunk/lib/Headers/__clang_cuda_device_functions.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Headers/__clang_cuda_device_functions.h?rev=358654&r1=358653&r2=358654&view=diff
==
--- cfe/trunk/lib/Headers/__clang_cuda_device_functions.h (original)
+++ cfe/trunk/lib/Headers/__clang_cuda_device_functions.h Thu Apr 18 03:08:55 
2019
@@ -223,7 +223,9 @@ __DEVICE__ int __ffs(int __a) { return _
 __DEVICE__ int __ffsll(long long __a) { return __nv_ffsll(__a); }
 __DEVICE__ int __finite(double __a) { return __nv_isfinited(__a); }
 __DEVICE__ int __finitef(float __a) { return __nv_finitef(__a); }
+#ifdef _MSC_VER
 __DEVICE__ int __finitel(long double __a);
+#endif
 __DEVICE__ int __float2int_rd(float __a) { return __nv_float2int_rd(__a); }
 __DEVICE__ int __float2int_rn(float __a) { return __nv_float2int_rn(__a); }
 __DEVICE__ int __float2int_ru(float __a) { return __nv_float2int_ru(__a); }
@@ -432,10 +434,14 @@ __DEVICE__ float __int_as_float(int __a)
 __DEVICE__ int __isfinited(double __a) { return __nv_isfinited(__a); }
 __DEVICE__ int __isinf(double __a) { return __nv_isinfd(__a); }
 __DEVICE__ int __isinff(float __a) { return __nv_isinff(__a); }
+#ifdef _MSC_VER
 __DEVICE__ int __isinfl(long double __a);
+#endif
 __DEVICE__ int __isnan(double __a) { return __nv_isnand(__a); }
 __DEVICE__ int __isnanf(float __a) { return __nv_isnanf(__a); }
+#ifdef _MSC_VER
 __DEVICE__ int __isnanl(long double __a);
+#endif
 __DEVICE__ double __ll2double_rd(long long __a) {
   return __nv_ll2double_rd(__a);
 }

Modified: cfe/trunk/lib/Headers/__clang_cuda_math_forward_declares.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Headers/__clang_cuda_math_forward_declares.h?rev=358654&r1=358653&r2=358654&view=diff
==
--- cfe/trunk/lib/Headers/__clang_cuda_math_forward_declares.h (original)
+++ cfe/trunk/lib/Headers/__clang_cuda_math_forward_declares.h Thu Apr 18 
03:08:55 2019
@@ -84,14 +84,18 @@ __DEVICE__ double hypot(double, double);
 __DEVICE__ float hypot(float, float);
 __DEVICE__ int ilogb(double);
 __DEVICE__ int ilogb(float);
+#ifdef _MSC_VER
 __DEVICE__ bool isfinite(long double);
+#endif
 __DEVICE__ bool isfinite(double);
 __DEVICE__ bool isfinite(float);
 __DEVICE__ bool isgreater(double, double);
 __DEVICE__ bool isgreaterequal(double, double);
 __DEVICE__ bool isgreaterequal(float, float);
 __DEVICE__ bool isgreater(float, float);
+#ifdef _MSC_VER
 __DEVICE__ bool isinf(long double);
+#endif
 __DEVICE__ bool isinf(double);
 __DEVICE__ bool isinf(float);
 __DEVICE__ bool isless(double, double);
@@ -100,7 +104,9 @@ __DEVICE__ bool islessequal(float, float
 __DEVICE__ bool isless(float, float);
 __DEVICE__ bool islessgreater(double, double);
 __DEVICE__ bool islessgreater(float, float);
+#ifdef _MSC_VER
 __DEVICE__ bool isnan(long double);
+#endif
 __DEVICE__ bool i

[PATCH] D60818: [CUDA][Windows] restrict long double device functions declarations to Windows

2019-04-18 Thread Evgeny Mankov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC358654: [CUDA][Windows] Restrict long double device 
functions declarations to Windows (authored by emankov, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D60818?vs=195546&id=195704#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D60818

Files:
  lib/Headers/__clang_cuda_cmath.h
  lib/Headers/__clang_cuda_device_functions.h
  lib/Headers/__clang_cuda_math_forward_declares.h


Index: lib/Headers/__clang_cuda_math_forward_declares.h
===
--- lib/Headers/__clang_cuda_math_forward_declares.h
+++ lib/Headers/__clang_cuda_math_forward_declares.h
@@ -84,14 +84,18 @@
 __DEVICE__ float hypot(float, float);
 __DEVICE__ int ilogb(double);
 __DEVICE__ int ilogb(float);
+#ifdef _MSC_VER
 __DEVICE__ bool isfinite(long double);
+#endif
 __DEVICE__ bool isfinite(double);
 __DEVICE__ bool isfinite(float);
 __DEVICE__ bool isgreater(double, double);
 __DEVICE__ bool isgreaterequal(double, double);
 __DEVICE__ bool isgreaterequal(float, float);
 __DEVICE__ bool isgreater(float, float);
+#ifdef _MSC_VER
 __DEVICE__ bool isinf(long double);
+#endif
 __DEVICE__ bool isinf(double);
 __DEVICE__ bool isinf(float);
 __DEVICE__ bool isless(double, double);
@@ -100,7 +104,9 @@
 __DEVICE__ bool isless(float, float);
 __DEVICE__ bool islessgreater(double, double);
 __DEVICE__ bool islessgreater(float, float);
+#ifdef _MSC_VER
 __DEVICE__ bool isnan(long double);
+#endif
 __DEVICE__ bool isnan(double);
 __DEVICE__ bool isnan(float);
 __DEVICE__ bool isnormal(double);
Index: lib/Headers/__clang_cuda_device_functions.h
===
--- lib/Headers/__clang_cuda_device_functions.h
+++ lib/Headers/__clang_cuda_device_functions.h
@@ -223,7 +223,9 @@
 __DEVICE__ int __ffsll(long long __a) { return __nv_ffsll(__a); }
 __DEVICE__ int __finite(double __a) { return __nv_isfinited(__a); }
 __DEVICE__ int __finitef(float __a) { return __nv_finitef(__a); }
+#ifdef _MSC_VER
 __DEVICE__ int __finitel(long double __a);
+#endif
 __DEVICE__ int __float2int_rd(float __a) { return __nv_float2int_rd(__a); }
 __DEVICE__ int __float2int_rn(float __a) { return __nv_float2int_rn(__a); }
 __DEVICE__ int __float2int_ru(float __a) { return __nv_float2int_ru(__a); }
@@ -432,10 +434,14 @@
 __DEVICE__ int __isfinited(double __a) { return __nv_isfinited(__a); }
 __DEVICE__ int __isinf(double __a) { return __nv_isinfd(__a); }
 __DEVICE__ int __isinff(float __a) { return __nv_isinff(__a); }
+#ifdef _MSC_VER
 __DEVICE__ int __isinfl(long double __a);
+#endif
 __DEVICE__ int __isnan(double __a) { return __nv_isnand(__a); }
 __DEVICE__ int __isnanf(float __a) { return __nv_isnanf(__a); }
+#ifdef _MSC_VER
 __DEVICE__ int __isnanl(long double __a);
+#endif
 __DEVICE__ double __ll2double_rd(long long __a) {
   return __nv_ll2double_rd(__a);
 }
Index: lib/Headers/__clang_cuda_cmath.h
===
--- lib/Headers/__clang_cuda_cmath.h
+++ lib/Headers/__clang_cuda_cmath.h
@@ -64,16 +64,13 @@
 #ifndef _MSC_VER
 __DEVICE__ bool isinf(float __x) { return ::__isinff(__x); }
 __DEVICE__ bool isinf(double __x) { return ::__isinf(__x); }
-__DEVICE__ bool isinf(long double __x) { return ::__isinfl(__x); }
 __DEVICE__ bool isfinite(float __x) { return ::__finitef(__x); }
 // For inscrutable reasons, __finite(), the double-precision version of
 // __finitef, does not exist when compiling for MacOS.  __isfinited is 
available
 // everywhere and is just as good.
 __DEVICE__ bool isfinite(double __x) { return ::__isfinited(__x); }
-__DEVICE__ bool isfinite(long double __x) { return ::__finitel(__x); }
 __DEVICE__ bool isnan(float __x) { return ::__isnanf(__x); }
 __DEVICE__ bool isnan(double __x) { return ::__isnan(__x); }
-__DEVICE__ bool isnan(long double __x) { return ::__isnanl(__x); }
 #endif
 
 __DEVICE__ bool isgreater(float __x, float __y) {


Index: lib/Headers/__clang_cuda_math_forward_declares.h
===
--- lib/Headers/__clang_cuda_math_forward_declares.h
+++ lib/Headers/__clang_cuda_math_forward_declares.h
@@ -84,14 +84,18 @@
 __DEVICE__ float hypot(float, float);
 __DEVICE__ int ilogb(double);
 __DEVICE__ int ilogb(float);
+#ifdef _MSC_VER
 __DEVICE__ bool isfinite(long double);
+#endif
 __DEVICE__ bool isfinite(double);
 __DEVICE__ bool isfinite(float);
 __DEVICE__ bool isgreater(double, double);
 __DEVICE__ bool isgreaterequal(double, double);
 __DEVICE__ bool isgreaterequal(float, float);
 __DEVICE__ bool isgreater(float, float);
+#ifdef _MSC_VER
 __DEVICE__ bool isinf(long double);
+#endif
 __DEVICE__ bool isinf(double);
 __DEVICE__ bool isinf(float);
 __DEVICE__ bool isless(double, double);
@@ -100,7 +104,9 @@
 __DEVICE__ bool isless(float, float);
 __DEVICE__ bo

[PATCH] D60853: clang-format converts a keyword macro definition to a macro function

2019-04-18 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

LGTM




Comment at: clang/lib/Format/UnwrappedLineParser.cpp:808
 
-  if (FormatTok->Tok.getKind() != tok::identifier) {
+  if (!FormatTok->Tok.getIdentifierInfo()) {
 IncludeGuard = IG_Rejected;

Is this equivalent to saying something that means `FormatTok->isKeyWord()` ? 
for those case where the #define 


Repository:
  rC Clang

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

https://reviews.llvm.org/D60853



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


[PATCH] D60362: [clang-format] [PR39719] clang-format converting object-like macro to function-like macro

2019-04-18 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay abandoned this revision.
MyDeveloperDay added a comment.

Abandoning in favor of D60853: clang-format converts a keyword macro definition 
to a macro function 


Repository:
  rC Clang

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

https://reviews.llvm.org/D60362



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


[PATCH] D60821: [clangd] Emit better error messages when rename fails.

2019-04-18 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, thanks!

I do think it can be further simplified, but if not then land as-is.




Comment at: clang-tools-extra/clangd/ClangdServer.cpp:57
 public:
+  RefactoringResultCollector(DiagnosticsEngine &DE) : Diags(DE) {}
   void handleError(llvm::Error Err) override {

hokein wrote:
> sammccall wrote:
> > why inject the DE here (and handle mapping errors both in the caller and 
> > here) rather than always doing the mapping in the caller?
> We don't have control of the Err caller for this class (the Error is passed 
> via the `handleError` interface)...so we need the DE in this class to do the 
> expanding.
But we just store the err in Result, and then ClangdServer::rename does
```
if (!ResultCollector.Result.getValue())
  return CB(ResultCollector.Result->takeError());
```
can it wrap the takeError() in expandDiagnostics()?

it still has access to the diagnosticsengine I think


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60821



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


[PATCH] D60267: [clangd] Support relatedInformation in diagnostics.

2019-04-18 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 195707.
sammccall added a comment.

Remove accidental copy/paste in lit test.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D60267

Files:
  clangd/ClangdLSPServer.cpp
  clangd/Diagnostics.cpp
  clangd/Diagnostics.h
  clangd/Protocol.cpp
  clangd/Protocol.h
  test/clangd/diagnostics-notes.test
  unittests/clangd/DiagnosticsTests.cpp

Index: unittests/clangd/DiagnosticsTests.cpp
===
--- unittests/clangd/DiagnosticsTests.cpp
+++ unittests/clangd/DiagnosticsTests.cpp
@@ -8,10 +8,14 @@
 
 #include "Annotations.h"
 #include "ClangdUnit.h"
+#include "Diagnostics.h"
+#include "Protocol.h"
 #include "SourceCode.h"
 #include "TestIndex.h"
+#include "TestFS.h"
 #include "TestTU.h"
 #include "index/MemIndex.h"
+#include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticSema.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include "gmock/gmock.h"
@@ -55,8 +59,12 @@
 
 MATCHER_P(EqualToLSPDiag, LSPDiag,
   "LSP diagnostic " + llvm::to_string(LSPDiag)) {
-  return std::tie(arg.range, arg.severity, arg.message) ==
- std::tie(LSPDiag.range, LSPDiag.severity, LSPDiag.message);
+  if (toJSON(arg) != toJSON(LSPDiag)) {
+*result_listener << llvm::formatv("expected:\n{0:2}\ngot\n{1:2}",
+  toJSON(LSPDiag), toJSON(arg)).str();
+return false;
+  }
+  return true;
 }
 
 MATCHER_P(DiagSource, S, "") { return arg.Source == S; }
@@ -248,6 +256,11 @@
 }
 
 TEST(DiagnosticsTest, ToLSP) {
+  URIForFile MainFile =
+  URIForFile::canonicalize(testPath("foo/bar/main.cpp"), "");
+  URIForFile HeaderFile =
+  URIForFile::canonicalize(testPath("foo/bar/header.h"), "");
+
   clangd::Diag D;
   D.ID = clang::diag::err_enum_class_reference;
   D.Name = "enum_class_reference";
@@ -257,6 +270,7 @@
   D.InsideMainFile = true;
   D.Severity = DiagnosticsEngine::Error;
   D.File = "foo/bar/main.cpp";
+  D.AbsFile = MainFile.file();
 
   clangd::Note NoteInMain;
   NoteInMain.Message = "declared somewhere in the main file";
@@ -264,6 +278,8 @@
   NoteInMain.Severity = DiagnosticsEngine::Remark;
   NoteInMain.File = "../foo/bar/main.cpp";
   NoteInMain.InsideMainFile = true;
+  NoteInMain.AbsFile = MainFile.file();
+
   D.Notes.push_back(NoteInMain);
 
   clangd::Note NoteInHeader;
@@ -272,44 +288,37 @@
   NoteInHeader.Severity = DiagnosticsEngine::Note;
   NoteInHeader.File = "../foo/baz/header.h";
   NoteInHeader.InsideMainFile = false;
+  NoteInHeader.AbsFile = HeaderFile.file();
   D.Notes.push_back(NoteInHeader);
 
   clangd::Fix F;
   F.Message = "do something";
   D.Fixes.push_back(F);
 
-  auto MatchingLSP = [](const DiagBase &D, StringRef Message) {
-clangd::Diagnostic Res;
-Res.range = D.Range;
-Res.severity = getSeverity(D.Severity);
-Res.message = Message;
-return Res;
-  };
-
   // Diagnostics should turn into these:
-  clangd::Diagnostic MainLSP =
-  MatchingLSP(D, R"(Something terrible happened (fix available)
+  clangd::Diagnostic MainLSP;
+  MainLSP.range = D.Range;
+  MainLSP.severity = getSeverity(DiagnosticsEngine::Error);
+  MainLSP.code = "enum_class_reference";
+  MainLSP.source = "clang";
+  MainLSP.message = R"(Something terrible happened (fix available)
 
 main.cpp:6:7: remark: declared somewhere in the main file
 
 ../foo/baz/header.h:10:11:
-note: declared somewhere in the header file)");
+note: declared somewhere in the header file)";
 
-  clangd::Diagnostic NoteInMainLSP =
-  MatchingLSP(NoteInMain, R"(Declared somewhere in the main file
+  clangd::Diagnostic NoteInMainLSP;
+  NoteInMainLSP.range = NoteInMain.Range;
+  NoteInMainLSP.severity = getSeverity(DiagnosticsEngine::Remark);
+  NoteInMainLSP.message = R"(Declared somewhere in the main file
 
-main.cpp:2:3: error: something terrible happened)");
+main.cpp:2:3: error: something terrible happened)";
 
-  // Transform dianostics and check the results.
+  ClangdDiagnosticOptions Opts;
+  // Transform diagnostics and check the results.
   std::vector>> LSPDiags;
-  toLSPDiags(D,
-#ifdef _WIN32
- URIForFile::canonicalize("c:\\path\\to\\foo\\bar\\main.cpp",
-  /*TUPath=*/""),
-#else
-  URIForFile::canonicalize("/path/to/foo/bar/main.cpp", /*TUPath=*/""),
-#endif
- ClangdDiagnosticOptions(),
+  toLSPDiags(D, MainFile, Opts,
  [&](clangd::Diagnostic LSPDiag, ArrayRef Fixes) {
LSPDiags.push_back(
{std::move(LSPDiag),
@@ -324,6 +333,30 @@
   EXPECT_EQ(LSPDiags[0].first.source, "clang");
   EXPECT_EQ(LSPDiags[1].first.code, "");
   EXPECT_EQ(LSPDiags[1].first.source, "");
+
+  // Same thing, but don't flatten notes into the main list.
+  LSPDiags.clear();
+  Opts.EmitRelatedLocations = true;
+  toLSPDiags(D, MainFile, Opts,
+ [&](clangd::Diagnostic LSPDiag, ArrayRef Fi

[PATCH] D60267: [clangd] Support relatedInformation in diagnostics.

2019-04-18 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 195706.
sammccall added a comment.

Propagate the capability to Diagnostics, add lit test.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D60267

Files:
  clangd/ClangdLSPServer.cpp
  clangd/Diagnostics.cpp
  clangd/Diagnostics.h
  clangd/Protocol.cpp
  clangd/Protocol.h
  test/clangd/diagnostics-notes.test
  unittests/clangd/DiagnosticsTests.cpp

Index: unittests/clangd/DiagnosticsTests.cpp
===
--- unittests/clangd/DiagnosticsTests.cpp
+++ unittests/clangd/DiagnosticsTests.cpp
@@ -8,10 +8,14 @@
 
 #include "Annotations.h"
 #include "ClangdUnit.h"
+#include "Diagnostics.h"
+#include "Protocol.h"
 #include "SourceCode.h"
 #include "TestIndex.h"
+#include "TestFS.h"
 #include "TestTU.h"
 #include "index/MemIndex.h"
+#include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticSema.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include "gmock/gmock.h"
@@ -55,8 +59,12 @@
 
 MATCHER_P(EqualToLSPDiag, LSPDiag,
   "LSP diagnostic " + llvm::to_string(LSPDiag)) {
-  return std::tie(arg.range, arg.severity, arg.message) ==
- std::tie(LSPDiag.range, LSPDiag.severity, LSPDiag.message);
+  if (toJSON(arg) != toJSON(LSPDiag)) {
+*result_listener << llvm::formatv("expected:\n{0:2}\ngot\n{1:2}",
+  toJSON(LSPDiag), toJSON(arg)).str();
+return false;
+  }
+  return true;
 }
 
 MATCHER_P(DiagSource, S, "") { return arg.Source == S; }
@@ -248,6 +256,11 @@
 }
 
 TEST(DiagnosticsTest, ToLSP) {
+  URIForFile MainFile =
+  URIForFile::canonicalize(testPath("foo/bar/main.cpp"), "");
+  URIForFile HeaderFile =
+  URIForFile::canonicalize(testPath("foo/bar/header.h"), "");
+
   clangd::Diag D;
   D.ID = clang::diag::err_enum_class_reference;
   D.Name = "enum_class_reference";
@@ -257,6 +270,7 @@
   D.InsideMainFile = true;
   D.Severity = DiagnosticsEngine::Error;
   D.File = "foo/bar/main.cpp";
+  D.AbsFile = MainFile.file();
 
   clangd::Note NoteInMain;
   NoteInMain.Message = "declared somewhere in the main file";
@@ -264,6 +278,8 @@
   NoteInMain.Severity = DiagnosticsEngine::Remark;
   NoteInMain.File = "../foo/bar/main.cpp";
   NoteInMain.InsideMainFile = true;
+  NoteInMain.AbsFile = MainFile.file();
+
   D.Notes.push_back(NoteInMain);
 
   clangd::Note NoteInHeader;
@@ -272,44 +288,37 @@
   NoteInHeader.Severity = DiagnosticsEngine::Note;
   NoteInHeader.File = "../foo/baz/header.h";
   NoteInHeader.InsideMainFile = false;
+  NoteInHeader.AbsFile = HeaderFile.file();
   D.Notes.push_back(NoteInHeader);
 
   clangd::Fix F;
   F.Message = "do something";
   D.Fixes.push_back(F);
 
-  auto MatchingLSP = [](const DiagBase &D, StringRef Message) {
-clangd::Diagnostic Res;
-Res.range = D.Range;
-Res.severity = getSeverity(D.Severity);
-Res.message = Message;
-return Res;
-  };
-
   // Diagnostics should turn into these:
-  clangd::Diagnostic MainLSP =
-  MatchingLSP(D, R"(Something terrible happened (fix available)
+  clangd::Diagnostic MainLSP;
+  MainLSP.range = D.Range;
+  MainLSP.severity = getSeverity(DiagnosticsEngine::Error);
+  MainLSP.code = "enum_class_reference";
+  MainLSP.source = "clang";
+  MainLSP.message = R"(Something terrible happened (fix available)
 
 main.cpp:6:7: remark: declared somewhere in the main file
 
 ../foo/baz/header.h:10:11:
-note: declared somewhere in the header file)");
+note: declared somewhere in the header file)";
 
-  clangd::Diagnostic NoteInMainLSP =
-  MatchingLSP(NoteInMain, R"(Declared somewhere in the main file
+  clangd::Diagnostic NoteInMainLSP;
+  NoteInMainLSP.range = NoteInMain.Range;
+  NoteInMainLSP.severity = getSeverity(DiagnosticsEngine::Remark);
+  NoteInMainLSP.message = R"(Declared somewhere in the main file
 
-main.cpp:2:3: error: something terrible happened)");
+main.cpp:2:3: error: something terrible happened)";
 
-  // Transform dianostics and check the results.
+  ClangdDiagnosticOptions Opts;
+  // Transform diagnostics and check the results.
   std::vector>> LSPDiags;
-  toLSPDiags(D,
-#ifdef _WIN32
- URIForFile::canonicalize("c:\\path\\to\\foo\\bar\\main.cpp",
-  /*TUPath=*/""),
-#else
-  URIForFile::canonicalize("/path/to/foo/bar/main.cpp", /*TUPath=*/""),
-#endif
- ClangdDiagnosticOptions(),
+  toLSPDiags(D, MainFile, Opts,
  [&](clangd::Diagnostic LSPDiag, ArrayRef Fixes) {
LSPDiags.push_back(
{std::move(LSPDiag),
@@ -324,6 +333,30 @@
   EXPECT_EQ(LSPDiags[0].first.source, "clang");
   EXPECT_EQ(LSPDiags[1].first.code, "");
   EXPECT_EQ(LSPDiags[1].first.source, "");
+
+  // Same thing, but don't flatten notes into the main list.
+  LSPDiags.clear();
+  Opts.EmitRelatedLocations = true;
+  toLSPDiags(D, MainFile, Opts,
+ [&](clangd::Diagnostic LSPDiag

[clang-tools-extra] r358655 - [clangd] Log verbosely (LSP bodies) in lit tests. NFC

2019-04-18 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Thu Apr 18 03:32:08 2019
New Revision: 358655

URL: http://llvm.org/viewvc/llvm-project?rev=358655&view=rev
Log:
[clangd] Log verbosely (LSP bodies) in lit tests. NFC

Modified:
clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp

Modified: clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp?rev=358655&r1=358654&r2=358655&view=diff
==
--- clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp (original)
+++ clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp Thu Apr 18 03:32:08 2019
@@ -93,7 +93,7 @@ static llvm::cl::opt LogL
 static llvm::cl::opt
 Test("lit-test",
  llvm::cl::desc("Abbreviation for -input-style=delimited -pretty "
-"-run-synchronously -enable-test-scheme. "
+"-run-synchronously -enable-test-scheme -log=verbose. "
 "Intended to simplify lit tests."),
  llvm::cl::init(false), llvm::cl::Hidden);
 
@@ -330,6 +330,7 @@ int main(int argc, char *argv[]) {
   if (Test) {
 RunSynchronously = true;
 InputStyle = JSONStreamStyle::Delimited;
+LogLevel = Logger::Verbose;
 PrettyPrint = true;
 preventThreadStarvationInTests(); // Ensure background index makes 
progress.
   }


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


[PATCH] D60835: [Serialization] Stable serialization order for OpenCLTypeExtMap and OpenCLDeclExtMap

2019-04-18 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In D60835#1470805 , @riccibruno wrote:

> By the way, I am wondering about how much this is tested. I did look quickly 
> in `test/PCH` and it appears that there are only 3 (short) tests : 
> `ocl_types.cl`, `opencl-extensions.cl` and `no-validate-pch`.


This is tested in  test/SemaOpenCL/extension-begin.cl: 
https://reviews.llvm.org/D53200

The ordering in PCH isn't tested anywhere however, but I am not clear how to 
check for nondeterminism properly. Because the fact that the same output is 
generated N times won't guarantee that it's the same N+1 times. Especially I do 
believe it's likely on the same revision the same output to be produced but 
it's less likely across revisions. :(

We could still go for something like the following but accept that some a 
random failure might happen not necessarily on a commit that introduces it?

In D60778#1468825 , @lebedev.ri wrote:

> > Not sure how to test this though? I guess we can trust that std::map is 
> > always sorted just as it says in its description.
>
> You could add a test that contains several entries in `OpenCLTypeExtMap` and 
> several entries in `OpenCLDeclExtMap`.
>  In that test, write te PCH, and then apply `llvm-bcanalyzer` to that PCH. It 
> should dump it the bitcode in textual dump.
>  And then simply apply FileCheck to that textual dump, with CHECK lines 
> requiring the specific order of these entries.
>  If the order is not deterministic in PCH, then that test would (should!) 
> fail sporadically.
>  At least that is my guess.



Repository:
  rC Clang

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

https://reviews.llvm.org/D60835



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


[PATCH] D60267: [clangd] Support relatedInformation in diagnostics.

2019-04-18 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clangd/Diagnostics.cpp:271
+  if (!Note.AbsFile) {
+log("Dropping note from unknown file: {0}", Note);
+continue;

ilya-biryukov wrote:
> Maybe `vlog`? This is what we use for dropped diagnostics, should probably 
> stick to the same level with dropped notes (even though the dropped notes 
> probably come up less often in practice).
We seem to be dropping these only at related information case, what about 
flattening?
Maybe we should get rid of them at that stage as well.



Comment at: clangd/Diagnostics.cpp:417
 D.InsideMainFile = InsideMainFile;
 D.File = Info.getSourceManager().getFilename(Info.getLocation());
+auto &SM = Info.getSourceManager();

Do we still need the File field as well?


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D60267



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


[PATCH] D60267: [clangd] Support relatedInformation in diagnostics.

2019-04-18 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 2 inline comments as done.
sammccall added inline comments.



Comment at: clangd/Diagnostics.cpp:271
+  if (!Note.AbsFile) {
+log("Dropping note from unknown file: {0}", Note);
+continue;

kadircet wrote:
> ilya-biryukov wrote:
> > Maybe `vlog`? This is what we use for dropped diagnostics, should probably 
> > stick to the same level with dropped notes (even though the dropped notes 
> > probably come up less often in practice).
> We seem to be dropping these only at related information case, what about 
> flattening?
> Maybe we should get rid of them at that stage as well.
As with the other comment - you're right, and we'll drop these if we refactor - 
I don't think there's any need to drop them now, though.



Comment at: clangd/Diagnostics.cpp:417
 D.InsideMainFile = InsideMainFile;
 D.File = Info.getSourceManager().getFilename(Info.getLocation());
+auto &SM = Info.getSourceManager();

kadircet wrote:
> Do we still need the File field as well?
It's more readable than full path - e.g. if the main TU is foo.cc and includes 
foo.h, this is "foo.h".

It's true that if we want to flatten as another pass, we're not going to make 
use of this information. I'd rather change that in the flatten-as-another-pass 
patch, so we can see whether the damage to output is worth the refactoring.
(And whether we want to explicitly compute a nice path somehow, etc)


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D60267



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


[PATCH] D60821: [clangd] Emit better error messages when rename fails.

2019-04-18 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 195715.
hokein marked an inline comment as done.
hokein added a comment.

Simplify the code further.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60821

Files:
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/test/clangd/rename.test


Index: clang-tools-extra/test/clangd/rename.test
===
--- clang-tools-extra/test/clangd/rename.test
+++ clang-tools-extra/test/clangd/rename.test
@@ -29,7 +29,7 @@
 
{"jsonrpc":"2.0","id":2,"method":"textDocument/rename","params":{"textDocument":{"uri":"test:///foo.cpp"},"position":{"line":0,"character":2},"newName":"bar"}}
 #  CHECK:  "error": {
 # CHECK-NEXT:"code": -32001,
-# CHECK-NEXT:"message": "clang diagnostic"
+# CHECK-NEXT:"message": "there is no symbol at the given location"
 # CHECK-NEXT:  },
 # CHECK-NEXT:  "id": 2,
 # CHECK-NEXT:  "jsonrpc": "2.0"
Index: clang-tools-extra/clangd/ClangdServer.cpp
===
--- clang-tools-extra/clangd/ClangdServer.cpp
+++ clang-tools-extra/clangd/ClangdServer.cpp
@@ -44,14 +44,24 @@
 namespace clangd {
 namespace {
 
+// Expand a DiagnosticError to make it print-friendly (print the detailed
+// message, rather than "clang diagnostic").
+llvm::Error expandDiagnostics(llvm::Error Err, DiagnosticsEngine &DE) {
+  if (auto Diag = DiagnosticError::take(Err)) {
+llvm::cantFail(std::move(Err));
+SmallVector DiagMessage;
+Diag->second.EmitToString(DE, DiagMessage);
+return llvm::make_error(DiagMessage,
+   llvm::inconvertibleErrorCode());
+  }
+  return Err;
+}
+
 class RefactoringResultCollector final
 : public tooling::RefactoringResultConsumer {
 public:
   void handleError(llvm::Error Err) override {
 assert(!Result.hasValue());
-// FIXME: figure out a way to return better message for DiagnosticError.
-// clangd uses llvm::toString to convert the Err to string, however, for
-// DiagnosticError, only "clang diagnostic" will be generated.
 Result = std::move(Err);
   }
 
@@ -301,13 +311,15 @@
 auto Rename = clang::tooling::RenameOccurrences::initiate(
 Context, SourceRange(SourceLocationBeg), NewName);
 if (!Rename)
-  return CB(Rename.takeError());
+  return CB(expandDiagnostics(Rename.takeError(),
+  AST.getASTContext().getDiagnostics()));
 
 Rename->invoke(ResultCollector, Context);
 
 assert(ResultCollector.Result.hasValue());
 if (!ResultCollector.Result.getValue())
-  return CB(ResultCollector.Result->takeError());
+  return CB(expandDiagnostics(ResultCollector.Result->takeError(),
+  AST.getASTContext().getDiagnostics()));
 
 std::vector Replacements;
 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {


Index: clang-tools-extra/test/clangd/rename.test
===
--- clang-tools-extra/test/clangd/rename.test
+++ clang-tools-extra/test/clangd/rename.test
@@ -29,7 +29,7 @@
 {"jsonrpc":"2.0","id":2,"method":"textDocument/rename","params":{"textDocument":{"uri":"test:///foo.cpp"},"position":{"line":0,"character":2},"newName":"bar"}}
 #  CHECK:  "error": {
 # CHECK-NEXT:"code": -32001,
-# CHECK-NEXT:"message": "clang diagnostic"
+# CHECK-NEXT:"message": "there is no symbol at the given location"
 # CHECK-NEXT:  },
 # CHECK-NEXT:  "id": 2,
 # CHECK-NEXT:  "jsonrpc": "2.0"
Index: clang-tools-extra/clangd/ClangdServer.cpp
===
--- clang-tools-extra/clangd/ClangdServer.cpp
+++ clang-tools-extra/clangd/ClangdServer.cpp
@@ -44,14 +44,24 @@
 namespace clangd {
 namespace {
 
+// Expand a DiagnosticError to make it print-friendly (print the detailed
+// message, rather than "clang diagnostic").
+llvm::Error expandDiagnostics(llvm::Error Err, DiagnosticsEngine &DE) {
+  if (auto Diag = DiagnosticError::take(Err)) {
+llvm::cantFail(std::move(Err));
+SmallVector DiagMessage;
+Diag->second.EmitToString(DE, DiagMessage);
+return llvm::make_error(DiagMessage,
+   llvm::inconvertibleErrorCode());
+  }
+  return Err;
+}
+
 class RefactoringResultCollector final
 : public tooling::RefactoringResultConsumer {
 public:
   void handleError(llvm::Error Err) override {
 assert(!Result.hasValue());
-// FIXME: figure out a way to return better message for DiagnosticError.
-// clangd uses llvm::toString to convert the Err to string, however, for
-// DiagnosticError, only "clang diagnostic" will be generated.
 Result = std::move(Err);
   }
 
@@ -301,13 +311,15 @@
 auto Rename = clang::tooling::RenameOccurrences::initiate(
 Context, SourceR

[clang-tools-extra] r358658 - [clangd] Emit better error messages when rename fails.

2019-04-18 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Thu Apr 18 04:35:22 2019
New Revision: 358658

URL: http://llvm.org/viewvc/llvm-project?rev=358658&view=rev
Log:
[clangd] Emit better error messages when rename fails.

Summary:
Currently we emit an unfriendly "clang diagnostic" message when rename fails. 
This
patch makes clangd to emit a detailed diagnostic message.

Reviewers: sammccall

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

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/ClangdServer.cpp
clang-tools-extra/trunk/test/clangd/rename.test

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=358658&r1=358657&r2=358658&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Thu Apr 18 04:35:22 2019
@@ -44,14 +44,24 @@ namespace clang {
 namespace clangd {
 namespace {
 
+// Expand a DiagnosticError to make it print-friendly (print the detailed
+// message, rather than "clang diagnostic").
+llvm::Error expandDiagnostics(llvm::Error Err, DiagnosticsEngine &DE) {
+  if (auto Diag = DiagnosticError::take(Err)) {
+llvm::cantFail(std::move(Err));
+SmallVector DiagMessage;
+Diag->second.EmitToString(DE, DiagMessage);
+return llvm::make_error(DiagMessage,
+   llvm::inconvertibleErrorCode());
+  }
+  return Err;
+}
+
 class RefactoringResultCollector final
 : public tooling::RefactoringResultConsumer {
 public:
   void handleError(llvm::Error Err) override {
 assert(!Result.hasValue());
-// FIXME: figure out a way to return better message for DiagnosticError.
-// clangd uses llvm::toString to convert the Err to string, however, for
-// DiagnosticError, only "clang diagnostic" will be generated.
 Result = std::move(Err);
   }
 
@@ -301,13 +311,15 @@ void ClangdServer::rename(PathRef File,
 auto Rename = clang::tooling::RenameOccurrences::initiate(
 Context, SourceRange(SourceLocationBeg), NewName);
 if (!Rename)
-  return CB(Rename.takeError());
+  return CB(expandDiagnostics(Rename.takeError(),
+  AST.getASTContext().getDiagnostics()));
 
 Rename->invoke(ResultCollector, Context);
 
 assert(ResultCollector.Result.hasValue());
 if (!ResultCollector.Result.getValue())
-  return CB(ResultCollector.Result->takeError());
+  return CB(expandDiagnostics(ResultCollector.Result->takeError(),
+  AST.getASTContext().getDiagnostics()));
 
 std::vector Replacements;
 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {

Modified: clang-tools-extra/trunk/test/clangd/rename.test
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clangd/rename.test?rev=358658&r1=358657&r2=358658&view=diff
==
--- clang-tools-extra/trunk/test/clangd/rename.test (original)
+++ clang-tools-extra/trunk/test/clangd/rename.test Thu Apr 18 04:35:22 2019
@@ -29,7 +29,7 @@
 
{"jsonrpc":"2.0","id":2,"method":"textDocument/rename","params":{"textDocument":{"uri":"test:///foo.cpp"},"position":{"line":0,"character":2},"newName":"bar"}}
 #  CHECK:  "error": {
 # CHECK-NEXT:"code": -32001,
-# CHECK-NEXT:"message": "clang diagnostic"
+# CHECK-NEXT:"message": "there is no symbol at the given location"
 # CHECK-NEXT:  },
 # CHECK-NEXT:  "id": 2,
 # CHECK-NEXT:  "jsonrpc": "2.0"


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


[PATCH] D60821: [clangd] Emit better error messages when rename fails.

2019-04-18 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE358658: [clangd] Emit better error messages when rename 
fails. (authored by hokein, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D60821?vs=195715&id=195717#toc

Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D60821

Files:
  clangd/ClangdServer.cpp
  test/clangd/rename.test


Index: test/clangd/rename.test
===
--- test/clangd/rename.test
+++ test/clangd/rename.test
@@ -29,7 +29,7 @@
 
{"jsonrpc":"2.0","id":2,"method":"textDocument/rename","params":{"textDocument":{"uri":"test:///foo.cpp"},"position":{"line":0,"character":2},"newName":"bar"}}
 #  CHECK:  "error": {
 # CHECK-NEXT:"code": -32001,
-# CHECK-NEXT:"message": "clang diagnostic"
+# CHECK-NEXT:"message": "there is no symbol at the given location"
 # CHECK-NEXT:  },
 # CHECK-NEXT:  "id": 2,
 # CHECK-NEXT:  "jsonrpc": "2.0"
Index: clangd/ClangdServer.cpp
===
--- clangd/ClangdServer.cpp
+++ clangd/ClangdServer.cpp
@@ -44,14 +44,24 @@
 namespace clangd {
 namespace {
 
+// Expand a DiagnosticError to make it print-friendly (print the detailed
+// message, rather than "clang diagnostic").
+llvm::Error expandDiagnostics(llvm::Error Err, DiagnosticsEngine &DE) {
+  if (auto Diag = DiagnosticError::take(Err)) {
+llvm::cantFail(std::move(Err));
+SmallVector DiagMessage;
+Diag->second.EmitToString(DE, DiagMessage);
+return llvm::make_error(DiagMessage,
+   llvm::inconvertibleErrorCode());
+  }
+  return Err;
+}
+
 class RefactoringResultCollector final
 : public tooling::RefactoringResultConsumer {
 public:
   void handleError(llvm::Error Err) override {
 assert(!Result.hasValue());
-// FIXME: figure out a way to return better message for DiagnosticError.
-// clangd uses llvm::toString to convert the Err to string, however, for
-// DiagnosticError, only "clang diagnostic" will be generated.
 Result = std::move(Err);
   }
 
@@ -301,13 +311,15 @@
 auto Rename = clang::tooling::RenameOccurrences::initiate(
 Context, SourceRange(SourceLocationBeg), NewName);
 if (!Rename)
-  return CB(Rename.takeError());
+  return CB(expandDiagnostics(Rename.takeError(),
+  AST.getASTContext().getDiagnostics()));
 
 Rename->invoke(ResultCollector, Context);
 
 assert(ResultCollector.Result.hasValue());
 if (!ResultCollector.Result.getValue())
-  return CB(ResultCollector.Result->takeError());
+  return CB(expandDiagnostics(ResultCollector.Result->takeError(),
+  AST.getASTContext().getDiagnostics()));
 
 std::vector Replacements;
 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {


Index: test/clangd/rename.test
===
--- test/clangd/rename.test
+++ test/clangd/rename.test
@@ -29,7 +29,7 @@
 {"jsonrpc":"2.0","id":2,"method":"textDocument/rename","params":{"textDocument":{"uri":"test:///foo.cpp"},"position":{"line":0,"character":2},"newName":"bar"}}
 #  CHECK:  "error": {
 # CHECK-NEXT:"code": -32001,
-# CHECK-NEXT:"message": "clang diagnostic"
+# CHECK-NEXT:"message": "there is no symbol at the given location"
 # CHECK-NEXT:  },
 # CHECK-NEXT:  "id": 2,
 # CHECK-NEXT:  "jsonrpc": "2.0"
Index: clangd/ClangdServer.cpp
===
--- clangd/ClangdServer.cpp
+++ clangd/ClangdServer.cpp
@@ -44,14 +44,24 @@
 namespace clangd {
 namespace {
 
+// Expand a DiagnosticError to make it print-friendly (print the detailed
+// message, rather than "clang diagnostic").
+llvm::Error expandDiagnostics(llvm::Error Err, DiagnosticsEngine &DE) {
+  if (auto Diag = DiagnosticError::take(Err)) {
+llvm::cantFail(std::move(Err));
+SmallVector DiagMessage;
+Diag->second.EmitToString(DE, DiagMessage);
+return llvm::make_error(DiagMessage,
+   llvm::inconvertibleErrorCode());
+  }
+  return Err;
+}
+
 class RefactoringResultCollector final
 : public tooling::RefactoringResultConsumer {
 public:
   void handleError(llvm::Error Err) override {
 assert(!Result.hasValue());
-// FIXME: figure out a way to return better message for DiagnosticError.
-// clangd uses llvm::toString to convert the Err to string, however, for
-// DiagnosticError, only "clang diagnostic" will be generated.
 Result = std::move(Err);
   }
 
@@ -301,13 +311,15 @@
 auto Rename = clang::tooling::RenameOccurrences::initiate(
 Context, SourceRange(SourceLocationBeg), NewName);
 if (!Rename)
-  return CB(Rename.takeError());
+  return CB(expa

[PATCH] D60627: [MSVC] Use the correct casing of HostX64/HostX86

2019-04-18 Thread Hans Wennborg via Phabricator via cfe-commits
hans accepted this revision.
hans added a comment.
This revision is now accepted and ready to land.

Looks good to me.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60627



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


[PATCH] D60267: [clangd] Support relatedInformation in diagnostics.

2019-04-18 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Discussed further offline - it's not clear that expressing the flattening as 
LSP diagnostic -> LSP diagnostic is better than the current Diag -> LSP 
diagnostic.

So that followup probably won't happen, and there isn't that much to be gained 
from "unifying" the behavior in !AbsFile or File!=AbsFile cases.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D60267



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


r358661 - [Sema] Delete unused parameters/variables

2019-04-18 Thread Fangrui Song via cfe-commits
Author: maskray
Date: Thu Apr 18 05:35:02 2019
New Revision: 358661

URL: http://llvm.org/viewvc/llvm-project?rev=358661&view=rev
Log:
[Sema] Delete unused parameters/variables

Modified:
cfe/trunk/lib/Sema/SemaDecl.cpp

Modified: cfe/trunk/lib/Sema/SemaDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDecl.cpp?rev=358661&r1=358660&r2=358661&view=diff
==
--- cfe/trunk/lib/Sema/SemaDecl.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDecl.cpp Thu Apr 18 05:35:02 2019
@@ -9612,9 +9612,7 @@ static bool CheckMultiVersionAdditionalR
 /// Returns true if there was an error, false otherwise.
 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
MultiVersionKind MVType,
-   const TargetAttr *TA,
-   const CPUDispatchAttr *CPUDisp,
-   const CPUSpecificAttr *CPUSpec) {
+   const TargetAttr *TA) {
   assert(MVType != MultiVersionKind::None &&
  "Function lacks multiversion attribute");
 
@@ -9921,8 +9919,7 @@ static bool CheckMultiVersionFunction(Se
 // multiversioning, this isn't an error condition.
 if (MVType == MultiVersionKind::None)
   return false;
-return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA, NewCPUDisp,
-  NewCPUSpec);
+return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
   }
 
   FunctionDecl *OldFD = OldDecl->getAsFunction();
@@ -11777,7 +11774,6 @@ Sema::ActOnCXXForRangeIdentifier(Scope *
   D.SetIdentifier(Ident, IdentLoc);
   D.takeAttributes(Attrs, AttrEnd);
 
-  ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
 IdentLoc);
   Decl *Var = ActOnDeclarator(S, D);


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


[PATCH] D60857: [clang-tidy] Address post-commit comments

2019-04-18 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added inline comments.



Comment at: clang-tools-extra/test/clang-tidy/alternative-fixes.cpp:1-7
+// RUN: clang-tidy -checks='-*,llvm-namespace-comment,clang-diagnostic-*' %s 
-- \
+// RUN: | FileCheck -implicit-check-not='{{warning|error|note}}:' %s
+
+// Verify clang-tidy only applies the first alternative fix.
+// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
+// RUN: clang-tidy -checks='-*,llvm-namespace-comment,clang-diagnostic-*' -fix 
%t.cpp --
+// RUN: FileCheck -input-file=%t.cpp %s -check-prefix=CHECK-FIX

Why can't we use the check_clang_tidy script?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60857



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


[PATCH] D60857: [clang-tidy] Address post-commit comments

2019-04-18 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/test/clang-tidy/alternative-fixes.cpp:1-7
+// RUN: clang-tidy -checks='-*,llvm-namespace-comment,clang-diagnostic-*' %s 
-- \
+// RUN: | FileCheck -implicit-check-not='{{warning|error|note}}:' %s
+
+// Verify clang-tidy only applies the first alternative fix.
+// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
+// RUN: clang-tidy -checks='-*,llvm-namespace-comment,clang-diagnostic-*' -fix 
%t.cpp --
+// RUN: FileCheck -input-file=%t.cpp %s -check-prefix=CHECK-FIX

alexfh wrote:
> Why can't we use the check_clang_tidy script?
Yes, we do. This was blindly copied from other diagnostic tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60857



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


[PATCH] D60857: [clang-tidy] Address post-commit comments

2019-04-18 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 195720.
hokein marked an inline comment as done.
hokein added a comment.

Use check_clang_tidy.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60857

Files:
  clang-tools-extra/clang-tidy/ClangTidy.cpp
  clang-tools-extra/test/clang-tidy/alternative-fixes.cpp
  clang/include/clang/Tooling/Core/Diagnostic.h

Index: clang/include/clang/Tooling/Core/Diagnostic.h
===
--- clang/include/clang/Tooling/Core/Diagnostic.h
+++ clang/include/clang/Tooling/Core/Diagnostic.h
@@ -93,8 +93,8 @@
   std::vector Diagnostics;
 };
 
-// Get the first fix to apply for this diagnostic.
-// Return nullptr if no fixes attached to the diagnostic.
+/// Get the first fix to apply for this diagnostic.
+/// Returns nullptr if no fixes are attached to the diagnostic.
 const llvm::StringMap *selectFirstFix(const Diagnostic& D);
 
 } // end namespace tooling
Index: clang-tools-extra/test/clang-tidy/alternative-fixes.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/alternative-fixes.cpp
@@ -0,0 +1,9 @@
+// RUN: %check_clang_tidy %s "llvm-namespace-comment,clang-diagnostic-*" %t
+void foo(int a) {
+  if (a = 1) {
+  // CHECK-NOTES: [[@LINE-1]]:9: warning: using the result of an assignment as a condition without parentheses [clang-diagnostic-parentheses]
+  // CHECK-NOTES: [[@LINE-2]]:9: note: place parentheses around the assignment to silence this warning
+  // CHECK-NOTES: [[@LINE-3]]:9: note: use '==' to turn this assignment into an equality comparison
+  // CHECK-FIXES: if ((a = 1)) {
+  }
+}
Index: clang-tools-extra/clang-tidy/ClangTidy.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidy.cpp
+++ clang-tools-extra/clang-tidy/ClangTidy.cpp
@@ -133,41 +133,40 @@
   for (const auto &Repl : FileAndReplacements.second) {
 ++TotalFixes;
 bool CanBeApplied = false;
-if (Repl.isApplicable()) {
-  SourceLocation FixLoc;
-  SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
-  Files.makeAbsolutePath(FixAbsoluteFilePath);
-  tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
- Repl.getLength(),
- Repl.getReplacementText());
-  Replacements &Replacements = FileReplacements[R.getFilePath()];
-  llvm::Error Err = Replacements.add(R);
-  if (Err) {
-// FIXME: Implement better conflict handling.
-llvm::errs() << "Trying to resolve conflict: "
- << llvm::toString(std::move(Err)) << "\n";
-unsigned NewOffset =
-Replacements.getShiftedCodePosition(R.getOffset());
-unsigned NewLength = Replacements.getShiftedCodePosition(
- R.getOffset() + R.getLength()) -
- NewOffset;
-if (NewLength == R.getLength()) {
-  R = Replacement(R.getFilePath(), NewOffset, NewLength,
-  R.getReplacementText());
-  Replacements = Replacements.merge(tooling::Replacements(R));
-  CanBeApplied = true;
-  ++AppliedFixes;
-} else {
-  llvm::errs()
-  << "Can't resolve conflict, skipping the replacement.\n";
-}
-  } else {
+if (!Repl.isApplicable())
+  continue;
+SourceLocation FixLoc;
+SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
+Files.makeAbsolutePath(FixAbsoluteFilePath);
+tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
+   Repl.getLength(), Repl.getReplacementText());
+Replacements &Replacements = FileReplacements[R.getFilePath()];
+llvm::Error Err = Replacements.add(R);
+if (Err) {
+  // FIXME: Implement better conflict handling.
+  llvm::errs() << "Trying to resolve conflict: "
+   << llvm::toString(std::move(Err)) << "\n";
+  unsigned NewOffset =
+  Replacements.getShiftedCodePosition(R.getOffset());
+  unsigned NewLength = Replacements.getShiftedCodePosition(
+   R.getOffset() + R.getLength()) -
+   NewOffset;
+  if (NewLength == R.getLength()) {
+R = Replacement(R.getFilePath(), NewOffset, NewLength,
+R.getReplacementText());
+Replacements = Replacements.merge(tooling::Replacemen

[PATCH] D60865: [clangd] Use llvm::set_thread_priority in background-index

2019-04-18 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: gribozavr.
Herald added subscribers: cfe-commits, jfb, arphaman, jkorous, MaskRay, ioeric, 
ilya-biryukov, krytarowski.
Herald added a project: clang.

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D60865

Files:
  clangd/Threading.cpp
  clangd/Threading.h
  clangd/index/Background.cpp
  clangd/index/Background.h
  clangd/tool/ClangdMain.cpp
  unittests/clangd/BackgroundIndexTests.cpp

Index: unittests/clangd/BackgroundIndexTests.cpp
===
--- unittests/clangd/BackgroundIndexTests.cpp
+++ unittests/clangd/BackgroundIndexTests.cpp
@@ -70,7 +70,7 @@
 
 class BackgroundIndexTest : public ::testing::Test {
 protected:
-  BackgroundIndexTest() { preventThreadStarvationInTests(); }
+  BackgroundIndexTest() { BackgroundIndex::preventThreadStarvationInTests(); }
 };
 
 TEST_F(BackgroundIndexTest, NoCrashOnErrorFile) {
Index: clangd/tool/ClangdMain.cpp
===
--- clangd/tool/ClangdMain.cpp
+++ clangd/tool/ClangdMain.cpp
@@ -13,6 +13,7 @@
 #include "Protocol.h"
 #include "Trace.h"
 #include "Transport.h"
+#include "index/Background.h"
 #include "index/Serialization.h"
 #include "clang/Basic/Version.h"
 #include "llvm/ADT/Optional.h"
@@ -332,7 +333,8 @@
 InputStyle = JSONStreamStyle::Delimited;
 LogLevel = Logger::Verbose;
 PrettyPrint = true;
-preventThreadStarvationInTests(); // Ensure background index makes progress.
+// Ensure background index makes progress.
+BackgroundIndex::preventThreadStarvationInTests();
   }
   if (Test || EnableTestScheme) {
 static URISchemeRegistry::Add X(
Index: clangd/index/Background.h
===
--- clangd/index/Background.h
+++ clangd/index/Background.h
@@ -88,6 +88,10 @@
   LLVM_NODISCARD bool
   blockUntilIdleForTest(llvm::Optional TimeoutSeconds = 10);
 
+  // Disables thread priority lowering in background index to make sure it can
+  // progress on loaded systems. Only affects tasks that run after the call.
+  static void preventThreadStarvationInTests();
+
 private:
   /// Given index results from a TU, only update symbols coming from files with
   /// different digests than \p DigestsSnapshot. Also stores new index
@@ -134,14 +138,14 @@
   // queue management
   using Task = std::function;
   void run(); // Main loop executed by Thread. Runs tasks from Queue.
-  void enqueueTask(Task T, ThreadPriority Prioirty);
+  void enqueueTask(Task T, llvm::ThreadPriority Prioirty);
   void enqueueLocked(tooling::CompileCommand Cmd,
  BackgroundIndexStorage *IndexStorage);
   std::mutex QueueMu;
   unsigned NumActiveTasks = 0; // Only idle when queue is empty *and* no tasks.
   std::condition_variable QueueCV;
   bool ShouldStop = false;
-  std::deque> Queue;
+  std::deque> Queue;
   std::vector ThreadPool; // FIXME: Abstract this away.
   GlobalCompilationDatabase::CommandChanged::Subscription CommandsChanged;
 };
Index: clangd/index/Background.cpp
===
--- clangd/index/Background.cpp
+++ clangd/index/Background.cpp
@@ -26,7 +26,9 @@
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/SHA1.h"
+#include "llvm/Support/Threading.h"
 
+#include 
 #include 
 #include 
 #include 
@@ -38,6 +40,9 @@
 namespace clang {
 namespace clangd {
 namespace {
+
+static std::atomic PreventStarvation = {false};
+
 // Resolves URI to file paths with cache.
 class URIToFileCache {
 public:
@@ -172,7 +177,7 @@
   WithContext Background(BackgroundContext.clone());
   while (true) {
 llvm::Optional Task;
-ThreadPriority Priority;
+llvm::ThreadPriority Priority;
 {
   std::unique_lock Lock(QueueMu);
   QueueCV.wait(Lock, [&] { return ShouldStop || !Queue.empty(); });
@@ -186,11 +191,11 @@
   Queue.pop_front();
 }
 
-if (Priority != ThreadPriority::Normal)
-  setCurrentThreadPriority(Priority);
+if (Priority != llvm::ThreadPriority::Default && !PreventStarvation.load())
+  llvm::set_thread_priority(Priority);
 (*Task)();
-if (Priority != ThreadPriority::Normal)
-  setCurrentThreadPriority(ThreadPriority::Normal);
+if (Priority != llvm::ThreadPriority::Default)
+  llvm::set_thread_priority(llvm::ThreadPriority::Default);
 
 {
   std::unique_lock Lock(QueueMu);
@@ -223,7 +228,7 @@
 for (auto &Elem : NeedsReIndexing)
   enqueue(std::move(Elem.first), Elem.second);
   },
-  ThreadPriority::Normal);
+  llvm::ThreadPriority::Default);
 }
 
 void BackgroundIndex::enqueue(tooling::CompileCommand Cmd,
@@ -238,10 +243,10 @@
std::move(Error));
   },
   std::move(Cmd)),
-  ThreadPriority::Low);
+  llvm::ThreadPriority::Background);
 }
 
-voi

[PATCH] D60835: [Serialization] Stable serialization order for OpenCLTypeExtMap and OpenCLDeclExtMap

2019-04-18 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno added a comment.

In D60835#1471498 , @Anastasia wrote:

> In D60835#1470805 , @riccibruno 
> wrote:
>
> > By the way, I am wondering about how much this is tested. I did look 
> > quickly in `test/PCH` and it appears that there are only 3 (short) tests : 
> > `ocl_types.cl`, `opencl-extensions.cl` and `no-validate-pch`.
>
>
> This is tested in  test/SemaOpenCL/extension-begin.cl: 
> https://reviews.llvm.org/D53200


Ah I see, I did indeed miss that.

> The ordering in PCH isn't tested anywhere however, but I am not clear how to 
> check for nondeterminism properly. Because the fact that the same output is 
> generated N times won't guarantee that it's the same N+1 times. Especially I 
> do believe it's likely on the same revision the same output to be produced 
> but it's less likely across revisions. :(
> 
> We could still go for something like the following but accept that some a 
> random failure might happen not necessarily on a commit that introduces it?

I am not sure that this is needed. Non-deterministic tests are really annoying.

> In D60778#1468825 , @lebedev.ri 
> wrote:
> 
>> > Not sure how to test this though? I guess we can trust that std::map is 
>> > always sorted just as it says in its description.
>>
>> You could add a test that contains several entries in `OpenCLTypeExtMap` and 
>> several entries in `OpenCLDeclExtMap`.
>>  In that test, write te PCH, and then apply `llvm-bcanalyzer` to that PCH. 
>> It should dump it the bitcode in textual dump.
>>  And then simply apply FileCheck to that textual dump, with CHECK lines 
>> requiring the specific order of these entries.
>>  If the order is not deterministic in PCH, then that test would (should!) 
>> fail sporadically.
>>  At least that is my guess.




Repository:
  rC Clang

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

https://reviews.llvm.org/D60835



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


[PATCH] D60867: [clang][CIndex] Use llvm::set_thread_priority

2019-04-18 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added reviewers: jkorous, gribozavr.
Herald added subscribers: cfe-commits, arphaman, dexonsmith.
Herald added a project: clang.

Repository:
  rC Clang

https://reviews.llvm.org/D60867

Files:
  tools/libclang/CIndex.cpp


Index: tools/libclang/CIndex.cpp
===
--- tools/libclang/CIndex.cpp
+++ tools/libclang/CIndex.cpp
@@ -8723,9 +8723,7 @@
   if (getenv("LIBCLANG_BGPRIO_DISABLE"))
 return;
 
-#ifdef USE_DARWIN_THREADS
-  setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
-#endif
+  llvm::set_thread_priority(llvm::ThreadPriority::Background);
 }
 
 void cxindex::printDiagsToStderr(ASTUnit *Unit) {


Index: tools/libclang/CIndex.cpp
===
--- tools/libclang/CIndex.cpp
+++ tools/libclang/CIndex.cpp
@@ -8723,9 +8723,7 @@
   if (getenv("LIBCLANG_BGPRIO_DISABLE"))
 return;
 
-#ifdef USE_DARWIN_THREADS
-  setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
-#endif
+  llvm::set_thread_priority(llvm::ThreadPriority::Background);
 }
 
 void cxindex::printDiagsToStderr(ASTUnit *Unit) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r358662 - [MSVC] Use the correct casing of HostX64/HostX86

2019-04-18 Thread Martin Storsjo via cfe-commits
Author: mstorsjo
Date: Thu Apr 18 06:27:31 2019
New Revision: 358662

URL: http://llvm.org/viewvc/llvm-project?rev=358662&view=rev
Log:
[MSVC] Use the correct casing of HostX64/HostX86

If accessing the MSVC installation root directly on a case sensitive
filesystem, these details matter.

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

Modified:
cfe/trunk/lib/Driver/ToolChains/MSVC.cpp

Modified: cfe/trunk/lib/Driver/ToolChains/MSVC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/MSVC.cpp?rev=358662&r1=358661&r2=358662&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/MSVC.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/MSVC.cpp Thu Apr 18 06:27:31 2019
@@ -496,7 +496,7 @@ void visualstudio::Linker::ConstructJob(
 // its containing bin directory at the top of PATH, followed by the
 // native target bin directory.
 // e.g. when compiling for x86 on an x64 host, PATH should start with:
-// /bin/HostX64/x86;/bin/HostX64/x64
+// /bin/Hostx64/x86;/bin/Hostx64/x64
 // This doesn't attempt to handle ToolsetLayout::DevDivInternal.
 if (TC.getIsVS2017OrNewer() &&
 llvm::Triple(llvm::sys::getProcessTriple()).getArch() != TC.getArch()) 
{
@@ -838,7 +838,7 @@ MSVCToolChain::getSubDirectoryPath(SubDi
 if (VSLayout == ToolsetLayout::VS2017OrNewer) {
   const bool HostIsX64 =
   llvm::Triple(llvm::sys::getProcessTriple()).isArch64Bit();
-  const char *const HostName = HostIsX64 ? "HostX64" : "HostX86";
+  const char *const HostName = HostIsX64 ? "Hostx64" : "Hostx86";
   llvm::sys::path::append(Path, "bin", HostName, SubdirName);
 } else { // OlderVS or DevDivInternal
   llvm::sys::path::append(Path, "bin", SubdirName);


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


[PATCH] D60627: [MSVC] Use the correct casing of HostX64/HostX86

2019-04-18 Thread Martin Storsjö via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL358662: [MSVC] Use the correct casing of HostX64/HostX86 
(authored by mstorsjo, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D60627?vs=194929&id=195726#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D60627

Files:
  cfe/trunk/lib/Driver/ToolChains/MSVC.cpp


Index: cfe/trunk/lib/Driver/ToolChains/MSVC.cpp
===
--- cfe/trunk/lib/Driver/ToolChains/MSVC.cpp
+++ cfe/trunk/lib/Driver/ToolChains/MSVC.cpp
@@ -496,7 +496,7 @@
 // its containing bin directory at the top of PATH, followed by the
 // native target bin directory.
 // e.g. when compiling for x86 on an x64 host, PATH should start with:
-// /bin/HostX64/x86;/bin/HostX64/x64
+// /bin/Hostx64/x86;/bin/Hostx64/x64
 // This doesn't attempt to handle ToolsetLayout::DevDivInternal.
 if (TC.getIsVS2017OrNewer() &&
 llvm::Triple(llvm::sys::getProcessTriple()).getArch() != TC.getArch()) 
{
@@ -838,7 +838,7 @@
 if (VSLayout == ToolsetLayout::VS2017OrNewer) {
   const bool HostIsX64 =
   llvm::Triple(llvm::sys::getProcessTriple()).isArch64Bit();
-  const char *const HostName = HostIsX64 ? "HostX64" : "HostX86";
+  const char *const HostName = HostIsX64 ? "Hostx64" : "Hostx86";
   llvm::sys::path::append(Path, "bin", HostName, SubdirName);
 } else { // OlderVS or DevDivInternal
   llvm::sys::path::append(Path, "bin", SubdirName);


Index: cfe/trunk/lib/Driver/ToolChains/MSVC.cpp
===
--- cfe/trunk/lib/Driver/ToolChains/MSVC.cpp
+++ cfe/trunk/lib/Driver/ToolChains/MSVC.cpp
@@ -496,7 +496,7 @@
 // its containing bin directory at the top of PATH, followed by the
 // native target bin directory.
 // e.g. when compiling for x86 on an x64 host, PATH should start with:
-// /bin/HostX64/x86;/bin/HostX64/x64
+// /bin/Hostx64/x86;/bin/Hostx64/x64
 // This doesn't attempt to handle ToolsetLayout::DevDivInternal.
 if (TC.getIsVS2017OrNewer() &&
 llvm::Triple(llvm::sys::getProcessTriple()).getArch() != TC.getArch()) {
@@ -838,7 +838,7 @@
 if (VSLayout == ToolsetLayout::VS2017OrNewer) {
   const bool HostIsX64 =
   llvm::Triple(llvm::sys::getProcessTriple()).isArch64Bit();
-  const char *const HostName = HostIsX64 ? "HostX64" : "HostX86";
+  const char *const HostName = HostIsX64 ? "Hostx64" : "Hostx86";
   llvm::sys::path::append(Path, "bin", HostName, SubdirName);
 } else { // OlderVS or DevDivInternal
   llvm::sys::path::append(Path, "bin", SubdirName);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D60857: [clang-tidy] Address post-commit comments

2019-04-18 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh accepted this revision.
alexfh added a comment.
This revision is now accepted and ready to land.

There's one more nit. Otherwise good to go.

Thanks!




Comment at: clang/include/clang/Tooling/Core/Diagnostic.h:97
+/// Get the first fix to apply for this diagnostic.
+/// Returns nullptr if no fixes are attached to the diagnostic.
 const llvm::StringMap *selectFirstFix(const Diagnostic& D);

This should be Doxygen's `\returns` keyword.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60857



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


[clang-tools-extra] r358664 - [clangd] Use llvm::set_thread_priority in background-index

2019-04-18 Thread Kadir Cetinkaya via cfe-commits
Author: kadircet
Date: Thu Apr 18 06:46:40 2019
New Revision: 358664

URL: http://llvm.org/viewvc/llvm-project?rev=358664&view=rev
Log:
[clangd] Use llvm::set_thread_priority in background-index

Reviewers: gribozavr

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

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/Threading.cpp
clang-tools-extra/trunk/clangd/Threading.h
clang-tools-extra/trunk/clangd/index/Background.cpp
clang-tools-extra/trunk/clangd/index/Background.h
clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp
clang-tools-extra/trunk/unittests/clangd/BackgroundIndexTests.cpp

Modified: clang-tools-extra/trunk/clangd/Threading.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Threading.cpp?rev=358664&r1=358663&r2=358664&view=diff
==
--- clang-tools-extra/trunk/clangd/Threading.cpp (original)
+++ clang-tools-extra/trunk/clangd/Threading.cpp Thu Apr 18 06:46:40 2019
@@ -113,33 +113,5 @@ void wait(std::unique_lock &
   CV.wait_until(Lock, D.time());
 }
 
-static std::atomic AvoidThreadStarvation = {false};
-
-void setCurrentThreadPriority(ThreadPriority Priority) {
-  // Some *really* old glibcs are missing SCHED_IDLE.
-#if defined(__linux__) && defined(SCHED_IDLE)
-  sched_param priority;
-  priority.sched_priority = 0;
-  pthread_setschedparam(
-  pthread_self(),
-  Priority == ThreadPriority::Low && !AvoidThreadStarvation ? SCHED_IDLE
-: SCHED_OTHER,
-  &priority);
-#elif defined(__APPLE__)
-  // 
https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getpriority.2.html
-  setpriority(PRIO_DARWIN_THREAD, 0,
-  Priority == ThreadPriority::Low && !AvoidThreadStarvation
-  ? PRIO_DARWIN_BG
-  : 0);
-#elif defined(_WIN32)
-  SetThreadPriority(GetCurrentThread(),
-Priority == ThreadPriority::Low && !AvoidThreadStarvation
-? THREAD_MODE_BACKGROUND_BEGIN
-: THREAD_MODE_BACKGROUND_END);
-#endif
-}
-
-void preventThreadStarvationInTests() { AvoidThreadStarvation = true; }
-
 } // namespace clangd
 } // namespace clang

Modified: clang-tools-extra/trunk/clangd/Threading.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Threading.h?rev=358664&r1=358663&r2=358664&view=diff
==
--- clang-tools-extra/trunk/clangd/Threading.h (original)
+++ clang-tools-extra/trunk/clangd/Threading.h Thu Apr 18 06:46:40 2019
@@ -117,16 +117,6 @@ private:
   std::size_t InFlightTasks = 0;
 };
 
-enum class ThreadPriority {
-  Low = 0,
-  Normal = 1,
-};
-void setCurrentThreadPriority(ThreadPriority Priority);
-// Avoid the use of scheduler policies that may starve low-priority threads.
-// This prevents tests from timing out on loaded systems.
-// Affects subsequent setThreadPriority() calls.
-void preventThreadStarvationInTests();
-
 } // namespace clangd
 } // namespace clang
 #endif

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=358664&r1=358663&r2=358664&view=diff
==
--- clang-tools-extra/trunk/clangd/index/Background.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Background.cpp Thu Apr 18 06:46:40 2019
@@ -26,7 +26,9 @@
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/SHA1.h"
+#include "llvm/Support/Threading.h"
 
+#include 
 #include 
 #include 
 #include 
@@ -38,6 +40,9 @@
 namespace clang {
 namespace clangd {
 namespace {
+
+static std::atomic PreventStarvation = {false};
+
 // Resolves URI to file paths with cache.
 class URIToFileCache {
 public:
@@ -172,7 +177,7 @@ void BackgroundIndex::run() {
   WithContext Background(BackgroundContext.clone());
   while (true) {
 llvm::Optional Task;
-ThreadPriority Priority;
+llvm::ThreadPriority Priority;
 {
   std::unique_lock Lock(QueueMu);
   QueueCV.wait(Lock, [&] { return ShouldStop || !Queue.empty(); });
@@ -186,11 +191,11 @@ void BackgroundIndex::run() {
   Queue.pop_front();
 }
 
-if (Priority != ThreadPriority::Normal)
-  setCurrentThreadPriority(Priority);
+if (Priority != llvm::ThreadPriority::Default && !PreventStarvation.load())
+  llvm::set_thread_priority(Priority);
 (*Task)();
-if (Priority != ThreadPriority::Normal)
-  setCurrentThreadPriority(ThreadPriority::Normal);
+if (Priority != llvm::ThreadPriority::Default)
+  llvm::set_thread_priority(llvm::ThreadPriority::Default);
 
 {
   std::unique_lo

[PATCH] D60865: [clangd] Use llvm::set_thread_priority in background-index

2019-04-18 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE358664: [clangd] Use llvm::set_thread_priority in 
background-index (authored by kadircet, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D60865?vs=195721&id=195730#toc

Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D60865

Files:
  clangd/Threading.cpp
  clangd/Threading.h
  clangd/index/Background.cpp
  clangd/index/Background.h
  clangd/tool/ClangdMain.cpp
  unittests/clangd/BackgroundIndexTests.cpp

Index: clangd/index/Background.cpp
===
--- clangd/index/Background.cpp
+++ clangd/index/Background.cpp
@@ -26,7 +26,9 @@
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/SHA1.h"
+#include "llvm/Support/Threading.h"
 
+#include 
 #include 
 #include 
 #include 
@@ -38,6 +40,9 @@
 namespace clang {
 namespace clangd {
 namespace {
+
+static std::atomic PreventStarvation = {false};
+
 // Resolves URI to file paths with cache.
 class URIToFileCache {
 public:
@@ -172,7 +177,7 @@
   WithContext Background(BackgroundContext.clone());
   while (true) {
 llvm::Optional Task;
-ThreadPriority Priority;
+llvm::ThreadPriority Priority;
 {
   std::unique_lock Lock(QueueMu);
   QueueCV.wait(Lock, [&] { return ShouldStop || !Queue.empty(); });
@@ -186,11 +191,11 @@
   Queue.pop_front();
 }
 
-if (Priority != ThreadPriority::Normal)
-  setCurrentThreadPriority(Priority);
+if (Priority != llvm::ThreadPriority::Default && !PreventStarvation.load())
+  llvm::set_thread_priority(Priority);
 (*Task)();
-if (Priority != ThreadPriority::Normal)
-  setCurrentThreadPriority(ThreadPriority::Normal);
+if (Priority != llvm::ThreadPriority::Default)
+  llvm::set_thread_priority(llvm::ThreadPriority::Default);
 
 {
   std::unique_lock Lock(QueueMu);
@@ -223,7 +228,7 @@
 for (auto &Elem : NeedsReIndexing)
   enqueue(std::move(Elem.first), Elem.second);
   },
-  ThreadPriority::Normal);
+  llvm::ThreadPriority::Default);
 }
 
 void BackgroundIndex::enqueue(tooling::CompileCommand Cmd,
@@ -238,10 +243,10 @@
std::move(Error));
   },
   std::move(Cmd)),
-  ThreadPriority::Low);
+  llvm::ThreadPriority::Background);
 }
 
-void BackgroundIndex::enqueueTask(Task T, ThreadPriority Priority) {
+void BackgroundIndex::enqueueTask(Task T, llvm::ThreadPriority Priority) {
   {
 std::lock_guard Lock(QueueMu);
 auto I = Queue.end();
@@ -249,10 +254,11 @@
 // Then we store low priority tasks. Normal priority tasks are pretty rare,
 // they should not grow beyond single-digit numbers, so it is OK to do
 // linear search and insert after that.
-if (Priority == ThreadPriority::Normal) {
-  I = llvm::find_if(Queue, [](const std::pair &Elem) {
-return Elem.second == ThreadPriority::Low;
-  });
+if (Priority == llvm::ThreadPriority::Default) {
+  I = llvm::find_if(
+  Queue, [](const std::pair &Elem) {
+return Elem.second == llvm::ThreadPriority::Background;
+  });
 }
 Queue.insert(I, {std::move(T), Priority});
   }
@@ -611,5 +617,9 @@
   return NeedsReIndexing;
 }
 
+void BackgroundIndex::preventThreadStarvationInTests() {
+  PreventStarvation.store(true);
+}
+
 } // namespace clangd
 } // namespace clang
Index: clangd/index/Background.h
===
--- clangd/index/Background.h
+++ clangd/index/Background.h
@@ -88,6 +88,10 @@
   LLVM_NODISCARD bool
   blockUntilIdleForTest(llvm::Optional TimeoutSeconds = 10);
 
+  // Disables thread priority lowering in background index to make sure it can
+  // progress on loaded systems. Only affects tasks that run after the call.
+  static void preventThreadStarvationInTests();
+
 private:
   /// Given index results from a TU, only update symbols coming from files with
   /// different digests than \p DigestsSnapshot. Also stores new index
@@ -134,14 +138,14 @@
   // queue management
   using Task = std::function;
   void run(); // Main loop executed by Thread. Runs tasks from Queue.
-  void enqueueTask(Task T, ThreadPriority Prioirty);
+  void enqueueTask(Task T, llvm::ThreadPriority Prioirty);
   void enqueueLocked(tooling::CompileCommand Cmd,
  BackgroundIndexStorage *IndexStorage);
   std::mutex QueueMu;
   unsigned NumActiveTasks = 0; // Only idle when queue is empty *and* no tasks.
   std::condition_variable QueueCV;
   bool ShouldStop = false;
-  std::deque> Queue;
+  std::deque> Queue;
   std::vector ThreadPool; // FIXME: Abstract this away.
   GlobalCompilationDatabase::CommandChanged::Subscription CommandsChanged;
 };
Index: clangd/Threading.cpp
=

r358665 - [clang][CIndex] Use llvm::set_thread_priority

2019-04-18 Thread Kadir Cetinkaya via cfe-commits
Author: kadircet
Date: Thu Apr 18 06:49:20 2019
New Revision: 358665

URL: http://llvm.org/viewvc/llvm-project?rev=358665&view=rev
Log:
[clang][CIndex] Use llvm::set_thread_priority

Reviewers: jkorous, gribozavr

Subscribers: dexonsmith, arphaman, cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/tools/libclang/CIndex.cpp

Modified: cfe/trunk/tools/libclang/CIndex.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/libclang/CIndex.cpp?rev=358665&r1=358664&r2=358665&view=diff
==
--- cfe/trunk/tools/libclang/CIndex.cpp (original)
+++ cfe/trunk/tools/libclang/CIndex.cpp Thu Apr 18 06:49:20 2019
@@ -8723,9 +8723,7 @@ void clang::setThreadBackgroundPriority(
   if (getenv("LIBCLANG_BGPRIO_DISABLE"))
 return;
 
-#ifdef USE_DARWIN_THREADS
-  setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
-#endif
+  llvm::set_thread_priority(llvm::ThreadPriority::Background);
 }
 
 void cxindex::printDiagsToStderr(ASTUnit *Unit) {


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


[PATCH] D60867: [clang][CIndex] Use llvm::set_thread_priority

2019-04-18 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC358665: [clang][CIndex] Use llvm::set_thread_priority 
(authored by kadircet, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D60867?vs=195725&id=195731#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D60867

Files:
  tools/libclang/CIndex.cpp


Index: tools/libclang/CIndex.cpp
===
--- tools/libclang/CIndex.cpp
+++ tools/libclang/CIndex.cpp
@@ -8723,9 +8723,7 @@
   if (getenv("LIBCLANG_BGPRIO_DISABLE"))
 return;
 
-#ifdef USE_DARWIN_THREADS
-  setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
-#endif
+  llvm::set_thread_priority(llvm::ThreadPriority::Background);
 }
 
 void cxindex::printDiagsToStderr(ASTUnit *Unit) {


Index: tools/libclang/CIndex.cpp
===
--- tools/libclang/CIndex.cpp
+++ tools/libclang/CIndex.cpp
@@ -8723,9 +8723,7 @@
   if (getenv("LIBCLANG_BGPRIO_DISABLE"))
 return;
 
-#ifdef USE_DARWIN_THREADS
-  setpriority(PRIO_DARWIN_THREAD, 0, PRIO_DARWIN_BG);
-#endif
+  llvm::set_thread_priority(llvm::ThreadPriority::Background);
 }
 
 void cxindex::printDiagsToStderr(ASTUnit *Unit) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D60568: [OpenMP] Add support for registering requires directives with the runtime

2019-04-18 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: lib/CodeGen/CGOpenMPRuntime.cpp:7956
 // Map other list items in the map clause which are not captured variables
-// but "declare target link" global variables.,
+// but "declare target link" global variables.
 for (const auto *C : this->CurDir.getClausesOfKind()) {

ABataev wrote:
> Restore the original, this must be changed in a separate patch.
Restore



Comment at: lib/Sema/SemaOpenMP.cpp:196
   nullptr};
+  /// Vector of previously encountered target directives
+  SmallVector TargetLocations;

I would suggest to split this patch into 2 parts: the sema checking part and 
the codegen part.



Comment at: lib/Sema/SemaOpenMP.cpp:468
+  void checkEncounteredTargets(SourceLocation Loc,
+   ArrayRef ClauseList) {
+for (OMPClause *CNew : ClauseList) {

Make function `const`



Comment at: lib/Sema/SemaOpenMP.cpp:469
+   ArrayRef ClauseList) {
+for (OMPClause *CNew : ClauseList) {
+  // Check if any of the requires clauses affect target regions.

`const OMPClause *`



Comment at: lib/Sema/SemaOpenMP.cpp:476
+   isa(CNew))) {
+SemaRef.Diag(Loc,
+ diag::err_omp_target_before_requires)

DSAStack usually is not used for diagnostic emission, it serves as the 
container. Better to move the diagnostics to Act... functions.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60568



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


[PATCH] D60835: [Serialization] Stable serialization order for OpenCLTypeExtMap and OpenCLDeclExtMap

2019-04-18 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia accepted this revision.
Anastasia added a comment.
This revision is now accepted and ready to land.

>> We could still go for something like the following but accept that some a 
>> random failure might happen not necessarily on a commit that introduces it?
> 
> I am not sure that this is needed. Non-deterministic tests are really 
> annoying.

Yes. I think this might be a wider topic to address if we happen to have more 
issues of this kind.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60835



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


[PATCH] D53866: [Preamble] Stop circular inclusion of main file when building preamble

2019-04-18 Thread Nikolai Kosjar via Phabricator via cfe-commits
nik added a comment.

Ping. Ilya?


Repository:
  rC Clang

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

https://reviews.llvm.org/D53866



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


[PATCH] D60857: [clang-tidy] Address post-commit comments

2019-04-18 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 195733.
hokein added a comment.

fix doxygen comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60857

Files:
  clang-tools-extra/clang-tidy/ClangTidy.cpp
  clang-tools-extra/test/clang-tidy/alternative-fixes.cpp
  clang/include/clang/Tooling/Core/Diagnostic.h

Index: clang/include/clang/Tooling/Core/Diagnostic.h
===
--- clang/include/clang/Tooling/Core/Diagnostic.h
+++ clang/include/clang/Tooling/Core/Diagnostic.h
@@ -93,8 +93,8 @@
   std::vector Diagnostics;
 };
 
-// Get the first fix to apply for this diagnostic.
-// Return nullptr if no fixes attached to the diagnostic.
+/// Get the first fix to apply for this diagnostic.
+/// \returns nullptr if no fixes are attached to the diagnostic.
 const llvm::StringMap *selectFirstFix(const Diagnostic& D);
 
 } // end namespace tooling
Index: clang-tools-extra/test/clang-tidy/alternative-fixes.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/alternative-fixes.cpp
@@ -0,0 +1,9 @@
+// RUN: %check_clang_tidy %s "llvm-namespace-comment,clang-diagnostic-*" %t
+void foo(int a) {
+  if (a = 1) {
+  // CHECK-NOTES: [[@LINE-1]]:9: warning: using the result of an assignment as a condition without parentheses [clang-diagnostic-parentheses]
+  // CHECK-NOTES: [[@LINE-2]]:9: note: place parentheses around the assignment to silence this warning
+  // CHECK-NOTES: [[@LINE-3]]:9: note: use '==' to turn this assignment into an equality comparison
+  // CHECK-FIXES: if ((a = 1)) {
+  }
+}
Index: clang-tools-extra/clang-tidy/ClangTidy.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidy.cpp
+++ clang-tools-extra/clang-tidy/ClangTidy.cpp
@@ -133,41 +133,40 @@
   for (const auto &Repl : FileAndReplacements.second) {
 ++TotalFixes;
 bool CanBeApplied = false;
-if (Repl.isApplicable()) {
-  SourceLocation FixLoc;
-  SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
-  Files.makeAbsolutePath(FixAbsoluteFilePath);
-  tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
- Repl.getLength(),
- Repl.getReplacementText());
-  Replacements &Replacements = FileReplacements[R.getFilePath()];
-  llvm::Error Err = Replacements.add(R);
-  if (Err) {
-// FIXME: Implement better conflict handling.
-llvm::errs() << "Trying to resolve conflict: "
- << llvm::toString(std::move(Err)) << "\n";
-unsigned NewOffset =
-Replacements.getShiftedCodePosition(R.getOffset());
-unsigned NewLength = Replacements.getShiftedCodePosition(
- R.getOffset() + R.getLength()) -
- NewOffset;
-if (NewLength == R.getLength()) {
-  R = Replacement(R.getFilePath(), NewOffset, NewLength,
-  R.getReplacementText());
-  Replacements = Replacements.merge(tooling::Replacements(R));
-  CanBeApplied = true;
-  ++AppliedFixes;
-} else {
-  llvm::errs()
-  << "Can't resolve conflict, skipping the replacement.\n";
-}
-  } else {
+if (!Repl.isApplicable())
+  continue;
+SourceLocation FixLoc;
+SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
+Files.makeAbsolutePath(FixAbsoluteFilePath);
+tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
+   Repl.getLength(), Repl.getReplacementText());
+Replacements &Replacements = FileReplacements[R.getFilePath()];
+llvm::Error Err = Replacements.add(R);
+if (Err) {
+  // FIXME: Implement better conflict handling.
+  llvm::errs() << "Trying to resolve conflict: "
+   << llvm::toString(std::move(Err)) << "\n";
+  unsigned NewOffset =
+  Replacements.getShiftedCodePosition(R.getOffset());
+  unsigned NewLength = Replacements.getShiftedCodePosition(
+   R.getOffset() + R.getLength()) -
+   NewOffset;
+  if (NewLength == R.getLength()) {
+R = Replacement(R.getFilePath(), NewOffset, NewLength,
+R.getReplacementText());
+Replacements = Replacements.merge(tooling::Replacements(R));
 CanBeApplied = t

r358666 - [clang-tidy] Address post-commit comments

2019-04-18 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Thu Apr 18 07:18:14 2019
New Revision: 358666

URL: http://llvm.org/viewvc/llvm-project?rev=358666&view=rev
Log:
[clang-tidy] Address post-commit comments

Summary:
Also add a test to verify clang-tidy only apply the first alternative
fix.

Reviewers: alexfh

Subscribers: xazax.hun, cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/include/clang/Tooling/Core/Diagnostic.h

Modified: cfe/trunk/include/clang/Tooling/Core/Diagnostic.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/Core/Diagnostic.h?rev=358666&r1=358665&r2=358666&view=diff
==
--- cfe/trunk/include/clang/Tooling/Core/Diagnostic.h (original)
+++ cfe/trunk/include/clang/Tooling/Core/Diagnostic.h Thu Apr 18 07:18:14 2019
@@ -93,8 +93,8 @@ struct TranslationUnitDiagnostics {
   std::vector Diagnostics;
 };
 
-// Get the first fix to apply for this diagnostic.
-// Return nullptr if no fixes attached to the diagnostic.
+/// Get the first fix to apply for this diagnostic.
+/// \returns nullptr if no fixes are attached to the diagnostic.
 const llvm::StringMap *selectFirstFix(const Diagnostic& D);
 
 } // end namespace tooling


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


[clang-tools-extra] r358666 - [clang-tidy] Address post-commit comments

2019-04-18 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Thu Apr 18 07:18:14 2019
New Revision: 358666

URL: http://llvm.org/viewvc/llvm-project?rev=358666&view=rev
Log:
[clang-tidy] Address post-commit comments

Summary:
Also add a test to verify clang-tidy only apply the first alternative
fix.

Reviewers: alexfh

Subscribers: xazax.hun, cfe-commits

Tags: #clang

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

Added:
clang-tools-extra/trunk/test/clang-tidy/alternative-fixes.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/ClangTidy.cpp

Modified: clang-tools-extra/trunk/clang-tidy/ClangTidy.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/ClangTidy.cpp?rev=358666&r1=358665&r2=358666&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/ClangTidy.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/ClangTidy.cpp Thu Apr 18 07:18:14 2019
@@ -133,41 +133,40 @@ public:
   for (const auto &Repl : FileAndReplacements.second) {
 ++TotalFixes;
 bool CanBeApplied = false;
-if (Repl.isApplicable()) {
-  SourceLocation FixLoc;
-  SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
-  Files.makeAbsolutePath(FixAbsoluteFilePath);
-  tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
- Repl.getLength(),
- Repl.getReplacementText());
-  Replacements &Replacements = FileReplacements[R.getFilePath()];
-  llvm::Error Err = Replacements.add(R);
-  if (Err) {
-// FIXME: Implement better conflict handling.
-llvm::errs() << "Trying to resolve conflict: "
- << llvm::toString(std::move(Err)) << "\n";
-unsigned NewOffset =
-Replacements.getShiftedCodePosition(R.getOffset());
-unsigned NewLength = Replacements.getShiftedCodePosition(
- R.getOffset() + R.getLength()) -
- NewOffset;
-if (NewLength == R.getLength()) {
-  R = Replacement(R.getFilePath(), NewOffset, NewLength,
-  R.getReplacementText());
-  Replacements = Replacements.merge(tooling::Replacements(R));
-  CanBeApplied = true;
-  ++AppliedFixes;
-} else {
-  llvm::errs()
-  << "Can't resolve conflict, skipping the replacement.\n";
-}
-  } else {
+if (!Repl.isApplicable())
+  continue;
+SourceLocation FixLoc;
+SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
+Files.makeAbsolutePath(FixAbsoluteFilePath);
+tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
+   Repl.getLength(), 
Repl.getReplacementText());
+Replacements &Replacements = FileReplacements[R.getFilePath()];
+llvm::Error Err = Replacements.add(R);
+if (Err) {
+  // FIXME: Implement better conflict handling.
+  llvm::errs() << "Trying to resolve conflict: "
+   << llvm::toString(std::move(Err)) << "\n";
+  unsigned NewOffset =
+  Replacements.getShiftedCodePosition(R.getOffset());
+  unsigned NewLength = Replacements.getShiftedCodePosition(
+   R.getOffset() + R.getLength()) -
+   NewOffset;
+  if (NewLength == R.getLength()) {
+R = Replacement(R.getFilePath(), NewOffset, NewLength,
+R.getReplacementText());
+Replacements = Replacements.merge(tooling::Replacements(R));
 CanBeApplied = true;
 ++AppliedFixes;
+  } else {
+llvm::errs()
+<< "Can't resolve conflict, skipping the replacement.\n";
   }
-  FixLoc = getLocation(FixAbsoluteFilePath, Repl.getOffset());
-  FixLocations.push_back(std::make_pair(FixLoc, CanBeApplied));
+} else {
+  CanBeApplied = true;
+  ++AppliedFixes;
 }
+FixLoc = getLocation(FixAbsoluteFilePath, Repl.getOffset());
+FixLocations.push_back(std::make_pair(FixLoc, CanBeApplied));
   }
 }
   }

Added: clang-tools-extra/trunk/test/clang-tidy/alternative-fixes.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/alternative-fixes.cpp?rev=358666&view=auto
==
--- clang-tools-extra/trunk/test/clang-tidy/alternative-fixes.cpp (added

[PATCH] D60857: [clang-tidy] Address post-commit comments

2019-04-18 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC358666: [clang-tidy] Address post-commit comments (authored 
by hokein, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D60857?vs=195733&id=195734#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D60857

Files:
  include/clang/Tooling/Core/Diagnostic.h


Index: include/clang/Tooling/Core/Diagnostic.h
===
--- include/clang/Tooling/Core/Diagnostic.h
+++ include/clang/Tooling/Core/Diagnostic.h
@@ -93,8 +93,8 @@
   std::vector Diagnostics;
 };
 
-// Get the first fix to apply for this diagnostic.
-// Return nullptr if no fixes attached to the diagnostic.
+/// Get the first fix to apply for this diagnostic.
+/// \returns nullptr if no fixes are attached to the diagnostic.
 const llvm::StringMap *selectFirstFix(const Diagnostic& D);
 
 } // end namespace tooling


Index: include/clang/Tooling/Core/Diagnostic.h
===
--- include/clang/Tooling/Core/Diagnostic.h
+++ include/clang/Tooling/Core/Diagnostic.h
@@ -93,8 +93,8 @@
   std::vector Diagnostics;
 };
 
-// Get the first fix to apply for this diagnostic.
-// Return nullptr if no fixes attached to the diagnostic.
+/// Get the first fix to apply for this diagnostic.
+/// \returns nullptr if no fixes are attached to the diagnostic.
 const llvm::StringMap *selectFirstFix(const Diagnostic& D);
 
 } // end namespace tooling
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D60568: [OpenMP] Add support for registering requires directives with the runtime

2019-04-18 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea marked an inline comment as done.
gtbercea added inline comments.



Comment at: lib/Sema/SemaOpenMP.cpp:476
+   isa(CNew))) {
+SemaRef.Diag(Loc,
+ diag::err_omp_target_before_requires)

ABataev wrote:
> DSAStack usually is not used for diagnostic emission, it serves as the 
> container. Better to move the diagnostics to Act... functions.
The "bool hasDuplicateRequiresClause(ArrayRef ClauseList) const {" 
function works in a similar function as this one and does emit diagnostics. See 
a few lines above.

I need to iterate through a private member of DSAStack so I don't see how that 
can be in any other place than in DSAStack.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60568



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


[PATCH] D60568: [OpenMP] Add support for registering requires directives with the runtime

2019-04-18 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: lib/Sema/SemaOpenMP.cpp:476
+   isa(CNew))) {
+SemaRef.Diag(Loc,
+ diag::err_omp_target_before_requires)

gtbercea wrote:
> ABataev wrote:
> > DSAStack usually is not used for diagnostic emission, it serves as the 
> > container. Better to move the diagnostics to Act... functions.
> The "bool hasDuplicateRequiresClause(ArrayRef ClauseList) const 
> {" function works in a similar function as this one and does emit 
> diagnostics. See a few lines above.
> 
> I need to iterate through a private member of DSAStack so I don't see how 
> that can be in any other place than in DSAStack.
1. `hasDuplicateRequiresClause` must be fixed.
2. You can return ArrayRef and iterate over it in the Act.. 
function


Repository:
  rC Clang

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

https://reviews.llvm.org/D60568



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


[PATCH] D60868: [clang-format] Fix an assertion failure

2019-04-18 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh created this revision.
alexfh added a reviewer: krasimir.
Herald added a project: clang.

Before this patch clang-format crashed when trying to issue a diagnostic about 
an unsupported BOM. See the bug report here: 
https://bugs.llvm.org/show_bug.cgi?id=26032


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D60868

Files:
  clang/lib/Basic/SourceManager.cpp
  clang/lib/Format/Format.cpp
  clang/lib/Format/FormatTokenLexer.cpp
  clang/lib/Format/FormatTokenLexer.h
  clang/lib/Format/SortJavaScriptImports.cpp
  clang/lib/Format/TokenAnalyzer.cpp
  clang/lib/Format/TokenAnalyzer.h
  clang/test/Format/invalid-bom.cpp
  clang/tools/clang-format/ClangFormat.cpp

Index: clang/tools/clang-format/ClangFormat.cpp
===
--- clang/tools/clang-format/ClangFormat.cpp
+++ clang/tools/clang-format/ClangFormat.cpp
@@ -271,6 +271,7 @@
 
   if (SortIncludes.getNumOccurrences() != 0)
 FormatStyle->SortIncludes = SortIncludes;
+
   unsigned CursorPosition = Cursor;
   Replacements Replaces = sortIncludes(*FormatStyle, Code->getBuffer(), Ranges,
AssumedFileName, &CursorPosition);
@@ -299,13 +300,13 @@
 
 outputReplacementsXML(Replaces);
 outs() << "\n";
-  } else {
+  } else if (!Replaces.empty()) {
 IntrusiveRefCntPtr InMemoryFileSystem(
 new llvm::vfs::InMemoryFileSystem);
 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
 DiagnosticsEngine Diagnostics(
 IntrusiveRefCntPtr(new DiagnosticIDs),
-new DiagnosticOptions);
+new DiagnosticOptions, new IgnoringDiagConsumer);
 SourceManager Sources(Diagnostics, Files);
 FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files,
InMemoryFileSystem.get());
@@ -326,6 +327,9 @@
   }
   Rewrite.getEditBuffer(ID).write(outs());
 }
+  } else if (!Inplace) { // Nothing changed, but we still need to dump the input
+ // as is.
+outs() << Code->getBuffer();
   }
   return false;
 }
Index: clang/test/Format/invalid-bom.cpp
===
--- /dev/null
+++ clang/test/Format/invalid-bom.cpp
@@ -0,0 +1,3 @@
+// REQUIRES: shell
+// RUN: echo -en "\xff\xfeinput with invalid BOM" | clang-format - >%t.out
+// RUN: grep "input with invalid BOM" %t.out
Index: clang/lib/Format/TokenAnalyzer.h
===
--- clang/lib/Format/TokenAnalyzer.h
+++ clang/lib/Format/TokenAnalyzer.h
@@ -35,19 +35,18 @@
 
 class Environment {
 public:
-  // This sets up an virtual file system with file \p FileName containing the
-  // fragment \p Code. Assumes that \p Code starts at \p FirstStartColumn,
-  // that the next lines of \p Code should start at \p NextStartColumn, and
-  // that \p Code should end at \p LastStartColumn if it ends in newline.
-  // See also the documentation of clang::format::internal::reformat.
-  Environment(StringRef Code, StringRef FileName,
-  ArrayRef Ranges, unsigned FirstStartColumn = 0,
-  unsigned NextStartColumn = 0, unsigned LastStartColumn = 0);
-
-  FileID getFileID() const { return ID; }
+  static std::unique_ptr Create(StringRef Code, StringRef FileName,
+ ArrayRef Ranges,
+ unsigned FirstStartColumn = 0,
+ unsigned NextStartColumn = 0,
+ unsigned LastStartColumn = 0);
 
   const SourceManager &getSourceManager() const { return SM; }
 
+  StringRef getBufferData() const { return BufferData; }
+  SourceLocation getStartLoc() const { return SM.getLocForStartOfFile(ID); }
+  SourceLocation getEndLoc() const { return SM.getLocForEndOfFile(ID); }
+
   ArrayRef getCharRanges() const { return CharRanges; }
 
   // Returns the column at which the fragment of code managed by this
@@ -63,6 +62,16 @@
   unsigned getLastStartColumn() const { return LastStartColumn; }
 
 private:
+  // This sets up an virtual file system with file \p FileName containing the
+  // fragment \p Code. Assumes that \p Code starts at \p FirstStartColumn,
+  // that the next lines of \p Code should start at \p NextStartColumn, and
+  // that \p Code should end at \p LastStartColumn if it ends in newline.
+  // See also the documentation of clang::format::internal::reformat.
+  Environment(StringRef Code, StringRef FileName,
+  ArrayRef Ranges, unsigned FirstStartColumn,
+  unsigned NextStartColumn, unsigned LastStartColumn,
+  bool *InvalidBuffer);
+
   // This is only set if constructed from string.
   std::unique_ptr VirtualSM;
 
@@ -75,6 +84,7 @@
   unsigned FirstStartColumn;
   unsigned NextStartColumn;
   unsigned LastStartColumn;
+  StringRef BufferData;
 };
 
 class TokenAnalyzer : public U

[PATCH] D60558: [clang-format] Fix indent of trailing raw string param after newline

2019-04-18 Thread Daniel Jasper via Phabricator via cfe-commits
djasper accepted this revision.
djasper added a comment.
This revision is now accepted and ready to land.

Looks good. Thank you.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60558



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


[PATCH] D58033: Add option for emitting dbg info for call site parameters

2019-04-18 Thread Paul Robinson via Phabricator via cfe-commits
probinson added a comment.

In D58033#1470260 , @djtodoro wrote:

> @probinson @aprantl Thanks a lot for your comments!
>
> Let's clarify some things. I'm sorry about the confusion.
>
> Initial patch for the functionality can be restricted by this option (like we 
> pushed here), since **LLDB** doesn't read this type of debug info (yet).
>  The plan is, when  **LLDB** has all necessary info and we are sure that 
> everything works fine during using this info in debugging sessions, we can 
> turn it to `ON` by default.
>
> Does that make sense ? :)


Yes.  And I agree with Adrian, this should be a CC1-only option; it can be 
default-off for now and maybe debugger-tuning specific later.


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

https://reviews.llvm.org/D58033



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


[PATCH] D60827: [rename] Deduplicate symbol occurrences

2019-04-18 Thread Haojian Wu via Phabricator via cfe-commits
hokein marked an inline comment as done.
hokein added inline comments.



Comment at: clang-tools-extra/unittests/clangd/ClangdTests.cpp:1160
 
+TEST_F(ClangdVFSTest, NoDuplicatedTextEditsOnRename) {
+  MockFSProvider FS;

kadircet wrote:
> maybe put the test under clang/unittests/Rename?
I considered it before, but it is not trivial to add the test there 
unfortunately :( I'd keep the test as-is. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60827



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


[PATCH] D60568: [OpenMP] Add support for registering requires directives with the runtime

2019-04-18 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 195739.
gtbercea added a comment.

- Add const.
- Address comments.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60568

Files:
  include/clang/Basic/DiagnosticSemaKinds.td
  lib/CodeGen/CGOpenMPRuntime.cpp
  lib/CodeGen/CGOpenMPRuntime.h
  lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
  lib/CodeGen/CGOpenMPRuntimeNVPTX.h
  lib/CodeGen/CodeGenModule.cpp
  lib/Sema/SemaOpenMP.cpp
  test/OpenMP/openmp_offload_registration.cpp
  test/OpenMP/target_codegen.cpp
  test/OpenMP/target_codegen_registration.cpp

Index: test/OpenMP/target_codegen_registration.cpp
===
--- test/OpenMP/target_codegen_registration.cpp
+++ test/OpenMP/target_codegen_registration.cpp
@@ -180,10 +180,11 @@
 // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]])
 
 // We have 4 initializers, one for the 500 priority, another one for 501, or more for the default priority, and the last one for the offloading registration function.
-// CHECK: @llvm.global_ctors = appending global [4 x { i32, void ()*, i8* }] [
+// CHECK: @llvm.global_ctors = appending global [5 x { i32, void ()*, i8* }] [
 // CHECK-SAME: { i32, void ()*, i8* } { i32 500, void ()* [[P500:@[^,]+]], i8* null },
 // CHECK-SAME: { i32, void ()*, i8* } { i32 501, void ()* [[P501:@[^,]+]], i8* null },
 // CHECK-SAME: { i32, void ()*, i8* } { i32 65535, void ()* [[PMAX:@[^,]+]], i8* null },
+// CHECK-SAME: { i32, void ()*, i8* } { i32 0, void ()* @.omp_offloading.requires_reg, i8* null },
 // CHECK-SAME: { i32, void ()*, i8* } { i32 0, void ()* @[[REGFN]], i8* bitcast (void ()* @[[REGFN]] to i8*) }]
 
 // CHECK-NTARGET: @llvm.global_ctors = appending global [3   x { i32, void ()*, i8* }] [
@@ -387,6 +388,10 @@
 
 // Check registration and unregistration
 
+//CHECK: define internal void @.omp_offloading.requires_reg()
+//CHECK: call void @__tgt_register_requires(i64 1)
+//CHECK: ret void
+
 //CHECK: define internal void @[[UNREGFN:.+]](i8*)
 //CHECK-SAME: comdat($[[REGFN]]) {
 //CHECK: call i32 @__tgt_unregister_lib([[DSCTY]]* [[DESC]])
@@ -432,31 +437,31 @@
 
 // Check metadata is properly generated:
 // CHECK: !omp_offload.info = !{!{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID:-?[0-9]+]], i32 [[FILEID:-?[0-9]+]], !"_ZN2SB3fooEv", i32 216, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SDD1Ev", i32 266, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SEC1Ev", i32 282, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SED1Ev", i32 288, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EE3fooEv", i32 299, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EEC1Ev", i32 305, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_Z3bari", i32 427, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EED1Ev", i32 311, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EEC1Ev", i32 305, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EED1Ev", i32 311, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EE3fooEv", i32 299, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SCC1Ev", i32 241, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID:-?[0-9]+]], i32 [[FILEID:-?[0-9]+]], !"_ZN2SB3fooEv", i32 217, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SDD1Ev", i32 267, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SEC1Ev", i32 283, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SED1Ev", i32 289, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EE3fooEv", i32 300, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EEC1Ev", i32 306, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_Z3bari", i32 432, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EED1Ev", i32 312, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EEC1Ev", i32 306, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EED1Ev", i32 312, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EE3fooEv", i32 300, i32 {{[0-9]+}}}
+// CHECK-DAG: =

[PATCH] D60568: [OpenMP] Add support for registering requires directives with the runtime

2019-04-18 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: include/clang/Basic/DiagnosticSemaKinds.td:9135
   "%0 clause previously used here">;
+def err_omp_target_before_requires : Error <
+  "Target region encountered before requires directive with %0 clause.">;

Split the patch, sema part must be separate.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60568



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


[PATCH] D60845: [VerifyDiagnosticConsumer] Document -verify= in doxygen

2019-04-18 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny updated this revision to Diff 195742.
jdenny added a comment.

Clarify the behavior of multiple -verify options.


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

https://reviews.llvm.org/D60845

Files:
  clang/include/clang/Frontend/VerifyDiagnosticConsumer.h


Index: clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
===
--- clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
+++ clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
@@ -33,7 +33,33 @@
 /// markers in the input source to check that all the emitted diagnostics match
 /// those expected.
 ///
-/// USING THE DIAGNOSTIC CHECKER:
+/// INVOKING THE DIAGNOSTIC CHECKER:
+///
+/// VerifyDiagnosticConsumer is typically invoked via the "-verify" option to
+/// "clang -cc1".  "-verify" is equivalent to "-verify=expected", so all
+/// diagnostics are typically specified with the prefix "expected".  For
+/// example:
+///
+/// \code
+///   int A = B; // expected-error {{use of undeclared identifier 'B'}}
+/// \endcode
+///
+/// Custom prefixes can be specified as a comma-separated sequence.  Each
+/// prefix must start with a letter and contain only alphanumeric characters,
+/// hyphens, and underscores.  For example, given just "-verify=foo,bar",
+/// the above diagnostic would be ignored, but the following diagnostics would
+/// be recognized:
+///
+/// \code
+///   int A = B; // foo-error {{use of undeclared identifier 'B'}}
+///   int C = D; // bar-error {{use of undeclared identifier 'D'}}
+/// \endcode
+///
+/// Multiple occurrences accumulate prefixes.  For example,
+/// "-verify -verify=foo,bar -verify=baz" is equivalent to
+/// "-verify=expected,foo,bar,baz".
+///
+/// SPECIFYING DIAGNOSTICS:
 ///
 /// Indicating that a line expects an error or a warning is simple. Put a
 /// comment on the line that has the diagnostic, use:


Index: clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
===
--- clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
+++ clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
@@ -33,7 +33,33 @@
 /// markers in the input source to check that all the emitted diagnostics match
 /// those expected.
 ///
-/// USING THE DIAGNOSTIC CHECKER:
+/// INVOKING THE DIAGNOSTIC CHECKER:
+///
+/// VerifyDiagnosticConsumer is typically invoked via the "-verify" option to
+/// "clang -cc1".  "-verify" is equivalent to "-verify=expected", so all
+/// diagnostics are typically specified with the prefix "expected".  For
+/// example:
+///
+/// \code
+///   int A = B; // expected-error {{use of undeclared identifier 'B'}}
+/// \endcode
+///
+/// Custom prefixes can be specified as a comma-separated sequence.  Each
+/// prefix must start with a letter and contain only alphanumeric characters,
+/// hyphens, and underscores.  For example, given just "-verify=foo,bar",
+/// the above diagnostic would be ignored, but the following diagnostics would
+/// be recognized:
+///
+/// \code
+///   int A = B; // foo-error {{use of undeclared identifier 'B'}}
+///   int C = D; // bar-error {{use of undeclared identifier 'D'}}
+/// \endcode
+///
+/// Multiple occurrences accumulate prefixes.  For example,
+/// "-verify -verify=foo,bar -verify=baz" is equivalent to
+/// "-verify=expected,foo,bar,baz".
+///
+/// SPECIFYING DIAGNOSTICS:
 ///
 /// Indicating that a line expects an error or a warning is simple. Put a
 /// comment on the line that has the diagnostic, use:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D60845: [VerifyDiagnosticConsumer] Document -verify= in doxygen

2019-04-18 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny added a comment.

Thanks for the accepts.

In D60845#1470986 , @NoQ wrote:

> In D60845#1470980 , @Charusso wrote:
>
> > I really like live working examples, I hope not just me. Could you link 
> > https://github.com/llvm/llvm-project/blob/master/clang/test/Analysis/use-after-move.cpp
> >  as well as a live example?
>
>
> I'd rather reserve an ability for myself to move the test around without 
> breaking links all over the place. Live examples are easy to grep for as soon 
> as you know what to grep for.


Agreed.

In D60845#1471002 , @rsmith wrote:

> I've seen a few projects outside of clang use `-verify` mode for their own 
> testing of various things.


Interesting.  What's an example?


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

https://reviews.llvm.org/D60845



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


r358674 - [Serialization] Stable serialization order for OpenCLTypeExtMap and OpenCLDeclExtMap

2019-04-18 Thread Bruno Ricci via cfe-commits
Author: brunoricci
Date: Thu Apr 18 08:13:27 2019
New Revision: 358674

URL: http://llvm.org/viewvc/llvm-project?rev=358674&view=rev
Log:
[Serialization] Stable serialization order for OpenCLTypeExtMap and 
OpenCLDeclExtMap

Sort the elements of Sema::OpenCLTypeExtMap and Sema::OpenCLDeclExtMap
by TypeIDs and DeclIDs to guarantee a stable serialization order.

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

Reviewed By: Anastasia

Reviewers: Anastasia, lebedev.ri


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

Modified: cfe/trunk/lib/Serialization/ASTWriter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Serialization/ASTWriter.cpp?rev=358674&r1=358673&r2=358674&view=diff
==
--- cfe/trunk/lib/Serialization/ASTWriter.cpp (original)
+++ cfe/trunk/lib/Serialization/ASTWriter.cpp Thu Apr 18 08:13:27 2019
@@ -4278,14 +4278,32 @@ void ASTWriter::WriteOpenCLExtensionType
   if (!SemaRef.Context.getLangOpts().OpenCL)
 return;
 
+  // Sort the elements of the map OpenCLTypeExtMap by TypeIDs,
+  // without copying them.
+  const llvm::DenseMap> &OpenCLTypeExtMap =
+  SemaRef.OpenCLTypeExtMap;
+  using ElementTy = std::pair *>;
+  llvm::SmallVector StableOpenCLTypeExtMap;
+  StableOpenCLTypeExtMap.reserve(OpenCLTypeExtMap.size());
+
+  for (const auto &I : OpenCLTypeExtMap)
+StableOpenCLTypeExtMap.emplace_back(
+getTypeID(I.first->getCanonicalTypeInternal()), &I.second);
+
+  auto CompareByTypeID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
+return E1.first < E2.first;
+  };
+  llvm::sort(StableOpenCLTypeExtMap, CompareByTypeID);
+
   RecordData Record;
-  for (const auto &I : SemaRef.OpenCLTypeExtMap) {
-Record.push_back(
-static_cast(getTypeID(I.first->getCanonicalTypeInternal(;
-Record.push_back(I.second.size());
-for (auto Ext : I.second)
+  for (const ElementTy &E : StableOpenCLTypeExtMap) {
+Record.push_back(E.first); // TypeID
+const std::set *ExtSet = E.second;
+Record.push_back(static_cast(ExtSet->size()));
+for (const std::string &Ext : *ExtSet)
   AddString(Ext, Record);
   }
+
   Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
 }
 
@@ -4293,13 +4311,31 @@ void ASTWriter::WriteOpenCLExtensionDecl
   if (!SemaRef.Context.getLangOpts().OpenCL)
 return;
 
+  // Sort the elements of the map OpenCLDeclExtMap by DeclIDs,
+  // without copying them.
+  const llvm::DenseMap> &OpenCLDeclExtMap =
+  SemaRef.OpenCLDeclExtMap;
+  using ElementTy = std::pair *>;
+  llvm::SmallVector StableOpenCLDeclExtMap;
+  StableOpenCLDeclExtMap.reserve(OpenCLDeclExtMap.size());
+
+  for (const auto &I : OpenCLDeclExtMap)
+StableOpenCLDeclExtMap.emplace_back(getDeclID(I.first), &I.second);
+
+  auto CompareByDeclID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
+return E1.first < E2.first;
+  };
+  llvm::sort(StableOpenCLDeclExtMap, CompareByDeclID);
+
   RecordData Record;
-  for (const auto &I : SemaRef.OpenCLDeclExtMap) {
-Record.push_back(getDeclID(I.first));
-Record.push_back(static_cast(I.second.size()));
-for (auto Ext : I.second)
+  for (const ElementTy &E : StableOpenCLDeclExtMap) {
+Record.push_back(E.first); // DeclID
+const std::set *ExtSet = E.second;
+Record.push_back(static_cast(ExtSet->size()));
+for (const std::string &Ext : *ExtSet)
   AddString(Ext, Record);
   }
+
   Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
 }
 


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


[PATCH] D60835: [Serialization] Stable serialization order for OpenCLTypeExtMap and OpenCLDeclExtMap

2019-04-18 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL358674: [Serialization] Stable serialization order for 
OpenCLTypeExtMap and… (authored by brunoricci, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D60835?vs=195627&id=195744#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D60835

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


Index: cfe/trunk/lib/Serialization/ASTWriter.cpp
===
--- cfe/trunk/lib/Serialization/ASTWriter.cpp
+++ cfe/trunk/lib/Serialization/ASTWriter.cpp
@@ -4278,14 +4278,32 @@
   if (!SemaRef.Context.getLangOpts().OpenCL)
 return;
 
+  // Sort the elements of the map OpenCLTypeExtMap by TypeIDs,
+  // without copying them.
+  const llvm::DenseMap> &OpenCLTypeExtMap =
+  SemaRef.OpenCLTypeExtMap;
+  using ElementTy = std::pair *>;
+  llvm::SmallVector StableOpenCLTypeExtMap;
+  StableOpenCLTypeExtMap.reserve(OpenCLTypeExtMap.size());
+
+  for (const auto &I : OpenCLTypeExtMap)
+StableOpenCLTypeExtMap.emplace_back(
+getTypeID(I.first->getCanonicalTypeInternal()), &I.second);
+
+  auto CompareByTypeID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
+return E1.first < E2.first;
+  };
+  llvm::sort(StableOpenCLTypeExtMap, CompareByTypeID);
+
   RecordData Record;
-  for (const auto &I : SemaRef.OpenCLTypeExtMap) {
-Record.push_back(
-static_cast(getTypeID(I.first->getCanonicalTypeInternal(;
-Record.push_back(I.second.size());
-for (auto Ext : I.second)
+  for (const ElementTy &E : StableOpenCLTypeExtMap) {
+Record.push_back(E.first); // TypeID
+const std::set *ExtSet = E.second;
+Record.push_back(static_cast(ExtSet->size()));
+for (const std::string &Ext : *ExtSet)
   AddString(Ext, Record);
   }
+
   Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
 }
 
@@ -4293,13 +4311,31 @@
   if (!SemaRef.Context.getLangOpts().OpenCL)
 return;
 
+  // Sort the elements of the map OpenCLDeclExtMap by DeclIDs,
+  // without copying them.
+  const llvm::DenseMap> &OpenCLDeclExtMap =
+  SemaRef.OpenCLDeclExtMap;
+  using ElementTy = std::pair *>;
+  llvm::SmallVector StableOpenCLDeclExtMap;
+  StableOpenCLDeclExtMap.reserve(OpenCLDeclExtMap.size());
+
+  for (const auto &I : OpenCLDeclExtMap)
+StableOpenCLDeclExtMap.emplace_back(getDeclID(I.first), &I.second);
+
+  auto CompareByDeclID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
+return E1.first < E2.first;
+  };
+  llvm::sort(StableOpenCLDeclExtMap, CompareByDeclID);
+
   RecordData Record;
-  for (const auto &I : SemaRef.OpenCLDeclExtMap) {
-Record.push_back(getDeclID(I.first));
-Record.push_back(static_cast(I.second.size()));
-for (auto Ext : I.second)
+  for (const ElementTy &E : StableOpenCLDeclExtMap) {
+Record.push_back(E.first); // DeclID
+const std::set *ExtSet = E.second;
+Record.push_back(static_cast(ExtSet->size()));
+for (const std::string &Ext : *ExtSet)
   AddString(Ext, Record);
   }
+
   Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
 }
 


Index: cfe/trunk/lib/Serialization/ASTWriter.cpp
===
--- cfe/trunk/lib/Serialization/ASTWriter.cpp
+++ cfe/trunk/lib/Serialization/ASTWriter.cpp
@@ -4278,14 +4278,32 @@
   if (!SemaRef.Context.getLangOpts().OpenCL)
 return;
 
+  // Sort the elements of the map OpenCLTypeExtMap by TypeIDs,
+  // without copying them.
+  const llvm::DenseMap> &OpenCLTypeExtMap =
+  SemaRef.OpenCLTypeExtMap;
+  using ElementTy = std::pair *>;
+  llvm::SmallVector StableOpenCLTypeExtMap;
+  StableOpenCLTypeExtMap.reserve(OpenCLTypeExtMap.size());
+
+  for (const auto &I : OpenCLTypeExtMap)
+StableOpenCLTypeExtMap.emplace_back(
+getTypeID(I.first->getCanonicalTypeInternal()), &I.second);
+
+  auto CompareByTypeID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
+return E1.first < E2.first;
+  };
+  llvm::sort(StableOpenCLTypeExtMap, CompareByTypeID);
+
   RecordData Record;
-  for (const auto &I : SemaRef.OpenCLTypeExtMap) {
-Record.push_back(
-static_cast(getTypeID(I.first->getCanonicalTypeInternal(;
-Record.push_back(I.second.size());
-for (auto Ext : I.second)
+  for (const ElementTy &E : StableOpenCLTypeExtMap) {
+Record.push_back(E.first); // TypeID
+const std::set *ExtSet = E.second;
+Record.push_back(static_cast(ExtSet->size()));
+for (const std::string &Ext : *ExtSet)
   AddString(Ext, Record);
   }
+
   Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
 }
 
@@ -4293,13 +4311,31 @@
   if (!SemaRef.Context.getLangOpts().OpenCL)
 return;
 
+  // Sort the elements of the map OpenCLDeclExtMap by DeclIDs,
+  // without copying them.
+  const llvm::DenseMap> &OpenCLDeclEx

[clang-tools-extra] r358675 - [clangd] Support relatedInformation in diagnostics.

2019-04-18 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Thu Apr 18 08:17:07 2019
New Revision: 358675

URL: http://llvm.org/viewvc/llvm-project?rev=358675&view=rev
Log:
[clangd] Support relatedInformation in diagnostics.

Summary: We already have the structure internally, we just need to expose it.

Reviewers: ilya-biryukov

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

Tags: #clang

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

Added:
clang-tools-extra/trunk/test/clangd/diagnostics-notes.test
Modified:
clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
clang-tools-extra/trunk/clangd/Diagnostics.cpp
clang-tools-extra/trunk/clangd/Diagnostics.h
clang-tools-extra/trunk/clangd/Protocol.cpp
clang-tools-extra/trunk/clangd/Protocol.h
clang-tools-extra/trunk/unittests/clangd/DiagnosticsTests.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp?rev=358675&r1=358674&r2=358675&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp Thu Apr 18 08:17:07 2019
@@ -348,6 +348,8 @@ void ClangdLSPServer::onInitialize(const
   CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
   DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
   DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
+  DiagOpts.EmitRelatedLocations =
+  Params.capabilities.DiagnosticRelatedInformation;
   if (Params.capabilities.WorkspaceSymbolKinds)
 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
   if (Params.capabilities.CompletionItemKinds)

Modified: clang-tools-extra/trunk/clangd/Diagnostics.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Diagnostics.cpp?rev=358675&r1=358674&r2=358675&view=diff
==
--- clang-tools-extra/trunk/clangd/Diagnostics.cpp (original)
+++ clang-tools-extra/trunk/clangd/Diagnostics.cpp Thu Apr 18 08:17:07 2019
@@ -10,6 +10,7 @@
 #include "../clang-tidy/ClangTidyDiagnosticConsumer.h"
 #include "Compiler.h"
 #include "Logger.h"
+#include "Protocol.h"
 #include "SourceCode.h"
 #include "clang/Basic/AllDiagnostics.h"
 #include "clang/Basic/DiagnosticIDs.h"
@@ -175,9 +176,7 @@ std::string capitalize(std::string Messa
 }
 
 /// Returns a message sent to LSP for the main diagnostic in \p D.
-/// The message includes all the notes with their corresponding locations.
-/// However, notes with fix-its are excluded as those usually only contain a
-/// fix-it message and just add noise if included in the message for 
diagnostic.
+/// This message may include notes, if they're not emited in some other way.
 /// Example output:
 ///
 /// no matching function for call to 'foo'
@@ -186,29 +185,34 @@ std::string capitalize(std::string Messa
 ///
 /// dir1/dir2/dir3/../../dir4/header.h:12:23
 /// note: candidate function not viable: requires 3 arguments
-std::string mainMessage(const Diag &D, bool DisplayFixesCount) {
+std::string mainMessage(const Diag &D, const ClangdDiagnosticOptions &Opts) {
   std::string Result;
   llvm::raw_string_ostream OS(Result);
   OS << D.Message;
-  if (DisplayFixesCount && !D.Fixes.empty())
+  if (Opts.DisplayFixesCount && !D.Fixes.empty())
 OS << " (" << (D.Fixes.size() > 1 ? "fixes" : "fix") << " available)";
-  for (auto &Note : D.Notes) {
-OS << "\n\n";
-printDiag(OS, Note);
-  }
+  // If notes aren't emitted as structured info, add them to the message.
+  if (!Opts.EmitRelatedLocations)
+for (auto &Note : D.Notes) {
+  OS << "\n\n";
+  printDiag(OS, Note);
+}
   OS.flush();
   return capitalize(std::move(Result));
 }
 
 /// Returns a message sent to LSP for the note of the main diagnostic.
-/// The message includes the main diagnostic to provide the necessary context
-/// for the user to understand the note.
-std::string noteMessage(const Diag &Main, const DiagBase &Note) {
+std::string noteMessage(const Diag &Main, const DiagBase &Note,
+const ClangdDiagnosticOptions &Opts) {
   std::string Result;
   llvm::raw_string_ostream OS(Result);
   OS << Note.Message;
-  OS << "\n\n";
-  printDiag(OS, Main);
+  // If the client doesn't support structured links between the note and the
+  // original diagnostic, then emit the main diagnostic to give context.
+  if (!Opts.EmitRelatedLocations) {
+OS << "\n\n";
+printDiag(OS, Main);
+  }
   OS.flush();
   return capitalize(std::move(Result));
 }
@@ -275,39 +279,54 @@ void toLSPDiags(
 return Res;
   };
 
-  {
-clangd::Diagnostic Main = FillBasicFields(D);
-Main.message = mainMessage(D, Opts.DisplayFixesCount);
-if (!D.Name.empty())
-  Main.code = D.Name;
-switch (D.Source) {
-case Diag::Clang:
- 

[PATCH] D60267: [clangd] Support relatedInformation in diagnostics.

2019-04-18 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL358675: [clangd] Support relatedInformation in diagnostics. 
(authored by sammccall, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

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

https://reviews.llvm.org/D60267

Files:
  clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
  clang-tools-extra/trunk/clangd/Diagnostics.cpp
  clang-tools-extra/trunk/clangd/Diagnostics.h
  clang-tools-extra/trunk/clangd/Protocol.cpp
  clang-tools-extra/trunk/clangd/Protocol.h
  clang-tools-extra/trunk/test/clangd/diagnostics-notes.test
  clang-tools-extra/trunk/unittests/clangd/DiagnosticsTests.cpp

Index: clang-tools-extra/trunk/test/clangd/diagnostics-notes.test
===
--- clang-tools-extra/trunk/test/clangd/diagnostics-notes.test
+++ clang-tools-extra/trunk/test/clangd/diagnostics-notes.test
@@ -0,0 +1,48 @@
+# RUN: clangd -lit-test < %s | FileCheck -strict-whitespace %s
+{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{"textDocument":{"publishDiagnostics":{"relatedInformation":true}}},"trace":"off"}}
+---
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///foo.cc","languageId":"cpp","version":1,"text":"int x;\nint x;"}}}
+#  CHECK:  "method": "textDocument/publishDiagnostics",
+# CHECK-NEXT:  "params": {
+# CHECK-NEXT:"diagnostics": [
+# CHECK-NEXT:  {
+# CHECK-NEXT:"code": "redefinition",
+# CHECK-NEXT:"message": "Redefinition of 'x'",
+# CHECK-NEXT:"range": {
+# CHECK-NEXT:  "end": {
+# CHECK-NEXT:"character": 5,
+# CHECK-NEXT:"line": 1
+# CHECK-NEXT:  },
+# CHECK-NEXT:  "start": {
+# CHECK-NEXT:"character": 4,
+# CHECK-NEXT:"line": 1
+# CHECK-NEXT:  }
+# CHECK-NEXT:},
+# CHECK-NEXT:"relatedInformation": [
+# CHECK-NEXT:  {
+# CHECK-NEXT:"location": {
+# CHECK-NEXT:  "range": {
+# CHECK-NEXT:"end": {
+# CHECK-NEXT:  "character": 5,
+# CHECK-NEXT:  "line": 0
+# CHECK-NEXT:},
+# CHECK-NEXT:"start": {
+# CHECK-NEXT:  "character": 4,
+# CHECK-NEXT:  "line": 0
+# CHECK-NEXT:}
+# CHECK-NEXT:  },
+# CHECK-NEXT:  "uri": "{{.*}}foo.cc"
+# CHECK-NEXT:},
+# CHECK-NEXT:"message": "Previous definition is here"
+# CHECK-NEXT:  }
+# CHECK-NEXT:],
+# CHECK-NEXT:"severity": 1,
+# CHECK-NEXT:"source": "clang"
+# CHECK-NEXT:  }
+# CHECK-NEXT:],
+# CHECK-NEXT:"uri": "file://{{.*}}/foo.cc"
+# CHECK-NEXT:  }
+---
+{"jsonrpc":"2.0","id":5,"method":"shutdown"}
+---
+{"jsonrpc":"2.0","method":"exit"}
Index: clang-tools-extra/trunk/unittests/clangd/DiagnosticsTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/DiagnosticsTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/DiagnosticsTests.cpp
@@ -8,10 +8,14 @@
 
 #include "Annotations.h"
 #include "ClangdUnit.h"
+#include "Diagnostics.h"
+#include "Protocol.h"
 #include "SourceCode.h"
 #include "TestIndex.h"
+#include "TestFS.h"
 #include "TestTU.h"
 #include "index/MemIndex.h"
+#include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticSema.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include "gmock/gmock.h"
@@ -55,8 +59,12 @@
 
 MATCHER_P(EqualToLSPDiag, LSPDiag,
   "LSP diagnostic " + llvm::to_string(LSPDiag)) {
-  return std::tie(arg.range, arg.severity, arg.message) ==
- std::tie(LSPDiag.range, LSPDiag.severity, LSPDiag.message);
+  if (toJSON(arg) != toJSON(LSPDiag)) {
+*result_listener << llvm::formatv("expected:\n{0:2}\ngot\n{1:2}",
+  toJSON(LSPDiag), toJSON(arg)).str();
+return false;
+  }
+  return true;
 }
 
 MATCHER_P(DiagSource, S, "") { return arg.Source == S; }
@@ -248,6 +256,11 @@
 }
 
 TEST(DiagnosticsTest, ToLSP) {
+  URIForFile MainFile =
+  URIForFile::canonicalize(testPath("foo/bar/main.cpp"), "");
+  URIForFile HeaderFile =
+  URIForFile::canonicalize(testPath("foo/bar/header.h"), "");
+
   clangd::Diag D;
   D.ID = clang::diag::err_enum_class_reference;
   D.Name = "enum_class_reference";
@@ -257,6 +270,7 @@
   D.InsideMainFile = true;
   D.Severity = DiagnosticsEngine::Error;
   D.File = "foo/bar/main.cpp";
+  D.AbsFile = MainFile.file();
 
   clangd::Note NoteInMain;
   NoteInMain.Message = "declared somewhere in the main file";
@@ -264,6 +278,8 @@
   NoteInMain.Severity = DiagnosticsEngine::Remark;
   NoteInMain.File = "../foo/bar/main.cpp";
   NoteInMain.InsideMainFile = true;
+  NoteInMain.AbsFile = MainFile.file()

[PATCH] D59457: [analyzer][NFC] Use capital variable names, move methods out-of-line, rename some in CheckerRegistry

2019-04-18 Thread Kristóf Umann via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL358676: [analyzer][NFC] Use capital variable names, move 
methods out-of-line, rename… (authored by Szelethus, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D59457?vs=190970&id=195747#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D59457

Files:
  cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
  cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistration.cpp
  cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp

Index: cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
===
--- cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
+++ cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
@@ -164,40 +164,23 @@
 
   /// Makes the checker with the full name \p fullName depends on the checker
   /// called \p dependency.
-  void addDependency(StringRef fullName, StringRef dependency) {
-auto CheckerThatNeedsDeps =
-   [&fullName](const CheckerInfo &Chk) { return Chk.FullName == fullName; };
-auto Dependency =
-  [&dependency](const CheckerInfo &Chk) {
-return Chk.FullName == dependency;
-  };
-
-auto CheckerIt = llvm::find_if(Checkers, CheckerThatNeedsDeps);
-assert(CheckerIt != Checkers.end() &&
-   "Failed to find the checker while attempting to set up it's "
-   "dependencies!");
-
-auto DependencyIt = llvm::find_if(Checkers, Dependency);
-assert(DependencyIt != Checkers.end() &&
-   "Failed to find the dependency of a checker!");
-
-CheckerIt->Dependencies.push_back(&*DependencyIt);
-  }
+  void addDependency(StringRef FullName, StringRef Dependency);
 
   // FIXME: This *really* should be added to the frontend flag descriptions.
   /// Initializes a CheckerManager by calling the initialization functions for
   /// all checkers specified by the given CheckerOptInfo list. The order of this
   /// list is significant; later options can be used to reverse earlier ones.
   /// This can be used to exclude certain checkers in an included package.
-  void initializeManager(CheckerManager &mgr) const;
+  void initializeManager(CheckerManager &CheckerMgr) const;
 
   /// Check if every option corresponds to a specific checker or package.
   void validateCheckerOptions() const;
 
   /// Prints the name and description of all checkers in this registry.
   /// This output is not intended to be machine-parseable.
-  void printHelp(raw_ostream &out, size_t maxNameChars = 30) const;
-  void printList(raw_ostream &out) const;
+  void printCheckerWithDescList(raw_ostream &Out,
+size_t MaxNameChars = 30) const;
+  void printEnabledCheckerList(raw_ostream &Out) const;
 
 private:
   /// Collect all enabled checkers. The returned container preserves the order
@@ -211,7 +194,7 @@
   CheckerInfoListRange getMutableCheckersForCmdLineArg(StringRef CmdLineArg);
 
   CheckerInfoList Checkers;
-  llvm::StringMap Packages;
+  llvm::StringMap PackageSizes;
 
   DiagnosticsEngine &Diags;
   AnalyzerOptions &AnOpts;
Index: cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp
@@ -28,35 +28,41 @@
 
 using RegisterCheckersFn = void (*)(CheckerRegistry &);
 
-static bool isCompatibleAPIVersion(const char *versionString) {
-  // If the version string is null, it's not an analyzer plugin.
-  if (!versionString)
+static bool isCompatibleAPIVersion(const char *VersionString) {
+  // If the version string is null, its not an analyzer plugin.
+  if (!VersionString)
 return false;
 
   // For now, none of the static analyzer API is considered stable.
   // Versions must match exactly.
-  return strcmp(versionString, CLANG_ANALYZER_API_VERSION_STRING) == 0;
+  return strcmp(VersionString, CLANG_ANALYZER_API_VERSION_STRING) == 0;
 }
 
-static bool checkerNameLT(const CheckerRegistry::CheckerInfo &a,
-  const CheckerRegistry::CheckerInfo &b) {
-  return a.FullName < b.FullName;
-}
+namespace {
+template 
+struct FullNameLT {
+  bool operator()(const T &Lhs, const T &Rhs) {
+return Lhs.FullName < Rhs.FullName;
+  }
+};
+
+using CheckerNameLT = FullNameLT;
+} // end of anonymous namespace
 
 static constexpr char PackageSeparator = '.';
 
-static bool isInPackage(const CheckerRegistry::CheckerInfo &checker,
-StringRef packageName) {
+static bool isInPackage(const CheckerRegistry::CheckerInfo &Checker,
+StringRef PackageName) {
   // Does the checker's full name have the package as a prefix?
-  if (!che

r358676 - [analyzer][NFC] Use capital variable names, move methods out-of-line, rename some in CheckerRegistry

2019-04-18 Thread Kristof Umann via cfe-commits
Author: szelethus
Date: Thu Apr 18 08:19:16 2019
New Revision: 358676

URL: http://llvm.org/viewvc/llvm-project?rev=358676&view=rev
Log:
[analyzer][NFC] Use capital variable names, move methods out-of-line, rename 
some in CheckerRegistry

There are barely any lines I haven't changed in these files, so I think I could
might as well leave it in an LLVM coding style conforming state. I also renamed
2 functions and moved addDependency out of line to ease on followup patches.

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

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistration.cpp
cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h?rev=358676&r1=358675&r2=358676&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h Thu Apr 
18 08:19:16 2019
@@ -164,40 +164,23 @@ public:
 
   /// Makes the checker with the full name \p fullName depends on the checker
   /// called \p dependency.
-  void addDependency(StringRef fullName, StringRef dependency) {
-auto CheckerThatNeedsDeps =
-   [&fullName](const CheckerInfo &Chk) { return Chk.FullName == fullName; 
};
-auto Dependency =
-  [&dependency](const CheckerInfo &Chk) {
-return Chk.FullName == dependency;
-  };
-
-auto CheckerIt = llvm::find_if(Checkers, CheckerThatNeedsDeps);
-assert(CheckerIt != Checkers.end() &&
-   "Failed to find the checker while attempting to set up it's "
-   "dependencies!");
-
-auto DependencyIt = llvm::find_if(Checkers, Dependency);
-assert(DependencyIt != Checkers.end() &&
-   "Failed to find the dependency of a checker!");
-
-CheckerIt->Dependencies.push_back(&*DependencyIt);
-  }
+  void addDependency(StringRef FullName, StringRef Dependency);
 
   // FIXME: This *really* should be added to the frontend flag descriptions.
   /// Initializes a CheckerManager by calling the initialization functions for
   /// all checkers specified by the given CheckerOptInfo list. The order of 
this
   /// list is significant; later options can be used to reverse earlier ones.
   /// This can be used to exclude certain checkers in an included package.
-  void initializeManager(CheckerManager &mgr) const;
+  void initializeManager(CheckerManager &CheckerMgr) const;
 
   /// Check if every option corresponds to a specific checker or package.
   void validateCheckerOptions() const;
 
   /// Prints the name and description of all checkers in this registry.
   /// This output is not intended to be machine-parseable.
-  void printHelp(raw_ostream &out, size_t maxNameChars = 30) const;
-  void printList(raw_ostream &out) const;
+  void printCheckerWithDescList(raw_ostream &Out,
+size_t MaxNameChars = 30) const;
+  void printEnabledCheckerList(raw_ostream &Out) const;
 
 private:
   /// Collect all enabled checkers. The returned container preserves the order
@@ -211,7 +194,7 @@ private:
   CheckerInfoListRange getMutableCheckersForCmdLineArg(StringRef CmdLineArg);
 
   CheckerInfoList Checkers;
-  llvm::StringMap Packages;
+  llvm::StringMap PackageSizes;
 
   DiagnosticsEngine &Diags;
   AnalyzerOptions &AnOpts;

Modified: cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistration.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistration.cpp?rev=358676&r1=358675&r2=358676&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistration.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistration.cpp Thu Apr 18 
08:19:16 2019
@@ -50,7 +50,8 @@ void ento::printCheckerHelp(raw_ostream
   out << "OVERVIEW: Clang Static Analyzer Checkers List\n\n";
   out << "USAGE: -analyzer-checker \n\n";
 
-  CheckerRegistry(plugins, diags, anopts, langOpts).printHelp(out);
+  CheckerRegistry(plugins, diags, anopts, langOpts)
+  .printCheckerWithDescList(out);
 }
 
 void ento::printEnabledCheckerList(raw_ostream &out,
@@ -60,7 +61,8 @@ void ento::printEnabledCheckerList(raw_o
const LangOptions &langOpts) {
   out << "OVERVIEW: Clang Static Analyzer Enabled Checkers List\n\n";
 
-  CheckerRegistry(plugins, diags, anopts, langOpts).printList(out);
+  CheckerRegistry(plugins, diags, anopts, langOpts)
+  .printEnabledCheckerList(out);
 }
 
 void ento::printAnalyzerConfigList(raw_ostream &out) {

Modified: cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyze

[PATCH] D60873: [clang][HeaderSuggestion] Handle the case of dotdot with an absolute path

2019-04-18 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: sammccall.
Herald added subscribers: cfe-commits, arphaman, jkorous, ioeric, ilya-biryukov.
Herald added a project: clang.

Include insertion in clangd was inserting absolute paths when the
include directory was an absolute path with a double dot. This patch makes sure
double dots are handled both with absolute and relative paths.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D60873

Files:
  clang-tools-extra/unittests/clangd/HeadersTests.cpp
  clang/lib/Lex/HeaderSearch.cpp
  clang/unittests/Lex/HeaderSearchTest.cpp


Index: clang/unittests/Lex/HeaderSearchTest.cpp
===
--- clang/unittests/Lex/HeaderSearchTest.cpp
+++ clang/unittests/Lex/HeaderSearchTest.cpp
@@ -91,5 +91,12 @@
 "z");
 }
 
+TEST_F(HeaderSearchTest, DotDotsWithAbsPath) {
+  addSearchDir("/x/../y/");
+  EXPECT_EQ(Search.suggestPathToFileForDiagnostics("/y/z",
+   /*WorkingDir=*/""),
+"z");
+}
+
 } // namespace
 } // namespace clang
Index: clang/lib/Lex/HeaderSearch.cpp
===
--- clang/lib/Lex/HeaderSearch.cpp
+++ clang/lib/Lex/HeaderSearch.cpp
@@ -1685,11 +1685,10 @@
 
 StringRef Dir = SearchDirs[I].getDir()->getName();
 llvm::SmallString<32> DirPath(Dir.begin(), Dir.end());
-if (!WorkingDir.empty() && !path::is_absolute(Dir)) {
+if (!WorkingDir.empty() && !path::is_absolute(Dir))
   fs::make_absolute(WorkingDir, DirPath);
-  path::remove_dots(DirPath, /*remove_dot_dot=*/true);
-  Dir = DirPath;
-}
+path::remove_dots(DirPath, /*remove_dot_dot=*/true);
+Dir = DirPath;
 for (auto NI = path::begin(File), NE = path::end(File),
   DI = path::begin(Dir), DE = path::end(Dir);
  /*termination condition in loop*/; ++NI, ++DI) {
Index: clang-tools-extra/unittests/clangd/HeadersTests.cpp
===
--- clang-tools-extra/unittests/clangd/HeadersTests.cpp
+++ clang-tools-extra/unittests/clangd/HeadersTests.cpp
@@ -213,6 +213,11 @@
 TEST_F(HeadersTest, ShortenedInclude) {
   std::string BarHeader = testPath("sub/bar.h");
   EXPECT_EQ(calculate(BarHeader), "\"bar.h\"");
+
+  SearchDirArg = (llvm::Twine("-I") + Subdir + "/..").str();
+  CDB.ExtraClangFlags = {SearchDirArg.c_str()};
+  BarHeader = testPath("sub/bar.h");
+  EXPECT_EQ(calculate(BarHeader), "\"sub/bar.h\"");
 }
 
 TEST_F(HeadersTest, NotShortenedInclude) {


Index: clang/unittests/Lex/HeaderSearchTest.cpp
===
--- clang/unittests/Lex/HeaderSearchTest.cpp
+++ clang/unittests/Lex/HeaderSearchTest.cpp
@@ -91,5 +91,12 @@
 "z");
 }
 
+TEST_F(HeaderSearchTest, DotDotsWithAbsPath) {
+  addSearchDir("/x/../y/");
+  EXPECT_EQ(Search.suggestPathToFileForDiagnostics("/y/z",
+   /*WorkingDir=*/""),
+"z");
+}
+
 } // namespace
 } // namespace clang
Index: clang/lib/Lex/HeaderSearch.cpp
===
--- clang/lib/Lex/HeaderSearch.cpp
+++ clang/lib/Lex/HeaderSearch.cpp
@@ -1685,11 +1685,10 @@
 
 StringRef Dir = SearchDirs[I].getDir()->getName();
 llvm::SmallString<32> DirPath(Dir.begin(), Dir.end());
-if (!WorkingDir.empty() && !path::is_absolute(Dir)) {
+if (!WorkingDir.empty() && !path::is_absolute(Dir))
   fs::make_absolute(WorkingDir, DirPath);
-  path::remove_dots(DirPath, /*remove_dot_dot=*/true);
-  Dir = DirPath;
-}
+path::remove_dots(DirPath, /*remove_dot_dot=*/true);
+Dir = DirPath;
 for (auto NI = path::begin(File), NE = path::end(File),
   DI = path::begin(Dir), DE = path::end(Dir);
  /*termination condition in loop*/; ++NI, ++DI) {
Index: clang-tools-extra/unittests/clangd/HeadersTests.cpp
===
--- clang-tools-extra/unittests/clangd/HeadersTests.cpp
+++ clang-tools-extra/unittests/clangd/HeadersTests.cpp
@@ -213,6 +213,11 @@
 TEST_F(HeadersTest, ShortenedInclude) {
   std::string BarHeader = testPath("sub/bar.h");
   EXPECT_EQ(calculate(BarHeader), "\"bar.h\"");
+
+  SearchDirArg = (llvm::Twine("-I") + Subdir + "/..").str();
+  CDB.ExtraClangFlags = {SearchDirArg.c_str()};
+  BarHeader = testPath("sub/bar.h");
+  EXPECT_EQ(calculate(BarHeader), "\"sub/bar.h\"");
 }
 
 TEST_F(HeadersTest, NotShortenedInclude) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r358678 - [Sema][NFC] Mark DR705 (Suppressing argument-dependent lookup via parentheses) as done

2019-04-18 Thread Bruno Ricci via cfe-commits
Author: brunoricci
Date: Thu Apr 18 08:34:03 2019
New Revision: 358678

URL: http://llvm.org/viewvc/llvm-project?rev=358678&view=rev
Log:
[Sema][NFC] Mark DR705 (Suppressing argument-dependent lookup via parentheses) 
as done

It was supported since at least clang 3 so just mark it as done.


Modified:
cfe/trunk/test/CXX/drs/dr7xx.cpp

Modified: cfe/trunk/test/CXX/drs/dr7xx.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CXX/drs/dr7xx.cpp?rev=358678&r1=358677&r2=358678&view=diff
==
--- cfe/trunk/test/CXX/drs/dr7xx.cpp (original)
+++ cfe/trunk/test/CXX/drs/dr7xx.cpp Thu Apr 18 08:34:03 2019
@@ -3,6 +3,19 @@
 // RUN: %clang_cc1 -std=c++14 %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors
 // RUN: %clang_cc1 -std=c++1z %s -verify -fexceptions -fcxx-exceptions 
-pedantic-errors
 
+namespace dr705 { // dr705: yes
+  namespace N {
+struct S {};
+void f(S); // expected-note {{declared here}}
+  }
+
+  void g() {
+N::S s;
+f(s);  // ok
+(f)(s);// expected-error {{use of undeclared}}
+  }
+}
+
 namespace dr727 { // dr727: partial
   struct A {
 template struct C; // expected-note 6{{here}}


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


r358679 - [Sema][NFC] Mark DR1563 as done (List-initialization and overloaded function disambiguation)

2019-04-18 Thread Bruno Ricci via cfe-commits
Author: brunoricci
Date: Thu Apr 18 08:45:08 2019
New Revision: 358679

URL: http://llvm.org/viewvc/llvm-project?rev=358679&view=rev
Log:
[Sema][NFC] Mark DR1563 as done (List-initialization and overloaded function 
disambiguation)

It has been supported since at least clang 3.1 so just mark it as done.


Modified:
cfe/trunk/test/CXX/drs/dr15xx.cpp

Modified: cfe/trunk/test/CXX/drs/dr15xx.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CXX/drs/dr15xx.cpp?rev=358679&r1=358678&r2=358679&view=diff
==
--- cfe/trunk/test/CXX/drs/dr15xx.cpp (original)
+++ cfe/trunk/test/CXX/drs/dr15xx.cpp Thu Apr 18 08:45:08 2019
@@ -236,6 +236,16 @@ namespace dr1560 { // dr1560: 3.5
   const X &x = true ? get() : throw 0;
 }
 
+namespace dr1563 { // dr1563: yes
+#if __cplusplus >= 201103L
+  double bar(double) { return 0.0; }
+  float bar(float) { return 0.0f; }
+
+  using fun = double(double);
+  fun &foo{bar}; // ok
+#endif
+}
+
 namespace dr1573 { // dr1573: 3.9
 #if __cplusplus >= 201103L
   // ellipsis is inherited (p0136r1 supersedes this part).


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


[PATCH] D60875: [OpenMP] Add checks for requires and target directives.

2019-04-18 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea created this revision.
gtbercea added reviewers: ABataev, AlexEichenberger, caomhin.
Herald added subscribers: cfe-commits, jdoerfert, jfb, guansong.
Herald added a project: clang.

The requires directive containing target related clauses must appear before any 
target region in the compilation unit.


Repository:
  rC Clang

https://reviews.llvm.org/D60875

Files:
  include/clang/Basic/DiagnosticSemaKinds.td
  lib/Sema/SemaOpenMP.cpp
  test/OpenMP/requires_messages.cpp
  test/OpenMP/requires_target_messages.cpp

Index: test/OpenMP/requires_target_messages.cpp
===
--- /dev/null
+++ test/OpenMP/requires_target_messages.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -verify -fopenmp -ferror-limit 100  %s
+
+void foo2() {
+  int a;
+  #pragma omp target // expected-note {{Target previously encountered here}}
+  {
+a = a + 1;
+  }
+}
+
+#pragma omp requires unified_shared_memory //expected-error {{Target region encountered before requires directive with unified_shared_memory clause}}
Index: test/OpenMP/requires_messages.cpp
===
--- test/OpenMP/requires_messages.cpp
+++ test/OpenMP/requires_messages.cpp
@@ -7,7 +7,7 @@
 
 #pragma omp requires unified_shared_memory, unified_shared_memory // expected-error {{Only one unified_shared_memory clause can appear on a requires directive in a single translation unit}} expected-error {{directive '#pragma omp requires' cannot contain more than one 'unified_shared_memory' clause}}
 
-#pragma omp requires unified_address // expected-error {{Only one unified_address clause can appear on a requires directive in a single translation unit}} 
+#pragma omp requires unified_address // expected-error {{Only one unified_address clause can appear on a requires directive in a single translation unit}}
 
 #pragma omp requires unified_address, unified_address // expected-error {{Only one unified_address clause can appear on a requires directive in a single translation unit}} expected-error {{directive '#pragma omp requires' cannot contain more than one 'unified_address' clause}}
 
@@ -29,13 +29,13 @@
 
 #pragma omp requires atomic_default_mem_order( // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
-#pragma omp requires atomic_default_mem_order(seq_cst // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}} 
+#pragma omp requires atomic_default_mem_order(seq_cst // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}}
 
-#pragma omp requires atomic_default_mem_order(invalid_modifier) // expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}} 
+#pragma omp requires atomic_default_mem_order(invalid_modifier) // expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
 #pragma omp requires atomic_default_mem_order(shared) // expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
-#pragma omp requires atomic_default_mem_order(acq_rel), atomic_default_mem_order(relaxed) // expected-error {{directive '#pragma omp requires' cannot contain more than one 'atomic_default_mem_order' claus}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}} 
+#pragma omp requires atomic_default_mem_order(acq_rel), atomic_default_mem_order(relaxed) // expected-error {{directive '#pragma omp requires' cannot contain more than one 'atomic_default_mem_order' claus}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}}
 
 #pragma omp requires // expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
Index: lib/Sema/SemaOpenMP.cpp
===
--- lib/Sema/SemaOpenMP.cpp
+++ lib/Sema/SemaOpenMP.cpp
@@ -193,6 +193,8 @@
   /// Expression for the predefined allocators.
   Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
   nullptr};
+  /// Vector of previously encountered target directives
+  SmallVector TargetLocations;
 
 public:
   explicit DSAStackTy

[PATCH] D60875: [OpenMP] Add checks for requires and target directives.

2019-04-18 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: include/clang/Basic/DiagnosticSemaKinds.td:9136
+def err_omp_target_before_requires : Error <
+  "Target region encountered before requires directive with %0 clause">;
+def note_omp_requires_encountered_target : Note <

Enclose `%0` in single quotes for better reading



Comment at: lib/Sema/SemaOpenMP.cpp:2440
+// Check if any of the requires clauses affect target regions.
+if (!TargetLocations.empty() &&
+(isa(CNew) ||

Better to check for `TargetLocations.empty()` before the loop



Comment at: lib/Sema/SemaOpenMP.cpp:4207
+DSAStack->hasRequiresDeclWithClause()) &&
+  !CurContext->isDependentContext()) {
+// Register target to DSA Stack.

Better to check for the dependent context at first, only after that check for 
the clause



Comment at: test/OpenMP/requires_target_messages.cpp:11
+
+#pragma omp requires unified_shared_memory //expected-error {{Target region 
encountered before requires directive with unified_shared_memory clause}}

Add the checks for all the clauses that may cause this error


Repository:
  rC Clang

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

https://reviews.llvm.org/D60875



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


[PATCH] D60875: [OpenMP] Add checks for requires and target directives.

2019-04-18 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 195762.
gtbercea added a comment.

  Fix test,


Repository:
  rC Clang

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

https://reviews.llvm.org/D60875

Files:
  include/clang/Basic/DiagnosticSemaKinds.td
  lib/Sema/SemaOpenMP.cpp
  test/OpenMP/requires_messages.cpp
  test/OpenMP/requires_target_messages.cpp

Index: test/OpenMP/requires_target_messages.cpp
===
--- /dev/null
+++ test/OpenMP/requires_target_messages.cpp
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -verify -fopenmp -ferror-limit 100  %s
+
+void foo2() {
+  int a;
+  #pragma omp target // expected-note {{Target previously encountered here}}
+  {
+a = a + 1;
+  }
+}
+
+#pragma omp requires atomic_default_mem_order(seq_cst)
+#pragma omp requires unified_shared_memory //expected-error {{Target region encountered before requires directive with unified_shared_memory clause}}
Index: test/OpenMP/requires_messages.cpp
===
--- test/OpenMP/requires_messages.cpp
+++ test/OpenMP/requires_messages.cpp
@@ -7,7 +7,7 @@
 
 #pragma omp requires unified_shared_memory, unified_shared_memory // expected-error {{Only one unified_shared_memory clause can appear on a requires directive in a single translation unit}} expected-error {{directive '#pragma omp requires' cannot contain more than one 'unified_shared_memory' clause}}
 
-#pragma omp requires unified_address // expected-error {{Only one unified_address clause can appear on a requires directive in a single translation unit}} 
+#pragma omp requires unified_address // expected-error {{Only one unified_address clause can appear on a requires directive in a single translation unit}}
 
 #pragma omp requires unified_address, unified_address // expected-error {{Only one unified_address clause can appear on a requires directive in a single translation unit}} expected-error {{directive '#pragma omp requires' cannot contain more than one 'unified_address' clause}}
 
@@ -29,13 +29,13 @@
 
 #pragma omp requires atomic_default_mem_order( // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
-#pragma omp requires atomic_default_mem_order(seq_cst // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}} 
+#pragma omp requires atomic_default_mem_order(seq_cst // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}}
 
-#pragma omp requires atomic_default_mem_order(invalid_modifier) // expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}} 
+#pragma omp requires atomic_default_mem_order(invalid_modifier) // expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
 #pragma omp requires atomic_default_mem_order(shared) // expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
-#pragma omp requires atomic_default_mem_order(acq_rel), atomic_default_mem_order(relaxed) // expected-error {{directive '#pragma omp requires' cannot contain more than one 'atomic_default_mem_order' claus}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}} 
+#pragma omp requires atomic_default_mem_order(acq_rel), atomic_default_mem_order(relaxed) // expected-error {{directive '#pragma omp requires' cannot contain more than one 'atomic_default_mem_order' claus}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}}
 
 #pragma omp requires // expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
Index: lib/Sema/SemaOpenMP.cpp
===
--- lib/Sema/SemaOpenMP.cpp
+++ lib/Sema/SemaOpenMP.cpp
@@ -193,6 +193,8 @@
   /// Expression for the predefined allocators.
   Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
   nullptr};
+  /// Vector of previously encountered target directives
+  SmallVector TargetLocations;
 
 public:
   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
@@ -454,6 +456,16 @@
 return IsDuplicate;
   }
 
+  /// Add location of p

[PATCH] D60853: clang-format converts a keyword macro definition to a macro function

2019-04-18 Thread Owen Pan via Phabricator via cfe-commits
owenpan marked 2 inline comments as done.
owenpan added inline comments.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:808
 
-  if (FormatTok->Tok.getKind() != tok::identifier) {
+  if (!FormatTok->Tok.getIdentifierInfo()) {
 IncludeGuard = IG_Rejected;

MyDeveloperDay wrote:
> Is this equivalent to saying something that means `FormatTok->isKeyWord()` ? 
> for those case where the #define 
The condition tests if `FormatTok` is neither a keyword (`true`, `false`, etc.) 
nor a non-keyword identifier.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60853



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


[PATCH] D60875: [OpenMP] Add checks for requires and target directives.

2019-04-18 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 195768.
gtbercea marked an inline comment as done.
gtbercea added a comment.

- Fix test.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60875

Files:
  include/clang/Basic/DiagnosticSemaKinds.td
  lib/Sema/SemaOpenMP.cpp
  test/OpenMP/requires_messages.cpp
  test/OpenMP/requires_target_messages.cpp

Index: test/OpenMP/requires_target_messages.cpp
===
--- /dev/null
+++ test/OpenMP/requires_target_messages.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -verify -fopenmp -ferror-limit 100  %s
+
+void foo2() {
+  int a;
+  #pragma omp target // expected-note {{Target previously encountered here}} expected-note {{Target previously encountered here}} expected-note {{Target previously encountered here}} expected-note {{Target previously encountered here}}
+  {
+a = a + 1;
+  }
+}
+
+#pragma omp requires atomic_default_mem_order(seq_cst)
+#pragma omp requires unified_address //expected-error {{Target region encountered before requires directive with 'unified_address' clause}}
+#pragma omp requires unified_shared_memory //expected-error {{Target region encountered before requires directive with 'unified_shared_memory' clause}}
+#pragma omp requires reverse_offload //expected-error {{Target region encountered before requires directive with 'reverse_offload' clause}}
+#pragma omp requires dynamic_allocators //expected-error {{Target region encountered before requires directive with 'dynamic_allocators' clause}}
Index: test/OpenMP/requires_messages.cpp
===
--- test/OpenMP/requires_messages.cpp
+++ test/OpenMP/requires_messages.cpp
@@ -7,7 +7,7 @@
 
 #pragma omp requires unified_shared_memory, unified_shared_memory // expected-error {{Only one unified_shared_memory clause can appear on a requires directive in a single translation unit}} expected-error {{directive '#pragma omp requires' cannot contain more than one 'unified_shared_memory' clause}}
 
-#pragma omp requires unified_address // expected-error {{Only one unified_address clause can appear on a requires directive in a single translation unit}} 
+#pragma omp requires unified_address // expected-error {{Only one unified_address clause can appear on a requires directive in a single translation unit}}
 
 #pragma omp requires unified_address, unified_address // expected-error {{Only one unified_address clause can appear on a requires directive in a single translation unit}} expected-error {{directive '#pragma omp requires' cannot contain more than one 'unified_address' clause}}
 
@@ -29,13 +29,13 @@
 
 #pragma omp requires atomic_default_mem_order( // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
-#pragma omp requires atomic_default_mem_order(seq_cst // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}} 
+#pragma omp requires atomic_default_mem_order(seq_cst // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}}
 
-#pragma omp requires atomic_default_mem_order(invalid_modifier) // expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}} 
+#pragma omp requires atomic_default_mem_order(invalid_modifier) // expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
 #pragma omp requires atomic_default_mem_order(shared) // expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
-#pragma omp requires atomic_default_mem_order(acq_rel), atomic_default_mem_order(relaxed) // expected-error {{directive '#pragma omp requires' cannot contain more than one 'atomic_default_mem_order' claus}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}} 
+#pragma omp requires atomic_default_mem_order(acq_rel), atomic_default_mem_order(relaxed) // expected-error {{directive '#pragma omp requires' cannot contain more than one 'atomic_default_mem_order' claus}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}}
 
 #pragma omp requires // ex

[PATCH] D60875: [OpenMP] Add checks for requires and target directives.

2019-04-18 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: lib/Sema/SemaOpenMP.cpp:4207
+DSAStack->hasRequiresDeclWithClause()) &&
+  !CurContext->isDependentContext()) {
+// Register target to DSA Stack.

ABataev wrote:
> Better to check for the dependent context at first, only after that check for 
> the clause
Better to check for the dependent context at first, only after that check for 
the clause



Comment at: test/OpenMP/requires_target_messages.cpp:5
+  int a;
+  #pragma omp target // expected-note {{Target previously encountered here}} 
expected-note {{Target previously encountered here}} expected-note {{Target 
previously encountered here}} expected-note {{Target previously encountered 
here}}
+  {

Just `expected-note 4 {{`


Repository:
  rC Clang

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

https://reviews.llvm.org/D60875



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


[PATCH] D60875: [OpenMP] Add checks for requires and target directives.

2019-04-18 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 195770.
gtbercea marked an inline comment as done.
gtbercea added a comment.

- Fix.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60875

Files:
  include/clang/Basic/DiagnosticSemaKinds.td
  lib/Sema/SemaOpenMP.cpp
  test/OpenMP/requires_messages.cpp
  test/OpenMP/requires_target_messages.cpp

Index: test/OpenMP/requires_target_messages.cpp
===
--- /dev/null
+++ test/OpenMP/requires_target_messages.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -verify -fopenmp -ferror-limit 100  %s
+
+void foo2() {
+  int a;
+  #pragma omp target // expected-note {{Target previously encountered here}} expected-note {{Target previously encountered here}} expected-note {{Target previously encountered here}} expected-note {{Target previously encountered here}}
+  {
+a = a + 1;
+  }
+}
+
+#pragma omp requires atomic_default_mem_order(seq_cst)
+#pragma omp requires unified_address //expected-error {{Target region encountered before requires directive with 'unified_address' clause}}
+#pragma omp requires unified_shared_memory //expected-error {{Target region encountered before requires directive with 'unified_shared_memory' clause}}
+#pragma omp requires reverse_offload //expected-error {{Target region encountered before requires directive with 'reverse_offload' clause}}
+#pragma omp requires dynamic_allocators //expected-error {{Target region encountered before requires directive with 'dynamic_allocators' clause}}
Index: test/OpenMP/requires_messages.cpp
===
--- test/OpenMP/requires_messages.cpp
+++ test/OpenMP/requires_messages.cpp
@@ -7,7 +7,7 @@
 
 #pragma omp requires unified_shared_memory, unified_shared_memory // expected-error {{Only one unified_shared_memory clause can appear on a requires directive in a single translation unit}} expected-error {{directive '#pragma omp requires' cannot contain more than one 'unified_shared_memory' clause}}
 
-#pragma omp requires unified_address // expected-error {{Only one unified_address clause can appear on a requires directive in a single translation unit}} 
+#pragma omp requires unified_address // expected-error {{Only one unified_address clause can appear on a requires directive in a single translation unit}}
 
 #pragma omp requires unified_address, unified_address // expected-error {{Only one unified_address clause can appear on a requires directive in a single translation unit}} expected-error {{directive '#pragma omp requires' cannot contain more than one 'unified_address' clause}}
 
@@ -29,13 +29,13 @@
 
 #pragma omp requires atomic_default_mem_order( // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
-#pragma omp requires atomic_default_mem_order(seq_cst // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}} 
+#pragma omp requires atomic_default_mem_order(seq_cst // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}}
 
-#pragma omp requires atomic_default_mem_order(invalid_modifier) // expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}} 
+#pragma omp requires atomic_default_mem_order(invalid_modifier) // expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
 #pragma omp requires atomic_default_mem_order(shared) // expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
-#pragma omp requires atomic_default_mem_order(acq_rel), atomic_default_mem_order(relaxed) // expected-error {{directive '#pragma omp requires' cannot contain more than one 'atomic_default_mem_order' claus}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}} 
+#pragma omp requires atomic_default_mem_order(acq_rel), atomic_default_mem_order(relaxed) // expected-error {{directive '#pragma omp requires' cannot contain more than one 'atomic_default_mem_order' claus}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}}
 
 #pragma omp requires // expecte

[PATCH] D60875: [OpenMP] Add checks for requires and target directives.

2019-04-18 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 195771.
gtbercea added a comment.

- Fix.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60875

Files:
  include/clang/Basic/DiagnosticSemaKinds.td
  lib/Sema/SemaOpenMP.cpp
  test/OpenMP/requires_messages.cpp
  test/OpenMP/requires_target_messages.cpp

Index: test/OpenMP/requires_target_messages.cpp
===
--- /dev/null
+++ test/OpenMP/requires_target_messages.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -verify -fopenmp -ferror-limit 100  %s
+
+void foo2() {
+  int a;
+  #pragma omp target // expected-note 4 {{Target previously encountered here}}
+  {
+a = a + 1;
+  }
+}
+
+#pragma omp requires atomic_default_mem_order(seq_cst)
+#pragma omp requires unified_address //expected-error {{Target region encountered before requires directive with 'unified_address' clause}}
+#pragma omp requires unified_shared_memory //expected-error {{Target region encountered before requires directive with 'unified_shared_memory' clause}}
+#pragma omp requires reverse_offload //expected-error {{Target region encountered before requires directive with 'reverse_offload' clause}}
+#pragma omp requires dynamic_allocators //expected-error {{Target region encountered before requires directive with 'dynamic_allocators' clause}}
Index: test/OpenMP/requires_messages.cpp
===
--- test/OpenMP/requires_messages.cpp
+++ test/OpenMP/requires_messages.cpp
@@ -7,7 +7,7 @@
 
 #pragma omp requires unified_shared_memory, unified_shared_memory // expected-error {{Only one unified_shared_memory clause can appear on a requires directive in a single translation unit}} expected-error {{directive '#pragma omp requires' cannot contain more than one 'unified_shared_memory' clause}}
 
-#pragma omp requires unified_address // expected-error {{Only one unified_address clause can appear on a requires directive in a single translation unit}} 
+#pragma omp requires unified_address // expected-error {{Only one unified_address clause can appear on a requires directive in a single translation unit}}
 
 #pragma omp requires unified_address, unified_address // expected-error {{Only one unified_address clause can appear on a requires directive in a single translation unit}} expected-error {{directive '#pragma omp requires' cannot contain more than one 'unified_address' clause}}
 
@@ -29,13 +29,13 @@
 
 #pragma omp requires atomic_default_mem_order( // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
-#pragma omp requires atomic_default_mem_order(seq_cst // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}} 
+#pragma omp requires atomic_default_mem_order(seq_cst // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}}
 
-#pragma omp requires atomic_default_mem_order(invalid_modifier) // expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}} 
+#pragma omp requires atomic_default_mem_order(invalid_modifier) // expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
 #pragma omp requires atomic_default_mem_order(shared) // expected-error {{expected 'seq_cst', 'acq_rel' or 'relaxed' in OpenMP clause 'atomic_default_mem_order'}} expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
-#pragma omp requires atomic_default_mem_order(acq_rel), atomic_default_mem_order(relaxed) // expected-error {{directive '#pragma omp requires' cannot contain more than one 'atomic_default_mem_order' claus}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}} 
+#pragma omp requires atomic_default_mem_order(acq_rel), atomic_default_mem_order(relaxed) // expected-error {{directive '#pragma omp requires' cannot contain more than one 'atomic_default_mem_order' claus}} expected-error {{Only one atomic_default_mem_order clause can appear on a requires directive in a single translation unit}}
 
 #pragma omp requires // expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
Index: lib/Sema/SemaOpenMP.cpp
===
--- lib/Sema/SemaOpenM

[PATCH] D60875: [OpenMP] Add checks for requires and target directives.

2019-04-18 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: include/clang/Basic/DiagnosticSemaKinds.td:9136
+def err_omp_target_before_requires : Error <
+  "Target region encountered before requires directive with '%0' clause">;
+def note_omp_requires_encountered_target : Note <

The messages must start from lower letter. Other messages must be fixed too in 
separate patches.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60875



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


r358689 - [clang-format] Fix indent of trailing raw string param after newline

2019-04-18 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Thu Apr 18 10:14:05 2019
New Revision: 358689

URL: http://llvm.org/viewvc/llvm-project?rev=358689&view=rev
Log:
[clang-format] Fix indent of trailing raw string param after newline

Summary:
Currently clang-format uses ContinuationIndent to indent the contents of a raw
string literal that is the last parameter of the function call. This is to
achieve formatting similar to trailing:
```
f(1, 2, R"pb(
x: y)pb");
```
However this had the unfortunate consequence of producing format like this:
```
fff(1, 2,
R"pb(
a: b
)pb");
```

This patch makes clang-format consider indenting a trailing raw string param
after a newline based off the start of the format delimiter, producing:
```
fff(1, 2,
R"pb(
  a: b
)pb");
```

Reviewers: djasper

Reviewed By: djasper

Subscribers: cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/lib/Format/ContinuationIndenter.h
cfe/trunk/unittests/Format/FormatTestRawStrings.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=358689&r1=358688&r2=358689&view=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Thu Apr 18 10:14:05 2019
@@ -1196,7 +1196,8 @@ unsigned ContinuationIndenter::moveState
   State.Column += Current.ColumnWidth;
   State.NextToken = State.NextToken->Next;
 
-  unsigned Penalty = handleEndOfLine(Current, State, DryRun, AllowBreak);
+  unsigned Penalty =
+  handleEndOfLine(Current, State, DryRun, AllowBreak, Newline);
 
   if (Current.Role)
 Current.Role->formatFromToken(State, this, DryRun);
@@ -1490,7 +1491,7 @@ static unsigned getLastLineEndColumn(Str
 
 unsigned ContinuationIndenter::reformatRawStringLiteral(
 const FormatToken &Current, LineState &State,
-const FormatStyle &RawStringStyle, bool DryRun) {
+const FormatStyle &RawStringStyle, bool DryRun, bool Newline) {
   unsigned StartColumn = State.Column - Current.ColumnWidth;
   StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText);
   StringRef NewDelimiter =
@@ -1530,8 +1531,10 @@ unsigned ContinuationIndenter::reformatR
   // source.
   bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
   // If this token is the last parameter (checked by looking if it's followed 
by
-  // `)`, the base the indent off the line's nested block indent. Otherwise,
-  // base the indent off the arguments indent, so we can achieve:
+  // `)` and is not on a newline, the base the indent off the line's nested
+  // block indent. Otherwise, base the indent off the arguments indent, so we
+  // can achieve:
+  //
   // fff(1, 2, 3, R"pb(
   // key1: 1  #
   // key2: 2)pb");
@@ -1540,11 +1543,18 @@ unsigned ContinuationIndenter::reformatR
   // R"pb(
   //   key1: 1  #
   //   key2: 2
+  // )pb");
+  //
+  // fff(1, 2, 3,
+  // R"pb(
+  //   key1: 1  #
+  //   key2: 2
   // )pb",
   // 5);
-  unsigned CurrentIndent = (Current.Next && Current.Next->is(tok::r_paren))
-   ? State.Stack.back().NestedBlockIndent
-   : State.Stack.back().Indent;
+  unsigned CurrentIndent =
+  (!Newline && Current.Next && Current.Next->is(tok::r_paren))
+  ? State.Stack.back().NestedBlockIndent
+  : State.Stack.back().Indent;
   unsigned NextStartColumn = ContentStartsOnNewline
  ? CurrentIndent + Style.IndentWidth
  : FirstStartColumn;
@@ -1646,13 +1656,14 @@ unsigned ContinuationIndenter::addMultil
 
 unsigned ContinuationIndenter::handleEndOfLine(const FormatToken &Current,
LineState &State, bool DryRun,
-   bool AllowBreak) {
+   bool AllowBreak, bool Newline) {
   unsigned Penalty = 0;
   // Compute the raw string style to use in case this is a raw string literal
   // that can be reformatted.
   auto RawStringStyle = getRawStringStyle(Current, State);
   if (RawStringStyle && !Current.Finalized) {
-Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, 
DryRun);
+Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, DryRun,
+   Newline);
   } else if (Current.IsMultiline && Current.isNot(TT_BlockComment)) {
 // Don't break multi-line tokens other than block comments and raw string
 // literals. Instead, just update the state.

Modified: cfe/trunk/lib/Format/ContinuationIndenter.h
URL: 
http://ll

[PATCH] D60558: [clang-format] Fix indent of trailing raw string param after newline

2019-04-18 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC358689: [clang-format] Fix indent of trailing raw string 
param after newline (authored by krasimir, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D60558?vs=194654&id=195772#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D60558

Files:
  lib/Format/ContinuationIndenter.cpp
  lib/Format/ContinuationIndenter.h
  unittests/Format/FormatTestRawStrings.cpp

Index: lib/Format/ContinuationIndenter.h
===
--- lib/Format/ContinuationIndenter.h
+++ lib/Format/ContinuationIndenter.h
@@ -111,12 +111,12 @@
   unsigned reformatRawStringLiteral(const FormatToken &Current,
 LineState &State,
 const FormatStyle &RawStringStyle,
-bool DryRun);
+bool DryRun, bool Newline);
 
   /// If the current token is at the end of the current line, handle
   /// the transition to the next line.
   unsigned handleEndOfLine(const FormatToken &Current, LineState &State,
-   bool DryRun, bool AllowBreak);
+   bool DryRun, bool AllowBreak, bool Newline);
 
   /// If \p Current is a raw string that is configured to be reformatted,
   /// return the style to be used.
Index: lib/Format/ContinuationIndenter.cpp
===
--- lib/Format/ContinuationIndenter.cpp
+++ lib/Format/ContinuationIndenter.cpp
@@ -1196,7 +1196,8 @@
   State.Column += Current.ColumnWidth;
   State.NextToken = State.NextToken->Next;
 
-  unsigned Penalty = handleEndOfLine(Current, State, DryRun, AllowBreak);
+  unsigned Penalty =
+  handleEndOfLine(Current, State, DryRun, AllowBreak, Newline);
 
   if (Current.Role)
 Current.Role->formatFromToken(State, this, DryRun);
@@ -1490,7 +1491,7 @@
 
 unsigned ContinuationIndenter::reformatRawStringLiteral(
 const FormatToken &Current, LineState &State,
-const FormatStyle &RawStringStyle, bool DryRun) {
+const FormatStyle &RawStringStyle, bool DryRun, bool Newline) {
   unsigned StartColumn = State.Column - Current.ColumnWidth;
   StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText);
   StringRef NewDelimiter =
@@ -1530,8 +1531,10 @@
   // source.
   bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
   // If this token is the last parameter (checked by looking if it's followed by
-  // `)`, the base the indent off the line's nested block indent. Otherwise,
-  // base the indent off the arguments indent, so we can achieve:
+  // `)` and is not on a newline, the base the indent off the line's nested
+  // block indent. Otherwise, base the indent off the arguments indent, so we
+  // can achieve:
+  //
   // fff(1, 2, 3, R"pb(
   // key1: 1  #
   // key2: 2)pb");
@@ -1540,11 +1543,18 @@
   // R"pb(
   //   key1: 1  #
   //   key2: 2
+  // )pb");
+  //
+  // fff(1, 2, 3,
+  // R"pb(
+  //   key1: 1  #
+  //   key2: 2
   // )pb",
   // 5);
-  unsigned CurrentIndent = (Current.Next && Current.Next->is(tok::r_paren))
-   ? State.Stack.back().NestedBlockIndent
-   : State.Stack.back().Indent;
+  unsigned CurrentIndent =
+  (!Newline && Current.Next && Current.Next->is(tok::r_paren))
+  ? State.Stack.back().NestedBlockIndent
+  : State.Stack.back().Indent;
   unsigned NextStartColumn = ContentStartsOnNewline
  ? CurrentIndent + Style.IndentWidth
  : FirstStartColumn;
@@ -1646,13 +1656,14 @@
 
 unsigned ContinuationIndenter::handleEndOfLine(const FormatToken &Current,
LineState &State, bool DryRun,
-   bool AllowBreak) {
+   bool AllowBreak, bool Newline) {
   unsigned Penalty = 0;
   // Compute the raw string style to use in case this is a raw string literal
   // that can be reformatted.
   auto RawStringStyle = getRawStringStyle(Current, State);
   if (RawStringStyle && !Current.Finalized) {
-Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, DryRun);
+Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, DryRun,
+   Newline);
   } else if (Current.IsMultiline && Current.isNot(TT_BlockComment)) {
 // Don't break multi-line tokens other than block comments and raw string
 // literals. Instead, just update the state.
Index: unittests/Format/FormatTestRawStrings.cpp
=

[PATCH] D60873: [clang][HeaderSuggestion] Handle the case of dotdot with an absolute path

2019-04-18 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.

Well done!
I never managed to track this one down, this was really annoying.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60873



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


[PATCH] D60568: [OpenMP] Add support for registering requires directives with the runtime

2019-04-18 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 195775.
gtbercea added a comment.

- Move error check in sema.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60568

Files:
  lib/CodeGen/CGOpenMPRuntime.cpp
  lib/CodeGen/CGOpenMPRuntime.h
  lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
  lib/CodeGen/CGOpenMPRuntimeNVPTX.h
  lib/CodeGen/CodeGenModule.cpp
  test/OpenMP/openmp_offload_registration.cpp
  test/OpenMP/target_codegen.cpp
  test/OpenMP/target_codegen_registration.cpp

Index: test/OpenMP/target_codegen_registration.cpp
===
--- test/OpenMP/target_codegen_registration.cpp
+++ test/OpenMP/target_codegen_registration.cpp
@@ -180,10 +180,11 @@
 // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]])
 
 // We have 4 initializers, one for the 500 priority, another one for 501, or more for the default priority, and the last one for the offloading registration function.
-// CHECK: @llvm.global_ctors = appending global [4 x { i32, void ()*, i8* }] [
+// CHECK: @llvm.global_ctors = appending global [5 x { i32, void ()*, i8* }] [
 // CHECK-SAME: { i32, void ()*, i8* } { i32 500, void ()* [[P500:@[^,]+]], i8* null },
 // CHECK-SAME: { i32, void ()*, i8* } { i32 501, void ()* [[P501:@[^,]+]], i8* null },
 // CHECK-SAME: { i32, void ()*, i8* } { i32 65535, void ()* [[PMAX:@[^,]+]], i8* null },
+// CHECK-SAME: { i32, void ()*, i8* } { i32 0, void ()* @.omp_offloading.requires_reg, i8* null },
 // CHECK-SAME: { i32, void ()*, i8* } { i32 0, void ()* @[[REGFN]], i8* bitcast (void ()* @[[REGFN]] to i8*) }]
 
 // CHECK-NTARGET: @llvm.global_ctors = appending global [3   x { i32, void ()*, i8* }] [
@@ -387,6 +388,10 @@
 
 // Check registration and unregistration
 
+//CHECK: define internal void @.omp_offloading.requires_reg()
+//CHECK: call void @__tgt_register_requires(i64 1)
+//CHECK: ret void
+
 //CHECK: define internal void @[[UNREGFN:.+]](i8*)
 //CHECK-SAME: comdat($[[REGFN]]) {
 //CHECK: call i32 @__tgt_unregister_lib([[DSCTY]]* [[DESC]])
@@ -432,31 +437,31 @@
 
 // Check metadata is properly generated:
 // CHECK: !omp_offload.info = !{!{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID:-?[0-9]+]], i32 [[FILEID:-?[0-9]+]], !"_ZN2SB3fooEv", i32 216, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SDD1Ev", i32 266, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SEC1Ev", i32 282, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SED1Ev", i32 288, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EE3fooEv", i32 299, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EEC1Ev", i32 305, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_Z3bari", i32 427, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EED1Ev", i32 311, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EEC1Ev", i32 305, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EED1Ev", i32 311, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EE3fooEv", i32 299, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SCC1Ev", i32 241, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID:-?[0-9]+]], i32 [[FILEID:-?[0-9]+]], !"_ZN2SB3fooEv", i32 217, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SDD1Ev", i32 267, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SEC1Ev", i32 283, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SED1Ev", i32 289, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EE3fooEv", i32 300, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EEC1Ev", i32 306, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_Z3bari", i32 432, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EED1Ev", i32 312, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EEC1Ev", i32 306, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EED1Ev", i32 312, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EE3fooEv", i32 300, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SCC1Ev", i32 242, i32 {{[0-9]

r358691 - [LibTooling] Add Stencil library for format-string style codegen.

2019-04-18 Thread Yitzhak Mandelbaum via cfe-commits
Author: ymandel
Date: Thu Apr 18 10:23:01 2019
New Revision: 358691

URL: http://llvm.org/viewvc/llvm-project?rev=358691&view=rev
Log:
[LibTooling] Add Stencil library for format-string style codegen.

Summary:
This file defines the *Stencil* abstraction: a code-generating object, 
parameterized by named references to (bound) AST nodes.  Given a match result, 
a stencil can be evaluated to a string of source code.

A stencil is similar in spirit to a format string: it is composed of a series 
of raw text strings, references to nodes (the parameters) and helper 
code-generation operations.

See thread on cfe-dev list with subject "[RFC] Easier source-to-source 
transformations with clang tooling" for background.

Reviewers: sbenza

Reviewed By: sbenza

Subscribers: ilya-biryukov, mgorny, jfb, jdoerfert, cfe-commits

Tags: #clang

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

Added:
cfe/trunk/include/clang/Tooling/Refactoring/Stencil.h
cfe/trunk/lib/Tooling/Refactoring/Stencil.cpp
cfe/trunk/unittests/Tooling/StencilTest.cpp
Modified:
cfe/trunk/lib/Tooling/Refactoring/CMakeLists.txt
cfe/trunk/unittests/Tooling/CMakeLists.txt

Added: cfe/trunk/include/clang/Tooling/Refactoring/Stencil.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/Refactoring/Stencil.h?rev=358691&view=auto
==
--- cfe/trunk/include/clang/Tooling/Refactoring/Stencil.h (added)
+++ cfe/trunk/include/clang/Tooling/Refactoring/Stencil.h Thu Apr 18 10:23:01 
2019
@@ -0,0 +1,161 @@
+//===--- Stencil.h - Stencil class --*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+///
+/// /file
+/// This file defines the *Stencil* abstraction: a code-generating object,
+/// parameterized by named references to (bound) AST nodes.  Given a match
+/// result, a stencil can be evaluated to a string of source code.
+///
+/// A stencil is similar in spirit to a format string: it is composed of a
+/// series of raw text strings, references to nodes (the parameters) and helper
+/// code-generation operations.
+///
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLING_REFACTOR_STENCIL_H_
+#define LLVM_CLANG_TOOLING_REFACTOR_STENCIL_H_
+
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Error.h"
+#include 
+#include 
+
+namespace clang {
+namespace tooling {
+
+/// A stencil is represented as a sequence of "parts" that can each 
individually
+/// generate a code string based on a match result.  The different kinds of
+/// parts include (raw) text, references to bound nodes and assorted operations
+/// on bound nodes.
+///
+/// Users can create custom Stencil operations by implementing this interface.
+class StencilPartInterface {
+public:
+  virtual ~StencilPartInterface() = default;
+
+  /// Evaluates this part to a string and appends it to \c Result.  \c Result 
is
+  /// undefined in the case of an error.
+  virtual llvm::Error eval(const ast_matchers::MatchFinder::MatchResult &Match,
+   std::string *Result) const = 0;
+
+  virtual bool isEqual(const StencilPartInterface &other) const = 0;
+
+  const void *typeId() const { return TypeId; }
+
+protected:
+  StencilPartInterface(const void *DerivedId) : TypeId(DerivedId) {}
+
+  // Since this is an abstract class, copying/assigning only make sense for
+  // derived classes implementing `clone()`.
+  StencilPartInterface(const StencilPartInterface &) = default;
+  StencilPartInterface &operator=(const StencilPartInterface &) = default;
+
+  /// Unique identifier of the concrete type of this instance.  Supports safe
+  /// downcasting.
+  const void *TypeId;
+};
+
+/// A copyable facade for a std::unique_ptr. Copies 
result
+/// in a copy of the underlying pointee object.
+class StencilPart {
+public:
+  explicit StencilPart(std::shared_ptr Impl)
+  : Impl(std::move(Impl)) {}
+
+  /// See `StencilPartInterface::eval()`.
+  llvm::Error eval(const ast_matchers::MatchFinder::MatchResult &Match,
+   std::string *Result) const {
+return Impl->eval(Match, Result);
+  }
+
+  bool operator==(const StencilPart &Other) const {
+if (Impl == Other.Impl)
+  return true;
+if (Impl == nullptr || Other.Impl == nullptr)
+  return false;
+return Impl->isEqual(*Other.Impl);
+  }
+
+private:
+  std::shared_ptr Impl;
+};
+
+/// A sequence of code fragments, references to parameters and code-generation
+/// operations that together can be evaluated to (a fragment of) source code

[PATCH] D59371: [LibTooling] Add Stencil library for format-string style codegen.

2019-04-18 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC358691: [LibTooling] Add Stencil library for format-string 
style codegen. (authored by ymandel, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D59371?vs=195606&id=195778#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D59371

Files:
  include/clang/Tooling/Refactoring/Stencil.h
  lib/Tooling/Refactoring/CMakeLists.txt
  lib/Tooling/Refactoring/Stencil.cpp
  unittests/Tooling/CMakeLists.txt
  unittests/Tooling/StencilTest.cpp

Index: unittests/Tooling/StencilTest.cpp
===
--- unittests/Tooling/StencilTest.cpp
+++ unittests/Tooling/StencilTest.cpp
@@ -0,0 +1,223 @@
+//===- unittest/Tooling/StencilTest.cpp ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/Refactoring/Stencil.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/FixIt.h"
+#include "clang/Tooling/Tooling.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace tooling;
+using namespace ast_matchers;
+
+namespace {
+using ::testing::AllOf;
+using ::testing::Eq;
+using ::testing::HasSubstr;
+using MatchResult = MatchFinder::MatchResult;
+using tooling::stencil::node;
+using tooling::stencil::sNode;
+using tooling::stencil::text;
+
+// In tests, we can't directly match on llvm::Expected since its accessors
+// mutate the object. So, we collapse it to an Optional.
+static llvm::Optional toOptional(llvm::Expected V) {
+  if (V)
+return *V;
+  ADD_FAILURE() << "Losing error in conversion to IsSomething: "
+<< llvm::toString(V.takeError());
+  return llvm::None;
+}
+
+// A very simple matcher for llvm::Optional values.
+MATCHER_P(IsSomething, ValueMatcher, "") {
+  if (!arg)
+return false;
+  return ::testing::ExplainMatchResult(ValueMatcher, *arg, result_listener);
+}
+
+// Create a valid translation-unit from a statement.
+static std::string wrapSnippet(llvm::Twine StatementCode) {
+  return ("auto stencil_test_snippet = []{" + StatementCode + "};").str();
+}
+
+static DeclarationMatcher wrapMatcher(const StatementMatcher &Matcher) {
+  return varDecl(hasName("stencil_test_snippet"),
+ hasDescendant(compoundStmt(hasAnySubstatement(Matcher;
+}
+
+struct TestMatch {
+  // The AST unit from which `result` is built. We bundle it because it backs
+  // the result. Users are not expected to access it.
+  std::unique_ptr AstUnit;
+  // The result to use in the test. References `ast_unit`.
+  MatchResult Result;
+};
+
+// Matches `Matcher` against the statement `StatementCode` and returns the
+// result. Handles putting the statement inside a function and modifying the
+// matcher correspondingly. `Matcher` should match `StatementCode` exactly --
+// that is, produce exactly one match.
+static llvm::Optional matchStmt(llvm::Twine StatementCode,
+   StatementMatcher Matcher) {
+  auto AstUnit = buildASTFromCode(wrapSnippet(StatementCode));
+  if (AstUnit == nullptr) {
+ADD_FAILURE() << "AST construction failed";
+return llvm::None;
+  }
+  ASTContext &Context = AstUnit->getASTContext();
+  auto Matches = ast_matchers::match(wrapMatcher(Matcher), Context);
+  // We expect a single, exact match for the statement.
+  if (Matches.size() != 1) {
+ADD_FAILURE() << "Wrong number of matches: " << Matches.size();
+return llvm::None;
+  }
+  return TestMatch{std::move(AstUnit), MatchResult(Matches[0], &Context)};
+}
+
+class StencilTest : public ::testing::Test {
+protected:
+  // Verifies that the given stencil fails when evaluated on a valid match
+  // result. Binds a statement to "stmt", a (non-member) ctor-initializer to
+  // "init", an expression to "expr" and a (nameless) declaration to "decl".
+  void testError(const Stencil &Stencil,
+ ::testing::Matcher Matcher) {
+const std::string Snippet = R"cc(
+  struct A {};
+  class F : public A {
+   public:
+F(int) {}
+  };
+  F(1);
+)cc";
+auto StmtMatch = matchStmt(
+Snippet,
+stmt(hasDescendant(
+ cxxConstructExpr(
+ hasDeclaration(decl(hasDescendant(cxxCtorInitializer(
+   isBaseInitializer())
+   .bind("init")))
+.bind("decl")))
+ .bind("expr")))
+.bind("stmt"));
+ASSERT_TRUE(StmtMatch);
+if (auto ResultOrEr

r358695 - [analyzer][NFC] Prefer binary searches in CheckerRegistry

2019-04-18 Thread Kristof Umann via cfe-commits
Author: szelethus
Date: Thu Apr 18 10:34:45 2019
New Revision: 358695

URL: http://llvm.org/viewvc/llvm-project?rev=358695&view=rev
Log:
[analyzer][NFC] Prefer binary searches in CheckerRegistry

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

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h?rev=358695&r1=358694&r2=358695&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h Thu Apr 
18 10:34:45 2019
@@ -108,8 +108,8 @@ public:
   State_Enabled
 };
 
-InitializationFunction Initialize;
-ShouldRegisterFunction ShouldRegister;
+InitializationFunction Initialize = nullptr;
+ShouldRegisterFunction ShouldRegister = nullptr;
 StringRef FullName;
 StringRef Desc;
 StringRef DocumentationUri;
@@ -129,6 +129,9 @@ public:
 StringRef Name, StringRef Desc, StringRef DocsUri)
 : Initialize(Fn), ShouldRegister(sfn), FullName(Name), Desc(Desc),
   DocumentationUri(DocsUri) {}
+
+// Used for lower_bound.
+explicit CheckerInfo(StringRef FullName) : FullName(FullName) {}
   };
 
   using StateFromCmdLine = CheckerInfo::StateFromCmdLine;

Modified: cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp?rev=358695&r1=358694&r2=358695&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp Thu Apr 18 
10:34:45 2019
@@ -48,6 +48,28 @@ template  struct FullNameLT {
 using CheckerNameLT = FullNameLT;
 } // end of anonymous namespace
 
+template 
+static
+typename std::conditional::value,
+  typename 
CheckerOrPackageInfoList::const_iterator,
+  typename 
CheckerOrPackageInfoList::iterator>::type
+binaryFind(CheckerOrPackageInfoList &Collection, StringRef FullName) {
+
+  using CheckerOrPackage = typename CheckerOrPackageInfoList::value_type;
+  using CheckerOrPackageFullNameLT = FullNameLT;
+
+  assert(std::is_sorted(Collection.begin(), Collection.end(),
+CheckerOrPackageFullNameLT{}) &&
+ "In order to efficiently gather checkers/packages, this function "
+ "expects them to be already sorted!");
+
+  typename CheckerOrPackageInfoList::value_type Info(FullName);
+
+  return llvm::lower_bound(
+  Collection, Info,
+  FullNameLT{});
+}
+
 static constexpr char PackageSeparator = '.';
 
 static bool isInPackage(const CheckerRegistry::CheckerInfo &Checker,
@@ -69,16 +91,7 @@ static bool isInPackage(const CheckerReg
 
 CheckerRegistry::CheckerInfoListRange
 CheckerRegistry::getMutableCheckersForCmdLineArg(StringRef CmdLineArg) {
-
-  assert(std::is_sorted(Checkers.begin(), Checkers.end(), CheckerNameLT{}) &&
- "In order to efficiently gather checkers, this function expects them "
- "to be already sorted!");
-
-  // Use a binary search to find the possible start of the package.
-  CheckerRegistry::CheckerInfo PackageInfo(nullptr, nullptr, CmdLineArg, "",
-   "");
-  auto It = std::lower_bound(Checkers.begin(), Checkers.end(), PackageInfo,
- CheckerNameLT{});
+  auto It = binaryFind(Checkers, CmdLineArg);
 
   if (!isInPackage(*It, CmdLineArg))
 return {Checkers.end(), Checkers.end()};
@@ -268,24 +281,18 @@ void CheckerRegistry::addChecker(Initial
   }
 }
 
-void CheckerRegistry::addDependency(StringRef FullName, StringRef dependency) {
-  auto CheckerThatNeedsDeps = [&FullName](const CheckerInfo &Chk) {
-return Chk.FullName == FullName;
-  };
-  auto Dependency = [&dependency](const CheckerInfo &Chk) {
-return Chk.FullName == dependency;
-  };
-
-  auto CheckerIt = llvm::find_if(Checkers, CheckerThatNeedsDeps);
-  assert(CheckerIt != Checkers.end() &&
+void CheckerRegistry::addDependency(StringRef FullName, StringRef Dependency) {
+  auto CheckerIt = binaryFind(Checkers, FullName);
+  assert(CheckerIt != Checkers.end() && CheckerIt->FullName == FullName &&
  "Failed to find the checker while attempting to set up its "
  "dependencies!");
 
-  auto DependencyIt = llvm::find_if(Checkers, Dependency);
+  auto DependencyIt = binaryFind(Checkers, Dependency);
   assert(DependencyIt != Checkers.end() &&
+ DependencyIt->FullName == Dependency &&
  "Failed to find the dependency of a checker!");
 
-  Check

r358694 - [analyzer][NFC] Clang-format CheckerRegistry

2019-04-18 Thread Kristof Umann via cfe-commits
Author: szelethus
Date: Thu Apr 18 10:32:51 2019
New Revision: 358694

URL: http://llvm.org/viewvc/llvm-project?rev=358694&view=rev
Log:
[analyzer][NFC] Clang-format CheckerRegistry

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

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h?rev=358694&r1=358693&r2=358694&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h Thu Apr 
18 10:32:51 2019
@@ -81,11 +81,10 @@ namespace ento {
 /// "core.builtin", or the full name "core.builtin.NoReturnFunctionChecker".
 class CheckerRegistry {
 public:
-  CheckerRegistry(
-  ArrayRef plugins, DiagnosticsEngine &diags,
-  AnalyzerOptions &AnOpts, const LangOptions &LangOpts,
-  ArrayRef>
-  checkerRegistrationFns = {});
+  CheckerRegistry(ArrayRef plugins, DiagnosticsEngine &diags,
+  AnalyzerOptions &AnOpts, const LangOptions &LangOpts,
+  ArrayRef>
+  checkerRegistrationFns = {});
 
   /// Initialization functions perform any necessary setup for a checker.
   /// They should include a call to CheckerManager::registerChecker.
@@ -135,14 +134,11 @@ public:
   using StateFromCmdLine = CheckerInfo::StateFromCmdLine;
 
 private:
-  template 
-  static void initializeManager(CheckerManager &mgr) {
+  template  static void initializeManager(CheckerManager &mgr) {
 mgr.registerChecker();
   }
 
-
-  template 
-  static bool returnTrue(const LangOptions &LO) {
+  template  static bool returnTrue(const LangOptions &LO) {
 return true;
   }
 

Modified: cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp?rev=358694&r1=358693&r2=358694&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp Thu Apr 18 
10:32:51 2019
@@ -11,8 +11,8 @@
 #include "clang/Basic/LLVM.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
-#include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/StringMap.h"
@@ -39,8 +39,7 @@ static bool isCompatibleAPIVersion(const
 }
 
 namespace {
-template 
-struct FullNameLT {
+template  struct FullNameLT {
   bool operator()(const T &Lhs, const T &Rhs) {
 return Lhs.FullName < Rhs.FullName;
   }
@@ -76,13 +75,13 @@ CheckerRegistry::getMutableCheckersForCm
  "to be already sorted!");
 
   // Use a binary search to find the possible start of the package.
-  CheckerRegistry::CheckerInfo
-  PackageInfo(nullptr, nullptr, CmdLineArg, "", "");
-  auto It = std::lower_bound(Checkers.begin(), Checkers.end(),
- PackageInfo, CheckerNameLT{});
+  CheckerRegistry::CheckerInfo PackageInfo(nullptr, nullptr, CmdLineArg, "",
+   "");
+  auto It = std::lower_bound(Checkers.begin(), Checkers.end(), PackageInfo,
+ CheckerNameLT{});
 
   if (!isInPackage(*It, CmdLineArg))
-return { Checkers.end(), Checkers.end() };
+return {Checkers.end(), Checkers.end()};
 
   // See how large the package is.
   // If the package doesn't exist, assume the option refers to a single
@@ -94,15 +93,14 @@ CheckerRegistry::getMutableCheckersForCm
   if (PackageSize != PackageSizes.end())
 Size = PackageSize->getValue();
 
-  return { It, It + Size };
+  return {It, It + Size};
 }
 
 CheckerRegistry::CheckerRegistry(
- ArrayRef Plugins, DiagnosticsEngine &Diags,
- AnalyzerOptions &AnOpts, const LangOptions &LangOpts,
- ArrayRef>
- CheckerRegistrationFns)
-  : Diags(Diags), AnOpts(AnOpts), LangOpts(LangOpts) {
+ArrayRef Plugins, DiagnosticsEngine &Diags,
+AnalyzerOptions &AnOpts, const LangOptions &LangOpts,
+ArrayRef> CheckerRegistrationFns)
+: Diags(Diags), AnOpts(AnOpts), LangOpts(LangOpts) {
 
   // Register builtin checkers.
 #define GET_CHECKERS
@@ -135,22 +133,21 @@ CheckerRegistry::CheckerRegistry(
   Diags.Report(diag::warn_incompatible_analyzer_plugin_api)
   << llvm::sys::path::filename(Plugin);
   Diags.Report(diag::note_incompatible_analyzer_plugin_api)
-  << CLANG_ANALYZER_API_VERSION_STRING
-  <

[clang-tools-extra] r358696 - [CodeComplete] Remove obsolete isOutputBinary().

2019-04-18 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Thu Apr 18 10:35:55 2019
New Revision: 358696

URL: http://llvm.org/viewvc/llvm-project?rev=358696&view=rev
Log:
[CodeComplete] Remove obsolete isOutputBinary().

Summary:
It's never set to true. Its only effect would be to set stdout to binary mode.
Hopefully we have better ways of doing this by now :-)

Reviewers: hokein

Subscribers: jkorous, arphaman, kadircet, llvm-commits

Tags: #llvm

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

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

Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=358696&r1=358695&r2=358696&view=diff
==
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Thu Apr 18 10:35:55 2019
@@ -701,8 +701,7 @@ static bool isBlacklistedMember(const Na
 struct CompletionRecorder : public CodeCompleteConsumer {
   CompletionRecorder(const CodeCompleteOptions &Opts,
  llvm::unique_function ResultsCallback)
-  : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
- /*OutputIsBinary=*/false),
+  : CodeCompleteConsumer(Opts.getClangCompleteOpts()),
 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
 CCAllocator(std::make_shared()),
 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
@@ -823,8 +822,7 @@ class SignatureHelpCollector final : pub
 public:
   SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
  const SymbolIndex *Index, SignatureHelp &SigHelp)
-  : CodeCompleteConsumer(CodeCompleteOpts,
- /*OutputIsBinary=*/false),
+  : CodeCompleteConsumer(CodeCompleteOpts),
 SigHelp(SigHelp),
 Allocator(std::make_shared()),
 CCTUInfo(Allocator), Index(Index) {}


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


[PATCH] D59458: [analyzer][NFC] Clang-format CheckerRegistry

2019-04-18 Thread Kristóf Umann via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC358694: [analyzer][NFC] Clang-format CheckerRegistry 
(authored by Szelethus, committed by ).

Repository:
  rC Clang

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

https://reviews.llvm.org/D59458

Files:
  include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
  lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp

Index: lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp
===
--- lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp
+++ lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp
@@ -11,8 +11,8 @@
 #include "clang/Basic/LLVM.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
-#include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/StringMap.h"
@@ -39,8 +39,7 @@
 }
 
 namespace {
-template 
-struct FullNameLT {
+template  struct FullNameLT {
   bool operator()(const T &Lhs, const T &Rhs) {
 return Lhs.FullName < Rhs.FullName;
   }
@@ -76,13 +75,13 @@
  "to be already sorted!");
 
   // Use a binary search to find the possible start of the package.
-  CheckerRegistry::CheckerInfo
-  PackageInfo(nullptr, nullptr, CmdLineArg, "", "");
-  auto It = std::lower_bound(Checkers.begin(), Checkers.end(),
- PackageInfo, CheckerNameLT{});
+  CheckerRegistry::CheckerInfo PackageInfo(nullptr, nullptr, CmdLineArg, "",
+   "");
+  auto It = std::lower_bound(Checkers.begin(), Checkers.end(), PackageInfo,
+ CheckerNameLT{});
 
   if (!isInPackage(*It, CmdLineArg))
-return { Checkers.end(), Checkers.end() };
+return {Checkers.end(), Checkers.end()};
 
   // See how large the package is.
   // If the package doesn't exist, assume the option refers to a single
@@ -94,15 +93,14 @@
   if (PackageSize != PackageSizes.end())
 Size = PackageSize->getValue();
 
-  return { It, It + Size };
+  return {It, It + Size};
 }
 
 CheckerRegistry::CheckerRegistry(
- ArrayRef Plugins, DiagnosticsEngine &Diags,
- AnalyzerOptions &AnOpts, const LangOptions &LangOpts,
- ArrayRef>
- CheckerRegistrationFns)
-  : Diags(Diags), AnOpts(AnOpts), LangOpts(LangOpts) {
+ArrayRef Plugins, DiagnosticsEngine &Diags,
+AnalyzerOptions &AnOpts, const LangOptions &LangOpts,
+ArrayRef> CheckerRegistrationFns)
+: Diags(Diags), AnOpts(AnOpts), LangOpts(LangOpts) {
 
   // Register builtin checkers.
 #define GET_CHECKERS
@@ -135,22 +133,21 @@
   Diags.Report(diag::warn_incompatible_analyzer_plugin_api)
   << llvm::sys::path::filename(Plugin);
   Diags.Report(diag::note_incompatible_analyzer_plugin_api)
-  << CLANG_ANALYZER_API_VERSION_STRING
-  << PluginAPIVersion;
+  << CLANG_ANALYZER_API_VERSION_STRING << PluginAPIVersion;
   continue;
 }
 
 // Register its checkers.
 RegisterCheckersFn RegisterPluginCheckers =
-reinterpret_cast(Lib.getAddressOfSymbol(
- "clang_registerCheckers"));
+reinterpret_cast(
+Lib.getAddressOfSymbol("clang_registerCheckers"));
 if (RegisterPluginCheckers)
   RegisterPluginCheckers(*this);
   }
 
   // Register statically linked checkers, that aren't generated from the tblgen
-  // file, but rather passed their registry function as a parameter in 
-  // checkerRegistrationFns. 
+  // file, but rather passed their registry function as a parameter in
+  // checkerRegistrationFns.
 
   for (const auto &Fn : CheckerRegistrationFns)
 Fn(*this);
@@ -174,7 +171,7 @@
   // command line.
   for (const std::pair &Opt : AnOpts.CheckersControlList) {
 CheckerInfoListRange CheckerForCmdLineArg =
- getMutableCheckersForCmdLineArg(Opt.first);
+getMutableCheckersForCmdLineArg(Opt.first);
 
 if (CheckerForCmdLineArg.begin() == CheckerForCmdLineArg.end()) {
   Diags.Report(diag::err_unknown_analyzer_checker) << Opt.first;
@@ -182,22 +179,23 @@
 }
 
 for (CheckerInfo &checker : CheckerForCmdLineArg) {
-  checker.State = Opt.second ? StateFromCmdLine::State_Enabled :
-   StateFromCmdLine::State_Disabled;
+  checker.State = Opt.second ? StateFromCmdLine::State_Enabled
+ : StateFromCmdLine::State_Disabled;
 }
   }
 }
 
 /// Collects dependencies in \p ret, returns false on failure.
-static bool collectDependenciesImpl(
-  const CheckerRegistry::ConstCheckerInfoList &Deps,
-  const LangOptions &LO,
-  CheckerRegist

r358696 - [CodeComplete] Remove obsolete isOutputBinary().

2019-04-18 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Thu Apr 18 10:35:55 2019
New Revision: 358696

URL: http://llvm.org/viewvc/llvm-project?rev=358696&view=rev
Log:
[CodeComplete] Remove obsolete isOutputBinary().

Summary:
It's never set to true. Its only effect would be to set stdout to binary mode.
Hopefully we have better ways of doing this by now :-)

Reviewers: hokein

Subscribers: jkorous, arphaman, kadircet, llvm-commits

Tags: #llvm

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

Modified:
cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h
cfe/trunk/lib/Frontend/ASTUnit.cpp
cfe/trunk/lib/Frontend/CompilerInstance.cpp
cfe/trunk/tools/libclang/CIndexCodeCompletion.cpp
cfe/trunk/unittests/Sema/CodeCompleteTest.cpp

Modified: cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h?rev=358696&r1=358695&r2=358696&view=diff
==
--- cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h (original)
+++ cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h Thu Apr 18 10:35:55 2019
@@ -992,10 +992,6 @@ class CodeCompleteConsumer {
 protected:
   const CodeCompleteOptions CodeCompleteOpts;
 
-  /// Whether the output format for the code-completion consumer is
-  /// binary.
-  bool OutputIsBinary;
-
 public:
   class OverloadCandidate {
   public:
@@ -1066,9 +1062,8 @@ public:
   bool IncludeBriefComments) const;
   };
 
-  CodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
-   bool OutputIsBinary)
-  : CodeCompleteOpts(CodeCompleteOpts), OutputIsBinary(OutputIsBinary) {}
+  CodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts)
+  : CodeCompleteOpts(CodeCompleteOpts) {}
 
   /// Whether the code-completion consumer wants to see macros.
   bool includeMacros() const {
@@ -1106,9 +1101,6 @@ public:
 return CodeCompleteOpts.LoadExternal;
   }
 
-  /// Determine whether the output of this consumer is binary.
-  bool isOutputBinary() const { return OutputIsBinary; }
-
   /// Deregisters and destroys this code-completion consumer.
   virtual ~CodeCompleteConsumer();
 
@@ -1181,7 +1173,7 @@ public:
   /// results to the given raw output stream.
   PrintingCodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
raw_ostream &OS)
-  : CodeCompleteConsumer(CodeCompleteOpts, false), OS(OS),
+  : CodeCompleteConsumer(CodeCompleteOpts), OS(OS),
 CCTUInfo(std::make_shared()) {}
 
   /// Prints the finalized code-completion results.

Modified: cfe/trunk/lib/Frontend/ASTUnit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/ASTUnit.cpp?rev=358696&r1=358695&r2=358696&view=diff
==
--- cfe/trunk/lib/Frontend/ASTUnit.cpp (original)
+++ cfe/trunk/lib/Frontend/ASTUnit.cpp Thu Apr 18 10:35:55 2019
@@ -1877,8 +1877,7 @@ namespace {
   public:
 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
   const CodeCompleteOptions &CodeCompleteOpts)
-: CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
-  AST(AST), Next(Next) {
+: CodeCompleteConsumer(CodeCompleteOpts), AST(AST), Next(Next) {
   // Compute the set of contexts in which we will look when we don't have
   // any information about the specific context.
   NormalContexts

Modified: cfe/trunk/lib/Frontend/CompilerInstance.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/CompilerInstance.cpp?rev=358696&r1=358695&r2=358696&view=diff
==
--- cfe/trunk/lib/Frontend/CompilerInstance.cpp (original)
+++ cfe/trunk/lib/Frontend/CompilerInstance.cpp Thu Apr 18 10:35:55 2019
@@ -585,12 +585,6 @@ void CompilerInstance::createCodeComplet
 setCodeCompletionConsumer(nullptr);
 return;
   }
-
-  if (CompletionConsumer->isOutputBinary() &&
-  llvm::sys::ChangeStdoutToBinary()) {
-getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
-setCodeCompletionConsumer(nullptr);
-  }
 }
 
 void CompilerInstance::createFrontendTimer() {

Modified: cfe/trunk/tools/libclang/CIndexCodeCompletion.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/libclang/CIndexCodeCompletion.cpp?rev=358696&r1=358695&r2=358696&view=diff
==
--- cfe/trunk/tools/libclang/CIndexCodeCompletion.cpp (original)
+++ cfe/trunk/tools/libclang/CIndexCodeCompletion.cpp Thu Apr 18 10:35:55 2019
@@ -568,9 +568,8 @@ namespace {
 CaptureCompletionResults(const CodeCompleteOptions &Opts,
  AllocatedCXCodeCompleteResults &Results,
  CXTranslationUnit *TranslationUnit)
-

[PATCH] D59459: [analyzer][NFC] Prefer binary searches in CheckerRegistry

2019-04-18 Thread Kristóf Umann via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL358695: [analyzer][NFC] Prefer binary searches in 
CheckerRegistry (authored by Szelethus, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D59459?vs=195358&id=195781#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D59459

Files:
  cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
  cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp

Index: cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp
@@ -48,6 +48,28 @@
 using CheckerNameLT = FullNameLT;
 } // end of anonymous namespace
 
+template 
+static
+typename std::conditional::value,
+  typename CheckerOrPackageInfoList::const_iterator,
+  typename CheckerOrPackageInfoList::iterator>::type
+binaryFind(CheckerOrPackageInfoList &Collection, StringRef FullName) {
+
+  using CheckerOrPackage = typename CheckerOrPackageInfoList::value_type;
+  using CheckerOrPackageFullNameLT = FullNameLT;
+
+  assert(std::is_sorted(Collection.begin(), Collection.end(),
+CheckerOrPackageFullNameLT{}) &&
+ "In order to efficiently gather checkers/packages, this function "
+ "expects them to be already sorted!");
+
+  typename CheckerOrPackageInfoList::value_type Info(FullName);
+
+  return llvm::lower_bound(
+  Collection, Info,
+  FullNameLT{});
+}
+
 static constexpr char PackageSeparator = '.';
 
 static bool isInPackage(const CheckerRegistry::CheckerInfo &Checker,
@@ -69,16 +91,7 @@
 
 CheckerRegistry::CheckerInfoListRange
 CheckerRegistry::getMutableCheckersForCmdLineArg(StringRef CmdLineArg) {
-
-  assert(std::is_sorted(Checkers.begin(), Checkers.end(), CheckerNameLT{}) &&
- "In order to efficiently gather checkers, this function expects them "
- "to be already sorted!");
-
-  // Use a binary search to find the possible start of the package.
-  CheckerRegistry::CheckerInfo PackageInfo(nullptr, nullptr, CmdLineArg, "",
-   "");
-  auto It = std::lower_bound(Checkers.begin(), Checkers.end(), PackageInfo,
- CheckerNameLT{});
+  auto It = binaryFind(Checkers, CmdLineArg);
 
   if (!isInPackage(*It, CmdLineArg))
 return {Checkers.end(), Checkers.end()};
@@ -268,24 +281,18 @@
   }
 }
 
-void CheckerRegistry::addDependency(StringRef FullName, StringRef dependency) {
-  auto CheckerThatNeedsDeps = [&FullName](const CheckerInfo &Chk) {
-return Chk.FullName == FullName;
-  };
-  auto Dependency = [&dependency](const CheckerInfo &Chk) {
-return Chk.FullName == dependency;
-  };
-
-  auto CheckerIt = llvm::find_if(Checkers, CheckerThatNeedsDeps);
-  assert(CheckerIt != Checkers.end() &&
+void CheckerRegistry::addDependency(StringRef FullName, StringRef Dependency) {
+  auto CheckerIt = binaryFind(Checkers, FullName);
+  assert(CheckerIt != Checkers.end() && CheckerIt->FullName == FullName &&
  "Failed to find the checker while attempting to set up its "
  "dependencies!");
 
-  auto DependencyIt = llvm::find_if(Checkers, Dependency);
+  auto DependencyIt = binaryFind(Checkers, Dependency);
   assert(DependencyIt != Checkers.end() &&
+ DependencyIt->FullName == Dependency &&
  "Failed to find the dependency of a checker!");
 
-  CheckerIt->Dependencies.push_back(&*DependencyIt);
+  CheckerIt->Dependencies.emplace_back(&*DependencyIt);
 }
 
 void CheckerRegistry::initializeManager(CheckerManager &CheckerMgr) const {
Index: cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
===
--- cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
+++ cfe/trunk/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
@@ -108,8 +108,8 @@
   State_Enabled
 };
 
-InitializationFunction Initialize;
-ShouldRegisterFunction ShouldRegister;
+InitializationFunction Initialize = nullptr;
+ShouldRegisterFunction ShouldRegister = nullptr;
 StringRef FullName;
 StringRef Desc;
 StringRef DocumentationUri;
@@ -129,6 +129,9 @@
 StringRef Name, StringRef Desc, StringRef DocsUri)
 : Initialize(Fn), ShouldRegister(sfn), FullName(Name), Desc(Desc),
   DocumentationUri(DocsUri) {}
+
+// Used for lower_bound.
+explicit CheckerInfo(StringRef FullName) : FullName(FullName) {}
   };
 
   using StateFromCmdLine = CheckerInfo::StateFromCmdLine;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.

[PATCH] D60349: [COFF, ARM64] Fix ABI implementation of struct returns

2019-04-18 Thread Richard Townsend (Arm) via Phabricator via cfe-commits
richard.townsend.arm added inline comments.



Comment at: lib/CodeGen/MicrosoftCXXABI.cpp:1090
+FI.getReturnInfo().setSRetAfterThis(isInstanceMethod);
+FI.getReturnInfo().setInReg(isAArch64 && isIndirectReturn);
 

Based on https://reviews.llvm.org/D60348 - 
lib/Target/AArch64/AArch64CallingConvention.td (line 44), should this be 
(isIndirectReturn || isInstanceMethod)? 


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

https://reviews.llvm.org/D60349



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


[PATCH] D60800: [MS] Emit S_HEAPALLOCSITE debug info

2019-04-18 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 195783.
akhuang marked 4 inline comments as done.
akhuang added a comment.

Removed extraneous information from test; changed type to DIType


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60800

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGen/debug-info-codeview-heapallocsite.c
  llvm/include/llvm/CodeGen/MachineFunction.h
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h
  llvm/lib/CodeGen/MachineFunction.cpp
  llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
  llvm/test/CodeGen/X86/label-heapallocsite.ll

Index: llvm/test/CodeGen/X86/label-heapallocsite.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/label-heapallocsite.ll
@@ -0,0 +1,68 @@
+; RUN: llc -O0 < %s | FileCheck %s
+; FIXME: Add test for llc with optimizations once it is implemented.
+
+; Source to regenerate:
+; $ clang --target=x86_64-windows-msvc -S heapallocsite.c  -g -gcodeview -o t.ll \
+;  -emit-llvm -O0 -Xclang -disable-llvm-passes -fms-extensions
+; __declspec(allocator) char *myalloc();
+; void g();
+; void foo() {
+;   g();
+;   myalloc()
+;   g();
+; }
+
+target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-windows-msvc"
+
+; Function Attrs: noinline nounwind optnone
+define dso_local void @f() #0 !dbg !7 {
+entry:
+  call void @g(), !dbg !11
+  %call = call i8* @myalloc(), !dbg !12, !heapallocsite !13
+  call void @g(), !dbg !14
+  ret void, !dbg !15
+}
+
+; CHECK-LABEL: f: # @f
+; CHECK: callq g
+; CHECK: .Lheapallocsite0:
+; CHECK: callq myalloc
+; CHECK: .Lheapallocsite1:
+; CHECK: retq
+
+; CHECK-LABEL: .short  4423# Record kind: S_GPROC32_ID
+; CHECK:   .short  4446# Record kind: S_HEAPALLOCSITE
+; CHECK-NEXT:  .secrel32   .Lheapallocsite0
+; CHECK-NEXT:  .secidx .Lheapallocsite0
+; CHECK-NEXT:  .short  .Lheapallocsite1-.Lheapallocsite0
+; CHECK-NEXT:  .long 112
+; CHECK-NEXT:  .p2align 2
+
+; CHECK-LABEL: .short  4431# Record kind: S_PROC_ID_END
+
+declare dso_local void @g() #1
+
+declare dso_local i8* @myalloc() #1
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5}
+!llvm.ident = !{!6}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!2 = !{}
+!3 = !{i32 2, !"CodeView", i32 1}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 2}
+!6 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)"}
+!7 = distinct !DISubprogram(name: "f", scope: !8, file: !8, line: 4, type: !9, scopeLine: 4, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
+!8 = !DIFile(filename: "heapallocsite.c", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!9 = !DISubroutineType(types: !10)
+!10 = !{null}
+!11 = !DILocation(line: 5, scope: !7)
+!12 = !DILocation(line: 6, scope: !7)
+!13 = !DIBasicType(name: "char", size: 8, encoding: DW_ATE_signed_char)
+!14 = !DILocation(line: 7, scope: !7)
+!15 = !DILocation(line: 8, scope: !7)
+
Index: llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
===
--- llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
+++ llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
@@ -1234,6 +1234,13 @@
   if (CLI.NumResultRegs && CLI.CS)
 updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs);
 
+  // Set labels for heapallocsite call.
+  if (CLI.CS && CLI.CS->getInstruction()->getMetadata("heapallocsite")) {
+DIType *DI = cast(CLI.CS->getInstruction()->
+  getMetadata("heapallocsite"));
+MF->addCodeViewHeapAllocSite(CLI.Call, DI);
+  }
+
   return true;
 }
 
Index: llvm/lib/CodeGen/MachineFunction.cpp
===
--- llvm/lib/CodeGen/MachineFunction.cpp
+++ llvm/lib/CodeGen/MachineFunction.cpp
@@ -806,6 +806,14 @@
   return FilterID;
 }
 
+void MachineFunction::addCodeViewHeapAllocSite(MachineInstr *I, DIType *DI) {
+  MCSymbol *BeginLabel = Ctx.createTempSymbol("heapallocsite", true);
+  MCSymbol *EndLabel = Ctx.createTempSymbol("heapallocsite", true);
+  I->setPreInstrSymbol(*this, BeginLabel);
+  I->setPostInstrSymbol(*this, EndLabel);
+  CodeViewHeapAllocSites.push_back({BeginLabel, EndLabel, DI});
+}
+
 /// \}
 
 //===--===//
Index: llvm/lib/Co

[PATCH] D60800: [MS] Emit S_HEAPALLOCSITE debug info

2019-04-18 Thread Amy Huang via Phabricator via cfe-commits
akhuang added inline comments.



Comment at: clang/lib/CodeGen/CGDebugInfo.cpp:1966
+  QualType PointeeTy = D.getTypePtr()->getPointeeType();
+  llvm::DIType *DI = getOrCreateType(PointeeTy, getOrCreateFile(Loc));
+  CI->setMetadata("heapallocsite", DI);

hans wrote:
> I don't really know this code, but does this also work for void pointers, 
> i.e. the if statement in the old code was unnecessary?
I think `getOrCreateType` returns null if it gets a void type, so it doesn't 
quite work for void pointers. In theory we shouldn't be getting void pointers 
here since the type should be cast to something but that hasn't been 
implemented yet.



Comment at: llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp:1078
+  MCSymbol *EndLabel = std::get<1>(HeapAllocSite);
+  DIType *DITy = cast(std::get<2>(HeapAllocSite));
+

hans wrote:
> Is the cast necessary? Couldn't the tuple member be made a DIType* in the 
> first place?
Changed the tuple member to be a DIType.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60800



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


r358697 - [LibTooling] Extend Transformer to support multiple simultaneous changes.

2019-04-18 Thread Yitzhak Mandelbaum via cfe-commits
Author: ymandel
Date: Thu Apr 18 10:52:24 2019
New Revision: 358697

URL: http://llvm.org/viewvc/llvm-project?rev=358697&view=rev
Log:
[LibTooling] Extend Transformer to support multiple simultaneous changes.

Summary: This revision allows users to specify independent changes to multiple 
(related) sections of the input.  Previously, only a single section of input 
could be selected for replacement.

Reviewers: ilya-biryukov

Reviewed By: ilya-biryukov

Subscribers: jfb, cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/include/clang/Tooling/Refactoring/Transformer.h
cfe/trunk/lib/Tooling/Refactoring/Transformer.cpp
cfe/trunk/unittests/Tooling/TransformerTest.cpp

Modified: cfe/trunk/include/clang/Tooling/Refactoring/Transformer.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/Refactoring/Transformer.h?rev=358697&r1=358696&r2=358697&view=diff
==
--- cfe/trunk/include/clang/Tooling/Refactoring/Transformer.h (original)
+++ cfe/trunk/include/clang/Tooling/Refactoring/Transformer.h Thu Apr 18 
10:52:24 2019
@@ -20,13 +20,13 @@
 #include "clang/ASTMatchers/ASTMatchersInternal.h"
 #include "clang/Tooling/Refactoring/AtomicChange.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/Error.h"
 #include 
 #include 
 #include 
 #include 
 #include 
-#include 
 
 namespace clang {
 namespace tooling {
@@ -47,6 +47,98 @@ enum class NodePart {
 using TextGenerator =
 std::function;
 
+/// Wraps a string as a TextGenerator.
+inline TextGenerator text(std::string M) {
+  return [M](const ast_matchers::MatchFinder::MatchResult &) { return M; };
+}
+
+// Description of a source-code edit, expressed in terms of an AST node.
+// Includes: an ID for the (bound) node, a selector for source related to the
+// node, a replacement and, optionally, an explanation for the edit.
+//
+// * Target: the source code impacted by the rule. This identifies an AST node,
+//   or part thereof (\c Part), whose source range indicates the extent of the
+//   replacement applied by the replacement term.  By default, the extent is 
the
+//   node matched by the pattern term (\c NodePart::Node). Target's are typed
+//   (\c Kind), which guides the determination of the node extent.
+//
+// * Replacement: a function that produces a replacement string for the target,
+//   based on the match result.
+//
+// * Note: (optional) a note specifically for this edit, potentially 
referencing
+//   elements of the match.  This will be displayed to the user, where 
possible;
+//   for example, in clang-tidy diagnostics.  Use of notes should be rare --
+//   explanations of the entire rewrite should be set in the rule
+//   (`RewriteRule::Explanation`) instead.  Notes serve the rare cases wherein
+//   edit-specific diagnostics are required.
+//
+// `ASTEdit` should be built using the `change` convenience fucntions. For
+// example,
+// \code
+//   change(fun, NodePart::Name, "Frodo")
+// \endcode
+// Or, if we use Stencil for the TextGenerator:
+// \code
+//   change(thenNode, stencil::cat("{", thenNode, "}"))
+//   change(call, NodePart::Args, stencil::cat(x, ",", y))
+// .note("argument order changed.")
+// \endcode
+// Or, if you are changing the node corresponding to the rule's matcher, you 
can
+// use the single-argument override of \c change:
+// \code
+//   change("different_expr")
+// \endcode
+struct ASTEdit {
+  // The (bound) id of the node whose source will be replaced.  This id should
+  // never be the empty string.
+  std::string Target;
+  ast_type_traits::ASTNodeKind Kind;
+  NodePart Part;
+  TextGenerator Replacement;
+  TextGenerator Note;
+};
+
+// Convenience functions for creating \c ASTEdits.  They all must be explicitly
+// instantiated with the desired AST type.  Each overload includes both \c
+// std::string and \c TextGenerator versions.
+
+// FIXME: For overloads taking a \c NodePart, constrain the valid values of \c
+// Part based on the type \c T.
+template 
+ASTEdit change(StringRef Target, NodePart Part, TextGenerator Replacement) {
+  ASTEdit E;
+  E.Target = Target.str();
+  E.Kind = ast_type_traits::ASTNodeKind::getFromNodeKind();
+  E.Part = Part;
+  E.Replacement = std::move(Replacement);
+  return E;
+}
+
+template 
+ASTEdit change(StringRef Target, NodePart Part, std::string Replacement) {
+  return change(Target, Part, text(std::move(Replacement)));
+}
+
+/// Variant of \c change for which the NodePart defaults to the whole node.
+template 
+ASTEdit change(StringRef Target, TextGenerator Replacement) {
+  return change(Target, NodePart::Node, std::move(Replacement));
+}
+
+/// Variant of \c change for which the NodePart defaults to the whole node.
+template 
+ASTEdit change(StringRef Target, std::string Replacement) {
+  return change(Target, text(std::move(Replacement)));
+}
+
+/// Variant of \c change t

[PATCH] D60408: [LibTooling] Extend Transformer to support multiple simultaneous changes.

2019-04-18 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
ymandel marked 2 inline comments as done.
Closed by commit rL358697: [LibTooling] Extend Transformer to support multiple 
simultaneous changes. (authored by ymandel, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D60408?vs=195365&id=195785#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D60408

Files:
  cfe/trunk/include/clang/Tooling/Refactoring/Transformer.h
  cfe/trunk/lib/Tooling/Refactoring/Transformer.cpp
  cfe/trunk/unittests/Tooling/TransformerTest.cpp

Index: cfe/trunk/lib/Tooling/Refactoring/Transformer.cpp
===
--- cfe/trunk/lib/Tooling/Refactoring/Transformer.cpp
+++ cfe/trunk/lib/Tooling/Refactoring/Transformer.cpp
@@ -144,60 +144,78 @@
   llvm_unreachable("Unexpected case in NodePart type.");
 }
 
-Expected
-tooling::applyRewriteRule(const RewriteRule &Rule,
-  const ast_matchers::MatchFinder::MatchResult &Match) {
-  if (Match.Context->getDiagnostics().hasErrorOccurred())
-return Transformation();
-
-  auto &NodesMap = Match.Nodes.getMap();
-  auto It = NodesMap.find(Rule.Target);
-  assert (It != NodesMap.end() && "Rule.Target must be bound in the match.");
-
-  Expected TargetOrErr =
-  getTargetRange(Rule.Target, It->second, Rule.TargetKind, Rule.TargetPart,
- *Match.Context);
-  if (auto Err = TargetOrErr.takeError())
-return std::move(Err);
-  auto &Target = *TargetOrErr;
-  if (Target.isInvalid() ||
-  isOriginMacroBody(*Match.SourceManager, Target.getBegin()))
-return Transformation();
-
-  return Transformation{Target, Rule.Replacement(Match)};
+Expected>
+tooling::translateEdits(const MatchResult &Result,
+llvm::ArrayRef Edits) {
+  SmallVector Transformations;
+  auto &NodesMap = Result.Nodes.getMap();
+  for (const auto &Edit : Edits) {
+auto It = NodesMap.find(Edit.Target);
+assert(It != NodesMap.end() && "Edit target must be bound in the match.");
+
+Expected RangeOrErr = getTargetRange(
+Edit.Target, It->second, Edit.Kind, Edit.Part, *Result.Context);
+if (auto Err = RangeOrErr.takeError())
+  return std::move(Err);
+Transformation T;
+T.Range = *RangeOrErr;
+if (T.Range.isInvalid() ||
+isOriginMacroBody(*Result.SourceManager, T.Range.getBegin()))
+  return SmallVector();
+T.Replacement = Edit.Replacement(Result);
+Transformations.push_back(std::move(T));
+  }
+  return Transformations;
 }
 
-constexpr llvm::StringLiteral RewriteRule::RootId;
-
-RewriteRuleBuilder RewriteRuleBuilder::replaceWith(TextGenerator T) {
-  Rule.Replacement = std::move(T);
-  return *this;
+RewriteRule tooling::makeRule(ast_matchers::internal::DynTypedMatcher M,
+  SmallVector Edits) {
+  M.setAllowBind(true);
+  // `tryBind` is guaranteed to succeed, because `AllowBind` was set to true.
+  return RewriteRule{*M.tryBind(RewriteRule::RootId), std::move(Edits)};
 }
 
-RewriteRuleBuilder RewriteRuleBuilder::because(TextGenerator T) {
-  Rule.Explanation = std::move(T);
-  return *this;
-}
+constexpr llvm::StringLiteral RewriteRule::RootId;
 
 void Transformer::registerMatchers(MatchFinder *MatchFinder) {
   MatchFinder->addDynamicMatcher(Rule.Matcher, this);
 }
 
 void Transformer::run(const MatchResult &Result) {
-  auto ChangeOrErr = applyRewriteRule(Rule, Result);
-  if (auto Err = ChangeOrErr.takeError()) {
-llvm::errs() << "Rewrite failed: " << llvm::toString(std::move(Err))
+  if (Result.Context->getDiagnostics().hasErrorOccurred())
+return;
+
+  // Verify the existence and validity of the AST node that roots this rule.
+  auto &NodesMap = Result.Nodes.getMap();
+  auto Root = NodesMap.find(RewriteRule::RootId);
+  assert(Root != NodesMap.end() && "Transformation failed: missing root node.");
+  SourceLocation RootLoc = Result.SourceManager->getExpansionLoc(
+  Root->second.getSourceRange().getBegin());
+  assert(RootLoc.isValid() && "Invalid location for Root node of match.");
+
+  auto TransformationsOrErr = translateEdits(Result, Rule.Edits);
+  if (auto Err = TransformationsOrErr.takeError()) {
+llvm::errs() << "Transformation failed: " << llvm::toString(std::move(Err))
  << "\n";
 return;
   }
-  auto &Change = *ChangeOrErr;
-  auto &Range = Change.Range;
-  if (Range.isInvalid()) {
+  auto &Transformations = *TransformationsOrErr;
+  if (Transformations.empty()) {
 // No rewrite applied (but no error encountered either).
+RootLoc.print(llvm::errs() << "note: skipping match at loc ",
+  *Result.SourceManager);
+llvm::errs() << "\n";
 return;
   }
-  AtomicChange AC(*Result.SourceManager, Range.getBegin());
-  if (auto Err = AC.replace(*Result.SourceManager, R

[PATCH] D60872: Add new warning knob for unknown attribute namespaces

2019-04-18 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added inline comments.



Comment at: lib/Sema/SemaDeclAttr.cpp:8623
+  } else if (A.hasScope()) {
+#define ATTR(A)
+#define ATTR_NAMESPACE(A) .Case(#A, false)

dblaikie wrote:
> Not sure how it's done elsewhere - but I'd sink these #defines down to 
> immediately before the #include
I think most other uses of .inc files only #define the macros they need to - 
assuming the others aren't defined, rather than explicitly providing an empty 
definition? (but I'm not sure - I guess that means teh .inc file needs a 
#ifndef X \ #define X #endif - but perhaps .inc files usually have those?)



Comment at: lib/Sema/SemaDeclAttr.cpp:8623-8624
+  } else if (A.hasScope()) {
+#define ATTR(A)
+#define ATTR_NAMESPACE(A) .Case(#A, false)
+if (llvm::StringSwitch(A.getScopeName()->getName())

Not sure how it's done elsewhere - but I'd sink these #defines down to 
immediately before the #include



Comment at: lib/Sema/SemaDeclAttr.cpp:8629-8630
+  Warning = diag::warn_unknown_attribute_namespace_ignored;
+#undef ATTR_NAMESPACE
+#undef ATTR
+  } else if (A.isC2xAttribute() || A.isCXX11Attribute()) {

Should AttrList.inc handle undefing all its attributes - so all its users don't 
have to?



Comment at: utils/TableGen/ClangAttrEmitter.cpp:2553
 
+void copyAttrNamespaces(std::set &S) const {
+  for (const Record *R : Attrs) {

Maybe "addAttrNamespacesTo" (not clear whether this would overwrite the contens 
of the std::set, or add to it)


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

https://reviews.llvm.org/D60872



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


[PATCH] D55044: [clang-tidy] check for Abseil make_unique

2019-04-18 Thread Don Hinton via Phabricator via cfe-commits
hintonda added inline comments.



Comment at: clang-tidy/abseil/AbseilTidyModule.cpp:77
+Opts["abseil-make-unique.MakeSmartPtrFunction"] = "absl::make_unique";
+Opts["abseil-make-unique.IgnoreListInit"] = true;
+return Options;

This is defined as `typedef std::map OptionMap;`, so 
you need to assign a string, not a literal `true` value.  hth...


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

https://reviews.llvm.org/D55044



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


[PATCH] D60872: Add new warning knob for unknown attribute namespaces

2019-04-18 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman marked 7 inline comments as done.
aaron.ballman added inline comments.



Comment at: lib/Sema/SemaDeclAttr.cpp:8623
+  } else if (A.hasScope()) {
+#define ATTR(A)
+#define ATTR_NAMESPACE(A) .Case(#A, false)

dblaikie wrote:
> dblaikie wrote:
> > Not sure how it's done elsewhere - but I'd sink these #defines down to 
> > immediately before the #include
> I think most other uses of .inc files only #define the macros they need to - 
> assuming the others aren't defined, rather than explicitly providing an empty 
> definition? (but I'm not sure - I guess that means teh .inc file needs a 
> #ifndef X \ #define X #endif - but perhaps .inc files usually have those?)
This file is generated without a default for `ATTR`, so there are a few places 
where we have to define it to an empty macro. I could add it to the emitter and 
remove a few of these spurious definitions, but that can be done in a follow-up.



Comment at: lib/Sema/SemaDeclAttr.cpp:8623-8624
+  } else if (A.hasScope()) {
+#define ATTR(A)
+#define ATTR_NAMESPACE(A) .Case(#A, false)
+if (llvm::StringSwitch(A.getScopeName()->getName())

aaron.ballman wrote:
> dblaikie wrote:
> > dblaikie wrote:
> > > Not sure how it's done elsewhere - but I'd sink these #defines down to 
> > > immediately before the #include
> > I think most other uses of .inc files only #define the macros they need to 
> > - assuming the others aren't defined, rather than explicitly providing an 
> > empty definition? (but I'm not sure - I guess that means teh .inc file 
> > needs a #ifndef X \ #define X #endif - but perhaps .inc files usually have 
> > those?)
> This file is generated without a default for `ATTR`, so there are a few 
> places where we have to define it to an empty macro. I could add it to the 
> emitter and remove a few of these spurious definitions, but that can be done 
> in a follow-up.
I think it's pretty awkward either way, so I'll go with your approach.



Comment at: lib/Sema/SemaDeclAttr.cpp:8629-8630
+  Warning = diag::warn_unknown_attribute_namespace_ignored;
+#undef ATTR_NAMESPACE
+#undef ATTR
+  } else if (A.isC2xAttribute() || A.isCXX11Attribute()) {

dblaikie wrote:
> Should AttrList.inc handle undefing all its attributes - so all its users 
> don't have to?
Good catch -- it already does that for me. I'll remove.



Comment at: utils/TableGen/ClangAttrEmitter.cpp:2553
 
+void copyAttrNamespaces(std::set &S) const {
+  for (const Record *R : Attrs) {

dblaikie wrote:
> Maybe "addAttrNamespacesTo" (not clear whether this would overwrite the 
> contens of the std::set, or add to it)
Good catch, I missed renaming it after a signature change where it was 
accepting an iterator instead of the container directly.


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

https://reviews.llvm.org/D60872



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


[PATCH] D60872: Add new warning knob for unknown attribute namespaces

2019-04-18 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman updated this revision to Diff 195790.
aaron.ballman marked 3 inline comments as done.
aaron.ballman added a comment.

Updated based on review feedback.


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

https://reviews.llvm.org/D60872

Files:
  include/clang/Basic/DiagnosticCommonKinds.td
  include/clang/Basic/DiagnosticGroups.td
  include/clang/Sema/Sema.h
  lib/Parse/ParseDecl.cpp
  lib/Sema/SemaDeclAttr.cpp
  lib/Sema/SemaDeclCXX.cpp
  lib/Sema/SemaStmtAttr.cpp
  lib/Sema/SemaType.cpp
  test/SemaCXX/attr-cxx0x.cpp
  utils/TableGen/ClangAttrEmitter.cpp

Index: utils/TableGen/ClangAttrEmitter.cpp
===
--- utils/TableGen/ClangAttrEmitter.cpp
+++ utils/TableGen/ClangAttrEmitter.cpp
@@ -17,7 +17,6 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
-#include "llvm/ADT/StringSet.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -2551,6 +2550,16 @@
   ::emitAttrList(OS, Descriptor.MacroName, Attrs);
 }
 
+void addAttrNamespacesTo(std::set &S) const {
+  for (const Record *R : Attrs) {
+std::vector Spellings = GetFlattenedSpellings(*R);
+for (const auto &Spell : Spellings) {
+  if (!Spell.nameSpace().empty())
+S.insert(Spell.nameSpace());
+}
+  }
+}
+
 void classifyAttrOnRoot(Record *Attr) {
   bool result = classifyAttr(Attr);
   assert(result && "failed to classify on root"); (void) result;
@@ -2621,6 +2630,19 @@
 #endif
 }
 
+void emitAttrNamespaces(raw_ostream &OS) const {
+  // Gather the unique set of attribute namespaces Clang knows about. We
+  // want this set to be ordered so we can do efficient lookups.
+  std::set Namespaces;
+  for (const auto &Class : Classes) {
+Class->addAttrNamespacesTo(Namespaces);
+  }
+  // Emit the list of namespaces.
+  for (const auto &Namespace : Namespaces) {
+OS << "ATTR_NAMESPACE(" << Namespace << ")\n";
+  }
+}
+
 void emitDefaultDefines(raw_ostream &OS) const {
   for (auto &Class : Classes) {
 Class->emitDefaultDefines(OS);
@@ -2682,6 +2704,7 @@
   // Add defaulting macro definitions.
   Hierarchy.emitDefaultDefines(OS);
   emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);
+  emitDefaultDefine(OS, "ATTR_NAMESPACE", nullptr);
 
   std::vector Attrs = Records.getAllDerivedDefinitions("Attr");
   std::vector PragmaAttrs;
@@ -2702,6 +2725,7 @@
 
   // Emit the ad hoc groups.
   emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
+  Hierarchy.emitAttrNamespaces(OS);
 
   // Emit the attribute ranges.
   OS << "#ifdef ATTR_RANGE\n";
@@ -2711,6 +2735,7 @@
 
   Hierarchy.emitUndefs(OS);
   OS << "#undef PRAGMA_SPELLING_ATTR\n";
+  OS << "#undef ATTR_NAMESPACE\n";
 }
 
 // Emits the enumeration list for attributes.
Index: test/SemaCXX/attr-cxx0x.cpp
===
--- test/SemaCXX/attr-cxx0x.cpp
+++ test/SemaCXX/attr-cxx0x.cpp
@@ -1,4 +1,6 @@
-// RUN: %clang_cc1 -fsyntax-only -fcxx-exceptions -verify -pedantic -std=c++11 %s
+// RUN: %clang_cc1 -fsyntax-only -fcxx-exceptions -verify -pedantic -DUNKNOWN_ATTRS -std=c++11 %s
+// RUN: %clang_cc1 -fsyntax-only -fcxx-exceptions -verify -pedantic -Wno-unknown-attributes -std=c++11 %s
+// RUN: %clang_cc1 -fsyntax-only -fcxx-exceptions -verify -pedantic -Wno-unknown-attributes -Wunknown-attribute-namespaces -DUNKNOWN_NAMESPACE -std=c++11 %s
 
 int align_illegal alignas(3); //expected-error {{requested alignment is not a power of 2}}
 char align_big alignas(int);
@@ -46,7 +48,25 @@
 
 static_assert(alignof(int(int)) >= 1, "alignof(function) not positive"); // expected-error{{invalid application of 'alignof' to a function type}}
 
-[[__carries_dependency__]]  // expected-warning{{unknown attribute '__carries_dependency__' ignored}}
+#if defined(UNKNOWN_ATTRS) || defined(UNKNOWN_NAMESPACE)
+// expected-warning@+2 {{unknown attribute '__carries_dependency__' ignored}}
+#endif
+[[__carries_dependency__]]
 void func(void);
 
 alignas(4) auto PR19252 = 0;
+
+#if defined(UNKNOWN_ATTRS) || defined(UNKNOWN_NAMESPACE)
+// expected-warning@+2 {{unknown attribute 'frobble' ignored}}
+#endif
+[[frobble]] int unknown1;
+
+#if defined(UNKNOWN_ATTRS) || defined(UNKNOWN_NAMESPACE)
+// expected-warning@+2 {{unknown attribute 'bobble' ignored}}
+#endif
+[[frobble::bobble]] int unknown2;
+
+#ifdef UNKNOWN_ATTRS
+// expected-warning@+2 {{unknown attribute 'unknown_attribute' ignored}}
+#endif
+[[gsl::unknown_attribute]] int unknown3;
Index: lib/Sema/SemaType.cpp
===
--- lib/Sema/SemaType.cpp
+++ lib/Sema/SemaType.cpp
@@ -7441,9 +7441,7 @@
 
 case ParsedAttr::UnknownAttribute:
   if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
-state.getSema()

[PATCH] D55044: [clang-tidy] check for Abseil make_unique

2019-04-18 Thread Andy Zhang via Phabricator via cfe-commits
axzhang marked 3 inline comments as done.
axzhang added inline comments.



Comment at: clang-tidy/modernize/MakeSmartPtrCheck.cpp:69
+  IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", true)),
+  IgnoreListInit(Options.get("IgnoreListInit", false)) {}
 

hintonda wrote:
> hintonda wrote:
> > axzhang wrote:
> > > hintonda wrote:
> > > > You’re setting it false here.
> > > I thought that false was the default value if the options do not contain 
> > > "IgnoreListInit"?
> > Do you have a test that passes this option?  I didn’t see one.
> I could be wrong, but when you do an Options.get(), that looks at what was 
> passed on the commandline, and if it wasn't found, it sets the default 
> provided.
Fixed by changing the Options value to "1" instead of true in the 
AbseilTidyModule


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

https://reviews.llvm.org/D55044



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


[PATCH] D60163: [ThinLTO] Handle -fno-builtin* options for distributed backends

2019-04-18 Thread Teresa Johnson via Phabricator via cfe-commits
tejohnson added a comment.

ping


Repository:
  rC Clang

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

https://reviews.llvm.org/D60163



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


[PATCH] D55044: [clang-tidy] check for Abseil make_unique

2019-04-18 Thread Andy Zhang via Phabricator via cfe-commits
axzhang updated this revision to Diff 195791.
axzhang added a comment.

Simplify tests and fix issues with Options.


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

https://reviews.llvm.org/D55044

Files:
  clang-tidy/abseil/AbseilTidyModule.cpp
  clang-tidy/modernize/MakeSmartPtrCheck.cpp
  clang-tidy/modernize/MakeSmartPtrCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/abseil-make-unique.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/modernize-make-unique.rst
  test/clang-tidy/abseil-make-unique.cpp

Index: test/clang-tidy/abseil-make-unique.cpp
===
--- /dev/null
+++ test/clang-tidy/abseil-make-unique.cpp
@@ -0,0 +1,67 @@
+// RUN: %check_clang_tidy %s abseil-make-unique %t -- -- -std=c++11 \
+// RUN:   -I%S/Inputs/modernize-smart-ptr
+
+#include "unique_ptr.h"
+#include "initializer_list.h"
+// CHECK-FIXES: #include "absl/memory/memory.h"
+
+class A {
+ int x;
+ int y;
+
+ public:
+   A(int _x, int _y): x(_x), y(_y) {}
+};
+
+struct B {
+  B(std::initializer_list);
+  B();
+};
+
+struct Base {
+  Base();
+};
+
+struct Derived : public Base {
+  Derived();
+};
+
+int* returnPointer();
+
+std::unique_ptr makeAndReturnPointer() {
+  return std::unique_ptr(new int(0));
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: return absl::make_unique(0);
+}
+
+void Positives() {
+  std::unique_ptr P1 = std::unique_ptr(new int(1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:29: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: std::unique_ptr P1 = absl::make_unique(1);
+
+  P1.reset(new int(2));
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: P1 = absl::make_unique(2);
+
+  // Non-primitive paramter
+  std::unique_ptr P2 = std::unique_ptr(new A(1, 2));
+  // CHECK-MESSAGES: :[[@LINE-1]]:27: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: std::unique_ptr P2 = absl::make_unique(1, 2);
+
+  P2.reset(new A(3, 4));
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: P2 = absl::make_unique(3, 4);
+}
+
+void Negatives() {
+  // Only warn if explicitly allocating a new object
+  std::unique_ptr R = std::unique_ptr(returnPointer());
+  R.reset(returnPointer());
+
+  // Only replace if the template type is same as new type
+  auto Pderived = std::unique_ptr(new Derived());
+
+  // Ignore initializer-list constructors
+  std::unique_ptr PInit = std::unique_ptr(new B{1, 2});
+  PInit.reset(new B{1, 2});
+}
Index: docs/clang-tidy/checks/modernize-make-unique.rst
===
--- docs/clang-tidy/checks/modernize-make-unique.rst
+++ docs/clang-tidy/checks/modernize-make-unique.rst
@@ -48,3 +48,9 @@
 
If set to non-zero, the check will not give warnings inside macros. Default
is `1`.
+
+.. option:: IgnoreListInit
+   
+   If set to non-zero, the check will ignore list initializations of `new`
+   expressions. Default is `0`.
+
Index: docs/clang-tidy/checks/list.rst
===
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -13,6 +13,7 @@
abseil-duration-subtraction
abseil-duration-unnecessary-conversion
abseil-faster-strsplit-delimiter
+   abseil-make-unique (redirects to modernize-make-unique) 
abseil-no-internal-dependencies
abseil-no-namespace
abseil-redundant-strcat-calls
Index: docs/clang-tidy/checks/abseil-make-unique.rst
===
--- /dev/null
+++ docs/clang-tidy/checks/abseil-make-unique.rst
@@ -0,0 +1,22 @@
+.. title:: clang-tidy - abseil-make-unique
+.. meta::
+   :http-equiv=refresh: 5;URL=abseil-make-unique.html
+
+abseil-make-unique
+==
+
+This check finds the creation of ``std::unique_ptr`` objects by explicitly
+calling the constructor and a ``new`` expression, and replaces it with a call
+to ``absl::make_unique``, the Abseil implementation of ``std::make_unique`` 
+in C++11.
+
+.. code-block:: c++
+
+  auto ptr = std::unique_ptr(new int(1));
+
+  // becomes
+
+  auto ptr = absl::make_unique(1);
+
+The Abseil Style Guide _ discusses this issue in
+more detail.
Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -85,6 +85,11 @@
   Finds and fixes cases where ``absl::Duration`` values are being converted to
   numeric types and back again.
 
+- New alias :doc:`abseil-make-unique
+  ` to :doc:`modernize-make-unique
+  `
+  added.
+
 - New :doc:`abseil-time-subtraction
   ` check.
 
@@ -104,6 +109,11 @@
   `CommentUserDefiniedLiterals`, `CommentStringLiterals`,
   `CommentCharacterLiterals` & `Commen

  1   2   >