[PATCH] D66538: [AST] AST structural equivalence to work internally with pairs.

2019-08-26 Thread Balázs Kéri via Phabricator via cfe-commits
balazske marked 2 inline comments as done.
balazske added a comment.

I remember that we had "problems" with nonsense ODR warnings where both 
declarations are the same. Probably the reason for it was this cache problem. 
Still the `NonEquivalentDecls` as cache is useful to filter out the 
non-equivalences that were already encountered to not produce repeated warnings 
for them.




Comment at: clang/unittests/AST/StructuralEquivalenceTest.cpp:1357
+
+  EXPECT_FALSE(isInNonEqCache(C));
+  EXPECT_FALSE(isInNonEqCache(findDeclPair(

a_sidorin wrote:
> The declarations of C are not equivalent, but they are not placed into the 
> non-equivalence cache. This looks strange to me, could you please explain 
> this behavior?
We can not know which declarations go into the `NonEquivalentDecls` (at least I 
do not expect it from this "interface"). It is only meaningful to test that 
there are no wrong (equivalent) values in it. I think users of this function 
should not rely on what exactly is put into the `NonEquivalentDecls`  because 
it is "implementation dependent". Currently the first encountered 
non-equivalence (during the internal checks) is put into it only, that is here 
the `A` and `B`. It can be a future work to put every encountered 
non-equivalent declaration into the cache but even that code will find these 
only until the first non-equivalence is encountered.



Comment at: clang/unittests/AST/StructuralEquivalenceTest.cpp:1399
+  TU, cxxRecordDecl(hasName("A"), unless(isImplicit());
+  EXPECT_FALSE(isInNonEqCache(
+  findDeclPair(TU, functionDecl(hasName("x");

a_sidorin wrote:
> We don't have any tests where isInNonEqCache() can return true. Is it 
> expected?
Yes, the specification for `IsEquivalent` should say that it returns if the 
declaratiopns are equivalent and puts something into the `NonEquivalentDecls` 
that is not equivalent. (This "something" is the first encountered 
non-equivalence and for this the warning message may be produced.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66538



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


[PATCH] D66723: [clangd] Add a distinct highlighting for local variables

2019-08-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.h:38
   Primitive,
+  LocalVariable,
 

NIT: maybe put it right after `Variable`? IIUC, we do not rely on actual 
numeric values being the same across different clangd versions.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66723



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


[PATCH] D66723: [clangd] Add a distinct highlighting for local variables

2019-08-26 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:229
+if (const VarDecl *VD = dyn_cast(D)) {
+  if (VD->isLocalVarDecl()) {
+addToken(Loc, HighlightingKind::LocalVariable);

nit: `addToken(Loc, VD->isLocalVarDecl() ? HighlightingKind::LocalVariable : 
HighlightingKind::Variable)`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66723



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


[PATCH] D66723: [clangd] Add a distinct highlighting for local variables

2019-08-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.h:38
   Primitive,
+  LocalVariable,
 

ilya-biryukov wrote:
> NIT: maybe put it right after `Variable`? IIUC, we do not rely on actual 
> numeric values being the same across different clangd versions.
+1, related symbols should be grouped together.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66723



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


[clang-tools-extra] r369884 - [clangd] Send highlighting diff beyond the end of the file.

2019-08-26 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Mon Aug 26 01:38:45 2019
New Revision: 369884

URL: http://llvm.org/viewvc/llvm-project?rev=369884&view=rev
Log:
[clangd] Send highlighting diff beyond the end of the file.

Summary: This would make the client life (tracking the changes) easier.

Reviewers: jvikstrom

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

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
clang-tools-extra/trunk/clangd/ClangdLSPServer.h
clang-tools-extra/trunk/clangd/ClangdServer.cpp
clang-tools-extra/trunk/clangd/ClangdServer.h
clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp
clang-tools-extra/trunk/clangd/SemanticHighlighting.h
clang-tools-extra/trunk/clangd/test/semantic-highlighting.test
clang-tools-extra/trunk/clangd/unittests/SemanticHighlightingTests.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp?rev=369884&r1=369883&r2=369884&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp Mon Aug 26 01:38:45 2019
@@ -1195,7 +1195,7 @@ bool ClangdLSPServer::shouldRunCompletio
 }
 
 void ClangdLSPServer::onHighlightingsReady(
-PathRef File, std::vector Highlightings, int NumLines) {
+PathRef File, std::vector Highlightings) {
   std::vector Old;
   std::vector HighlightingsCopy = Highlightings;
   {
@@ -1205,8 +1205,7 @@ void ClangdLSPServer::onHighlightingsRea
   }
   // LSP allows us to send incremental edits of highlightings. Also need to 
diff
   // to remove highlightings from tokens that should no longer have them.
-  std::vector Diffed =
-  diffHighlightings(Highlightings, Old, NumLines);
+  std::vector Diffed = diffHighlightings(Highlightings, 
Old);
   publishSemanticHighlighting(
   {{URIForFile::canonicalize(File, /*TUPath=*/File)},
toSemanticHighlightingInformation(Diffed)});

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.h?rev=369884&r1=369883&r2=369884&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.h (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.h Mon Aug 26 01:38:45 2019
@@ -55,9 +55,9 @@ private:
   // Implement DiagnosticsConsumer.
   void onDiagnosticsReady(PathRef File, std::vector Diagnostics) 
override;
   void onFileUpdated(PathRef File, const TUStatus &Status) override;
-  void onHighlightingsReady(PathRef File,
-std::vector Highlightings,
-int NumLines) override;
+  void
+  onHighlightingsReady(PathRef File,
+   std::vector Highlightings) override;
 
   // LSP methods. Notifications have signature void(const Params&).
   // Calls have signature void(const Params&, Callback).

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=369884&r1=369883&r2=369884&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Mon Aug 26 01:38:45 2019
@@ -73,19 +73,10 @@ struct UpdateIndexCallbacks : public Par
 if (SemanticHighlighting)
   Highlightings = getSemanticHighlightings(AST);
 
-// FIXME: We need a better way to send the maximum line number to the
-// differ.
-// The differ needs the information about the max number of lines
-// to not send diffs that are outside the file.
-const SourceManager &SM = AST.getSourceManager();
-FileID MainFileID = SM.getMainFileID();
-int NumLines = SM.getBufferData(MainFileID).count('\n') + 1;
-
 Publish([&]() {
   DiagConsumer.onDiagnosticsReady(Path, std::move(Diagnostics));
   if (SemanticHighlighting)
-DiagConsumer.onHighlightingsReady(Path, std::move(Highlightings),
-  NumLines);
+DiagConsumer.onHighlightingsReady(Path, std::move(Highlightings));
 });
   }
 

Modified: clang-tools-extra/trunk/clangd/ClangdServer.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.h?rev=369884&r1=369883&r2=369884&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.h (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.h Mon Aug 26 01:38:45 2019
@@ -56,8 +56,7 @@ public:
   /// where generated from.
   virtual void
   onHighlightingsReady(PathRef File,
-   std::vector High

[PATCH] D66541: [clangd] Send highlighting diff beyond the end of the file.

2019-08-26 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL369884: [clangd] Send highlighting diff beyond the end of 
the file. (authored by hokein, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D66541?vs=216417&id=217090#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D66541

Files:
  clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
  clang-tools-extra/trunk/clangd/ClangdLSPServer.h
  clang-tools-extra/trunk/clangd/ClangdServer.cpp
  clang-tools-extra/trunk/clangd/ClangdServer.h
  clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp
  clang-tools-extra/trunk/clangd/SemanticHighlighting.h
  clang-tools-extra/trunk/clangd/test/semantic-highlighting.test
  clang-tools-extra/trunk/clangd/unittests/SemanticHighlightingTests.cpp

Index: clang-tools-extra/trunk/clangd/ClangdLSPServer.h
===
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.h
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.h
@@ -55,9 +55,9 @@
   // Implement DiagnosticsConsumer.
   void onDiagnosticsReady(PathRef File, std::vector Diagnostics) override;
   void onFileUpdated(PathRef File, const TUStatus &Status) override;
-  void onHighlightingsReady(PathRef File,
-std::vector Highlightings,
-int NumLines) override;
+  void
+  onHighlightingsReady(PathRef File,
+   std::vector Highlightings) override;
 
   // LSP methods. Notifications have signature void(const Params&).
   // Calls have signature void(const Params&, Callback).
Index: clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp
@@ -339,9 +339,11 @@
 
 std::vector
 diffHighlightings(ArrayRef New,
-  ArrayRef Old, int NewMaxLine) {
-  assert(std::is_sorted(New.begin(), New.end()) && "New must be a sorted vector");
-  assert(std::is_sorted(Old.begin(), Old.end()) && "Old must be a sorted vector");
+  ArrayRef Old) {
+  assert(std::is_sorted(New.begin(), New.end()) &&
+ "New must be a sorted vector");
+  assert(std::is_sorted(Old.begin(), Old.end()) &&
+ "Old must be a sorted vector");
 
   // FIXME: There's an edge case when tokens span multiple lines. If the first
   // token on the line started on a line above the current one and the rest of
@@ -371,9 +373,7 @@
 return std::min(NextNew, NextOld);
   };
 
-  // If the New file has fewer lines than the Old file we don't want to send
-  // highlightings beyond the end of the file.
-  for (int LineNumber = 0; LineNumber < NewMaxLine;
+  for (int LineNumber = 0; NewLine.end() < NewEnd || OldLine.end() < OldEnd;
LineNumber = NextLineNumber()) {
 NewLine = takeLine(New, NewLine.end(), LineNumber);
 OldLine = takeLine(Old, OldLine.end(), LineNumber);
Index: clang-tools-extra/trunk/clangd/SemanticHighlighting.h
===
--- clang-tools-extra/trunk/clangd/SemanticHighlighting.h
+++ clang-tools-extra/trunk/clangd/SemanticHighlighting.h
@@ -71,15 +71,15 @@
 /// Return a line-by-line diff between two highlightings.
 ///  - if the tokens on a line are the same in both hightlightings, this line is
 ///  omitted.
-///  - if a line exists in New but not in Old the tokens on this line are
+///  - if a line exists in New but not in Old, the tokens on this line are
 ///  emitted.
-///  - if a line does not exists in New but exists in Old an empty line is
+///  - if a line does not exist in New but exists in Old, an empty line is
 ///  emitted (to tell client to clear the previous highlightings on this line).
-/// \p NewMaxLine is the maximum line number from the new file.
+///
 /// REQUIRED: Old and New are sorted.
 std::vector
 diffHighlightings(ArrayRef New,
-  ArrayRef Old, int NewMaxLine);
+  ArrayRef Old);
 
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
===
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
@@ -1195,7 +1195,7 @@
 }
 
 void ClangdLSPServer::onHighlightingsReady(
-PathRef File, std::vector Highlightings, int NumLines) {
+PathRef File, std::vector Highlightings) {
   std::vector Old;
   std::vector HighlightingsCopy = Highlightings;
   {
@@ -1205,8 +1205,7 @@
   }
   // LSP allows us to send incremental edits of highlightings. Also need to diff
   // to remove highlightings from tokens that should no longer have them.
-  std::vector Diffed =
-  diffHighlightings(Highl

[PATCH] D66627: [clang-tidy] new check: bugprone-pthread-return

2019-08-26 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr added a comment.

Thanks for the contribution! In abstract, I think it is a good checker, 
however, the implementation largely duplicates 
`clang-tidy/bugprone/PosixReturnCheck.cpp` -- do you think you could factor out 
the common parts? I see at least two ways:

- Factor out a library, use it in both checkers.

- Put everything into one checker, if necessary, add configuration options to 
turn on/off POSIX and PThread parts. However, I don't even think configuration 
options would be necessary -- it is unlikely that someone would want one but 
not the other -- or is there a use case?




Comment at: clang-tools-extra/test/clang-tidy/bugprone-pthread-return.cpp:101
+extern "C" int pthread_timedjoin_np(pthread_t thread, void **retval, const 
struct timespec *abstime);
+extern "C" int pthread_yield(void);
+

It does not seem like most of these functions are used in the test below. Could 
you leave only representative functions for each case in the code?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66627



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


[PATCH] D66219: [clangd] Added a colorizer to the vscode extension.

2019-08-26 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom updated this revision to Diff 217099.
jvikstrom marked 12 inline comments as done.
jvikstrom added a comment.

Made tests more readable.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66219

Files:
  clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts
  clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
  
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts

Index: clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
@@ -1,13 +1,15 @@
 import * as assert from 'assert';
 import * as path from 'path';
+import * as vscode from 'vscode';
 
-import * as SM from '../src/semantic-highlighting';
+import * as semanticHighlighting from '../src/semantic-highlighting';
 
 suite('SemanticHighlighting Tests', () => {
   test('Parses arrays of textmate themes.', async () => {
 const themePath =
 path.join(__dirname, '../../test/assets/includeTheme.jsonc');
-const scopeColorRules = await SM.parseThemeFile(themePath);
+const scopeColorRules =
+await semanticHighlighting.parseThemeFile(themePath);
 const getScopeRule = (scope: string) =>
 scopeColorRules.find((v) => v.scope === scope);
 assert.equal(scopeColorRules.length, 3);
@@ -32,8 +34,9 @@
 {character : 10, scopeIndex : 0, length : 1}
   ]
 ];
-testCases.forEach((testCase, i) => assert.deepEqual(
-  SM.decodeTokens(testCase), expected[i]));
+testCases.forEach(
+(testCase, i) => assert.deepEqual(
+semanticHighlighting.decodeTokens(testCase), expected[i]));
   });
   test('ScopeRules overrides for more specific themes', () => {
 const rules = [
@@ -44,7 +47,7 @@
   {scope : 'storage', foreground : '5'},
   {scope : 'variable.other.parameter', foreground : '6'},
 ];
-const tm = new SM.ThemeRuleMatcher(rules);
+const tm = new semanticHighlighting.ThemeRuleMatcher(rules);
 assert.deepEqual(tm.getBestThemeRule('variable.other.cpp').scope,
  'variable.other');
 assert.deepEqual(tm.getBestThemeRule('storage.static').scope,
@@ -57,4 +60,103 @@
 assert.deepEqual(tm.getBestThemeRule('variable.other.parameter.cpp').scope,
  'variable.other.parameter');
   });
+  test('Colorizer groups decorations correctly', async () => {
+// Helper for creating a vscode Range.
+const createRange = (line: number, startCharacter: number,
+ length: number) =>
+new vscode.Range(new vscode.Position(line, startCharacter),
+ new vscode.Position(line, startCharacter + length));
+const scopeTable = [
+  [ 'variable' ], [ 'entity.type.function' ],
+  [ 'entity.type.function.method' ]
+];
+// Create the scope source ranges the highlightings should be highlighted
+// at. Assumes the scopes used are the ones in the "scopeTable" variable.
+const createHighlightingScopeRanges =
+(highlightingLines:
+ semanticHighlighting.SemanticHighlightingLine[]) => {
+  // Initialize the scope ranges list to the correct size. Otherwise
+  // scopes that don't have any highlightings are missed.
+  let scopeRanges: vscode.Range[][] = scopeTable.map(() => []);
+  highlightingLines.forEach((line) => {
+line.tokens.forEach((token) => {
+  scopeRanges[token.scopeIndex].push(
+  createRange(line.line, token.character, token.length));
+});
+  });
+  return scopeRanges;
+};
+
+const rules = [
+  {scope : 'variable', foreground : '1'},
+  {scope : 'entity.type', foreground : '2'},
+];
+class MockHighlighter extends semanticHighlighting.Highlighter {
+  applicationUriHistory: string[] = [];
+  // Override to make the highlighting calls accessible to the test. Also makes the test not depend on visible text editors.
+  applyHighlights(fileUri: string) {
+this.applicationUriHistory.push(fileUri);
+  }
+  // Override to make it accessible from the test.
+  getDecorationRanges(fileUri: string) {
+return super.getDecorationRanges(fileUri);
+  }
+  // Override to make tests not depend on visible text editors.
+  getVisibleTextEditorUris() { return [ 'a', 'b' ]; }
+}
+const highlighter = new MockHighlighter(scopeTable);
+const tm = new semanticHighlighting.ThemeRuleMatcher(rules);
+// Recolorizes when initialized.
+highlighter.highlight('a', []);
+assert.deepEqual(highlighter.applicationUriHistory, [ 'a' ]);
+highlighter.

[PATCH] D66219: [clangd] Added a colorizer to the vscode extension.

2019-08-26 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom added inline comments.



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts:135
+  // Update the themeRuleMatcher that is used when highlighting. Also triggers 
a
+  // recolorization for all current highlighters. Safe to call multiple times.
+  public initialize(themeRuleMatcher: ThemeRuleMatcher) {

hokein wrote:
> nit: the comment is stale now.  I believe this function is only called 
> whenever we reload a theme or at the first launch of the extension.
It's should only called when a theme is loaded (and we happen to load a theme 
when we initialize, but it's async).
Don't see why the comment is stale though, it seems to describe what it does to 
me.



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts:139
+  const options: vscode.DecorationRenderOptions = {
+color : themeRuleMatcher.getBestThemeRule(scopes[0]).foreground,
+// If the rangeBehavior is set to Open in any direction the

hokein wrote:
> just want to confirm: if we fail to find a matched theme rule, we return an 
> empty decoration. I think vscode just doesn't do anything on an empty color?
vscode indeed does not do anything on empty colors.



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts:94
+let line = [
+  {character : 1, length : 2, scopeIndex : 1},
+  {character : 5, length : 2, scopeIndex : 1},

hokein wrote:
> I believe the test code is correct, but the code here/below is complex and 
> hard to follow. I think we need make the code more readable/understandable.
> 
> some suggestions:
> 
> - the line number is implicitly indicated by the index of the array, I think 
> we can add one more field `line` to the structure (call HighlightingTokens).
> - and creates some helper functions (with proper names) that take the 
> `HighlightingTokens` as parameter and generate the data you need e.g. 
> `SemanticHighlightingLine[]`, `vscode.Range`.
> 
Started exporting the `SemanticHighlightingLine` interface and use that format 
in the tests to not create more interfaces (also means we don't need a helper 
for creating the SemanticHighlightingLine).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66219



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


[PATCH] D66731: [Driver] Add an option for createInvocationFromCommandLine to recover on errors

2019-08-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added a reviewer: gribozavr.
Herald added subscribers: kadircet, arphaman, jkorous.
Herald added a project: clang.

Previously, it would always return nullptr on any error.
This change adds a parameter, controlling whether the function should
attempt to return a non-null result even if unknown arguments (or other
errors were encountered).

The new behavior is only used in clangd.

Considered an alternative of changing the return value instead of adding
a new parameter, but that would require updating all callsites. Settled
with the parameter to minimize the code changes.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66731

Files:
  clang-tools-extra/clangd/Compiler.cpp
  clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
  clang/include/clang/Frontend/Utils.h
  clang/lib/Frontend/CreateInvocationFromCommandLine.cpp

Index: clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
===
--- clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
+++ clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
@@ -24,14 +24,9 @@
 using namespace clang;
 using namespace llvm::opt;
 
-/// createInvocationFromCommandLine - Construct a compiler invocation object for
-/// a command line argument vector.
-///
-/// \return A CompilerInvocation, or 0 if none was built for the given
-/// argument vector.
 std::unique_ptr clang::createInvocationFromCommandLine(
 ArrayRef ArgList, IntrusiveRefCntPtr Diags,
-IntrusiveRefCntPtr VFS) {
+IntrusiveRefCntPtr VFS, bool ShouldRecoverOnErorrs) {
   if (!Diags.get()) {
 // No diagnostics engine was provided, so create our own diagnostics object
 // with the default options.
@@ -95,11 +90,10 @@
 
   const ArgStringList &CCArgs = Cmd.getArguments();
   auto CI = std::make_unique();
-  if (!CompilerInvocation::CreateFromArgs(*CI,
- const_cast(CCArgs.data()),
- const_cast(CCArgs.data()) +
- CCArgs.size(),
- *Diags))
+  if (!CompilerInvocation::CreateFromArgs(
+  *CI, const_cast(CCArgs.data()),
+  const_cast(CCArgs.data()) + CCArgs.size(), *Diags) &&
+  !ShouldRecoverOnErorrs)
 return nullptr;
   return CI;
 }
Index: clang/include/clang/Frontend/Utils.h
===
--- clang/include/clang/Frontend/Utils.h
+++ clang/include/clang/Frontend/Utils.h
@@ -213,13 +213,18 @@
 /// createInvocationFromCommandLine - Construct a compiler invocation object for
 /// a command line argument vector.
 ///
+/// \param ShouldRecoverOnErrors - whether we should attempt to return a
+/// non-null (and possibly incorrect) CompilerInvocation if any errors were
+/// encountered. When this flag is false, always return null on errors.
+///
 /// \return A CompilerInvocation, or 0 if none was built for the given
 /// argument vector.
 std::unique_ptr createInvocationFromCommandLine(
 ArrayRef Args,
 IntrusiveRefCntPtr Diags =
 IntrusiveRefCntPtr(),
-IntrusiveRefCntPtr VFS = nullptr);
+IntrusiveRefCntPtr VFS = nullptr,
+bool ShouldRecoverOnErrors = false);
 
 /// Return the value of the last argument as an integer, or a default. If Diags
 /// is non-null, emits an error if the argument is given, but non-integral.
Index: clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
===
--- clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
+++ clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
@@ -9,7 +9,9 @@
 #include "AST.h"
 #include "Annotations.h"
 #include "ClangdUnit.h"
+#include "Compiler.h"
 #include "SourceCode.h"
+#include "TestFS.h"
 #include "TestTU.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/Basic/TokenKinds.h"
@@ -244,6 +246,20 @@
   EXPECT_EQ(T.expandedTokens().drop_back().back().text(SM), "}");
 }
 
+TEST(ClangdUnitTest, CanBuildInvocationWithUnknownArgs) {
+  // Unknown flags should not prevent a build of compiler invocation.
+  ParseInputs Inputs;
+  Inputs.FS = buildTestFS({{testPath("foo.cpp"), "void test() {}"}});
+  Inputs.CompileCommand.CommandLine = {"clang", "-fsome-unknown-flag",
+   testPath("foo.cpp")};
+  EXPECT_NE(buildCompilerInvocation(Inputs), nullptr);
+
+  // Unknown forwarded to -cc1 should not a failure either.
+  Inputs.CompileCommand.CommandLine = {
+  "clang", "-Xclang", "-fsome-unknown-flag", testPath("foo.cpp")};
+  EXPECT_NE(buildCompilerInvocation(Inputs), nullptr);
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/Compiler.cpp
===
--- clang-tools-extra/clangd/Compiler.cpp
+++ clang-tools-extra/clangd/Compiler.cpp
@@ -59,7 +59,8 @@
   CompilerInsta

[PATCH] D66731: [Driver] Add an option for createInvocationFromCommandLine to recover on errors

2019-08-26 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr added a comment.

It does seem reasonable for Clangd to recover when it sees unknown command line 
flags (after all, in compiler_commands.json we can see command line flags from 
past and future versions of Clang, GCC and other compilers -- whatever the 
build system decided to write there). However I have two requests:

- In the doc comment for `CompilerInvocation::CreateFromArgs`, could you add a 
note that it does a best effort to provide a CompilerInvocation even if it 
returns false? Right now the doc comment reads like there are no guarantees at 
all if it returns false.

- (can be a separate patch) Could we produce a diagnostic in the affected TU 
notifying the user that the compiler commands could not be parsed and we did 
our best to recover, but it may be completely wrong?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66731



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


[PATCH] D66538: [AST] AST structural equivalence to work internally with pairs.

2019-08-26 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 217105.
balazske added a comment.

- Small update to newer C++ syntax, use std::pair in test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66538

Files:
  clang/include/clang/AST/ASTStructuralEquivalence.h
  clang/lib/AST/ASTStructuralEquivalence.cpp
  clang/unittests/AST/StructuralEquivalenceTest.cpp

Index: clang/unittests/AST/StructuralEquivalenceTest.cpp
===
--- clang/unittests/AST/StructuralEquivalenceTest.cpp
+++ clang/unittests/AST/StructuralEquivalenceTest.cpp
@@ -1273,6 +1273,128 @@
   classTemplateSpecializationDecl(hasName("Primary")));
   EXPECT_FALSE(testStructuralMatch(t));
 }
+struct StructuralEquivalenceCacheTest : public StructuralEquivalenceTest {
+  llvm::DenseSet> NonEquivalentDecls;
+
+  template 
+  std::pair
+  findDeclPair(std::tuple TU,
+   MatcherType M) {
+NodeType *D0 = FirstDeclMatcher().match(get<0>(TU), M);
+NodeType *D1 = FirstDeclMatcher().match(get<1>(TU), M);
+return {D0, D1};
+  }
+
+  template 
+  bool isInNonEqCache(std::pair D) {
+return NonEquivalentDecls.count(D) > 0;
+  }
+};
+
+TEST_F(StructuralEquivalenceCacheTest, SimpleNonEq) {
+  auto TU = makeTuDecls(
+  R"(
+  class A {};
+  class B {};
+  void x(A, A);
+  )",
+  R"(
+  class A {};
+  class B {};
+  void x(A, B);
+  )",
+  Lang_CXX);
+
+  StructuralEquivalenceContext Ctx(
+  get<0>(TU)->getASTContext(), get<1>(TU)->getASTContext(),
+  NonEquivalentDecls, StructuralEquivalenceKind::Default, false, false);
+
+  auto X = findDeclPair(TU, functionDecl(hasName("x")));
+  EXPECT_FALSE(Ctx.IsEquivalent(X.first, X.second));
+
+  EXPECT_FALSE(isInNonEqCache(findDeclPair(
+  TU, cxxRecordDecl(hasName("A"), unless(isImplicit());
+  EXPECT_FALSE(isInNonEqCache(findDeclPair(
+  TU, cxxRecordDecl(hasName("B"), unless(isImplicit());
+}
+
+TEST_F(StructuralEquivalenceCacheTest, SpecialNonEq) {
+  auto TU = makeTuDecls(
+  R"(
+  class A {};
+  class B { int i; };
+  void x(A *);
+  void y(A *);
+  class C {
+friend void x(A *);
+friend void y(A *);
+  };
+  )",
+  R"(
+  class A {};
+  class B { int i; };
+  void x(A *);
+  void y(B *);
+  class C {
+friend void x(A *);
+friend void y(B *);
+  };
+  )",
+  Lang_CXX);
+
+  StructuralEquivalenceContext Ctx(
+  get<0>(TU)->getASTContext(), get<1>(TU)->getASTContext(),
+  NonEquivalentDecls, StructuralEquivalenceKind::Default, false, false);
+
+  auto C = findDeclPair(
+  TU, cxxRecordDecl(hasName("C"), unless(isImplicit(;
+  EXPECT_FALSE(Ctx.IsEquivalent(C.first, C.second));
+
+  EXPECT_FALSE(isInNonEqCache(C));
+  EXPECT_FALSE(isInNonEqCache(findDeclPair(
+  TU, cxxRecordDecl(hasName("A"), unless(isImplicit());
+  EXPECT_FALSE(isInNonEqCache(findDeclPair(
+  TU, cxxRecordDecl(hasName("B"), unless(isImplicit());
+  EXPECT_FALSE(isInNonEqCache(
+  findDeclPair(TU, functionDecl(hasName("x");
+  EXPECT_FALSE(isInNonEqCache(
+  findDeclPair(TU, functionDecl(hasName("y");
+}
+
+TEST_F(StructuralEquivalenceCacheTest, Cycle) {
+  auto TU = makeTuDecls(
+  R"(
+  class C;
+  class A { C *c; };
+  void x(A *);
+  class C {
+friend void x(A *);
+  };
+  )",
+  R"(
+  class C;
+  class A { C *c; };
+  void x(A *);
+  class C {
+friend void x(A *);
+  };
+  )",
+  Lang_CXX);
+
+  StructuralEquivalenceContext Ctx(
+  get<0>(TU)->getASTContext(), get<1>(TU)->getASTContext(),
+  NonEquivalentDecls, StructuralEquivalenceKind::Default, false, false);
+
+  auto C = findDeclPair(
+  TU, cxxRecordDecl(hasName("C"), unless(isImplicit(;
+  EXPECT_TRUE(Ctx.IsEquivalent(C.first, C.second));
+
+  EXPECT_FALSE(isInNonEqCache(C));
+  EXPECT_FALSE(isInNonEqCache(findDeclPair(
+  TU, cxxRecordDecl(hasName("A"), unless(isImplicit());
+  EXPECT_FALSE(isInNonEqCache(
+  findDeclPair(TU, functionDecl(hasName("x");
+}
 
 } // end namespace ast_matchers
 } // end namespace clang
Index: clang/lib/AST/ASTStructuralEquivalence.cpp
===
--- clang/lib/AST/ASTStructuralEquivalence.cpp
+++ clang/lib/AST/ASTStructuralEquivalence.cpp
@@ -1574,20 +1574,24 @@
  Decl *D1, Decl *D2) {
   // FIXME: Check for known structural equivalences via a callback of some sort.
 
+  D1 = D1->getCanonicalDecl();
+  D2 = D2->getCanonicalDecl();
+  std::pair P{D1, D2};
+
   // Check whether we already know that these two declarations are not
   // structurally equivalent.
-  if (Context.NonEquivalentDecls.count(
-  std::make_pair(D1->getCanonicalDecl(), D2->getCanonicalDecl(
+  if (Context.NonE

[PATCH] D65526: [Clangd] First version of ExtractFunction

2019-08-26 Thread Shaurya Gupta via Phabricator via cfe-commits
SureYeaah updated this revision to Diff 217108.
SureYeaah added a comment.

Fixed typo


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65526

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

Index: clang-tools-extra/clangd/unittests/TweakTests.cpp
===
--- clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -599,6 +599,106 @@
 R"cpp(const char * x = "test")cpp");
 }
 
+TWEAK_TEST(ExtractFunction);
+TEST_F(ExtractFunctionTest, FunctionTest) {
+  Header = R"cpp(
+#define F(BODY) void FFF() { BODY }
+  )cpp";
+  Context = Function;
+
+  // Root statements should have common parent.
+  EXPECT_EQ(apply("for(;;) [[1+2; 1+2;]]"), "unavailable");
+  // Expressions aren't extracted.
+  EXPECT_EQ(apply("int x = 0; [[x++;]]"), "unavailable");
+  // We don't support extraction from lambdas.
+  EXPECT_EQ(apply("auto lam = [](){ [[int x;]] }; "), "unavailable");
+  // FIXME: Add tests for macros after selectionTree works properly for macros.
+  // FIXME: This should be extractable
+  EXPECT_EQ(apply("F ([[int x = 0;]])"), "unavailable");
+
+  // Ensure that end of Zone and Beginning of PostZone being adjacent doesn't
+  // lead to break being included in the extraction zone.
+  EXPECT_THAT(apply("for(;;) { [[{}]]break; }"), HasSubstr("extracted"));
+  // FIXME: This should be unavailable since partially selected but
+  // selectionTree doesn't always work correctly for VarDecls.
+  EXPECT_THAT(apply("int [[x = 0]];"), HasSubstr("extracted"));
+  // FIXME: ExtractFunction should be unavailable inside loop construct
+  // initalizer/condition.
+  EXPECT_THAT(apply(" for([[int i = 0;]];);"), HasSubstr("extracted"));
+  // Don't extract because needs hoisting.
+  EXPECT_THAT(apply(" [[int a = 5;]] a++; "), StartsWith("fail"));
+  // Don't extract return
+  EXPECT_THAT(apply(" if(true) [[return;]] "), StartsWith("fail"));
+  // Don't extract break and continue.
+  // FIXME: We should be able to extract this since it's non broken.
+  EXPECT_THAT(apply(" [[for(;;) break;]] "), StartsWith("fail"));
+  EXPECT_THAT(apply(" for(;;) [[continue;]] "), StartsWith("fail"));
+}
+
+TEST_F(ExtractFunctionTest, FileTest) {
+  // Check all parameters are in order
+  std::string ParameterCheckInput = R"cpp(
+struct FOO {
+  int x;
+};
+void f(int a) {
+  int b; int *ptr = &a; FOO foo;
+  [[a += foo.x + b;
+  *ptr++;]]
+})cpp";
+  std::string ParameterCheckOutput = R"cpp(
+struct FOO {
+  int x;
+};
+void extracted(int &a, int &b, int * &ptr, struct FOO &foo) {
+a += foo.x + b;
+  *ptr++;
+}
+void f(int a) {
+  int b; int *ptr = &a; FOO foo;
+  extracted(a, b, ptr, foo);
+})cpp";
+  EXPECT_EQ(apply(ParameterCheckInput), ParameterCheckOutput);
+
+  // Check const qualifier
+  std::string ConstCheckInput = R"cpp(
+void f(const int c) {
+  [[while(c) {}]]
+})cpp";
+  std::string ConstCheckOutput = R"cpp(
+void extracted(const int &c) {
+while(c) {}
+}
+void f(const int c) {
+  extracted(c);
+})cpp";
+  EXPECT_EQ(apply(ConstCheckInput), ConstCheckOutput);
+
+  // Don't extract when we need to make a function as a parameter.
+  EXPECT_THAT(apply("void f() { [[int a; f();]] }"), StartsWith("fail"));
+
+  // We don't extract from methods for now since they may involve multi-file
+  // edits
+  std::string MethodFailInput = R"cpp(
+class T {
+  void f() {
+[[int x;]]
+  }
+};
+  )cpp";
+  EXPECT_EQ(apply(MethodFailInput), "unavailable");
+
+  // We don't extract from templated functions for now as templates are hard
+  // to deal with.
+  std::string TemplateFailInput = R"cpp(
+template
+void f() {
+  [[int x;]]
+}
+  )cpp";
+  EXPECT_EQ(apply(TemplateFailInput), "unavailable");
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
@@ -0,0 +1,591 @@
+//===--- ExtractFunction.cpp -*- C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// Extracts statements to a new function and replaces the statements with a
+// call to the new function.
+// Before:
+//   void f(int a) {
+// [[if(a < 5)
+//   a = 5;]]
+//   }
+// After:
+//   void extracted(int &a) {
+// if(a < 5)
+//   a = 5;
+//   }
+//   void f(int a) {
+// extracted(a);
+//   }
+/

[PATCH] D66219: [clangd] Added a colorizer to the vscode extension.

2019-08-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

thanks, looks great, looking forward to use it, just a few more nits.

Please update the patch description before committing.




Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts:135
+  // Update the themeRuleMatcher that is used when highlighting. Also triggers 
a
+  // recolorization for all current highlighters. Safe to call multiple times.
+  public initialize(themeRuleMatcher: ThemeRuleMatcher) {

jvikstrom wrote:
> hokein wrote:
> > nit: the comment is stale now.  I believe this function is only called 
> > whenever we reload a theme or at the first launch of the extension.
> It's should only called when a theme is loaded (and we happen to load a theme 
> when we initialize, but it's async).
> Don't see why the comment is stale though, it seems to describe what it does 
> to me.
IIRC, the comment here was move from `setThemeRuleMatcher`, but now it's named 
`initialize`, I'd expect the comment is more specific about *initialization* of 
the class -- when this method should be called, and what it does (in a high 
level).



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts:139
+  const options: vscode.DecorationRenderOptions = {
+color : themeRuleMatcher.getBestThemeRule(scopes[0]).foreground,
+// If the rangeBehavior is set to Open in any direction the

jvikstrom wrote:
> hokein wrote:
> > just want to confirm: if we fail to find a matched theme rule, we return an 
> > empty decoration. I think vscode just doesn't do anything on an empty color?
> vscode indeed does not do anything on empty colors.
could you add a comment for this?



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts:58
   // The rules for the current theme.
   themeRuleMatcher: ThemeRuleMatcher;
+  // The object that applies the highlightings clangd sends.

nit: I think we can remove this field since it is not used in this class.



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts:170
+
+  // Exists to make the initialize method testable.
+  protected getVisibleTextEditorUris() {

I think we should comment this method as normal methods. 



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts:171
+  // Exists to make the initialize method testable.
+  protected getVisibleTextEditorUris() {
+return vscode.window.visibleTextEditors.map((e) =>

nit: spell the return type.



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts:84
+  scopeRanges[token.scopeIndex].push(
+  createRange(line.line, token.character, token.length));
+});

nit: I'd inline the `createRange` here, since we only use it once.



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts:105
+  // Override to make tests not depend on visible text editors.
+  getVisibleTextEditorUris() { return [ 'a', 'b' ]; }
+}

nit: use some readable name, e.g. `file1`, `file2`?



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts:108
+const highlighter = new MockHighlighter(scopeTable);
+const tm = new semanticHighlighting.ThemeRuleMatcher(rules);
+// Recolorizes when initialized.

nit: inline the `rules` here.



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts:139
+const smallHighlightingsInLine:
+semanticHighlighting.SemanticHighlightingLine[] = [
+  {

the array contains a single element, I'd use ` 
semanticHighlighting.SemanticHighlightingLine` and name it 
`HighlightingsInLine1`



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts:160
+createHighlightingScopeRanges(
+[...highlightingsInLine.slice(1), ...smallHighlightingsInLine ]));
+  });

maybe just `[HighlightingsInLine1, ...highlightingsInLine.slice(1)]`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66219



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


[PATCH] D66516: [clangd] Added highlighting to types dependant on templates.

2019-08-26 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom marked an inline comment as done.
jvikstrom added inline comments.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:177
   return;
+if (TP->isPointerType() || TP->isLValueReferenceType())
+  // When highlighting dependant template types the type can be a pointer 
or

ilya-biryukov wrote:
> jvikstrom wrote:
> > ilya-biryukov wrote:
> > > jvikstrom wrote:
> > > > ilya-biryukov wrote:
> > > > > `RecursiveASTVisitor` also traverses the pointer and reference types, 
> > > > > why does it not reach the inner `TemplateTypeParmType` in the cases 
> > > > > you describe?
> > > > The D in `using D = ...` `typedef ... D` does not have a TypeLoc (at 
> > > > least not one that is visited). Therefore we use the 
> > > > VisitTypedefNameDecl (line 121) to get the location of `D` to be able 
> > > > to highlight it. And we just send the typeLocs typeptr to addType 
> > > > (which is a Pointer for `using D = T*;`)...
> > > > 
> > > > But maybe we should get the underlying type before we call addType with 
> > > > TypePtr? Just a while loop on line 123 basically (can we have multiple 
> > > > PointerTypes nested in each other actually?)
> > > > 
> > > > Even if we keep it in addType the comment is actually wrong, because it 
> > > > obviously works when for the actual "type occurrences" for `D` (so will 
> > > > fix that no matter what). This recursion will just make us add more 
> > > > duplicate tokens...
> > > Could we investigate why `RecursiveASTVisitor` does not visit the 
> > > `TypeLoc` of a corresponding decl?
> > > Here's the code from `RecursiveASTVisitor.h` that should do the trick:
> > > ```
> > > DEF_TRAVERSE_DECL(TypeAliasDecl, {
> > >   TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
> > >   // We shouldn't traverse D->getTypeForDecl(); it's a result of
> > >   // declaring the type alias, not something that was written in the
> > >   // source.
> > > })
> > > ```
> > > 
> > > If it doesn't, we are probably holding it wrong.
> > There just doesn't seem to be a TypeLoc for the typedef'ed Decl.  We can 
> > get the `T*` TypeLoc (with `D->getTypeSourceInfo()->getTypeLoc()`). But 
> > there isn't one for `D`. Even the `D->getTypeForDecl` returns null.
> > 
> > And I have no idea where I'd even start debugging that. Or if it's even a 
> > bug
> > 
> I may have misinterpreted the patch. Are we trying to add highlightings for 
> the names of using aliases here? E.g. for the following range:
> ```
> template 
> struct Foo {
>   using [[D]] = T**;
> };
> ```
> 
> Why isn't this handled in `VisitNamedDecl`?
> We don't seem to call this function for `TypedefNameDecl` at all and it 
> actually weird. Is this because we attempt to highlight typedefs as their 
> underlying types?
So currently using aliases and typedefs are highlighted the same as the 
underlying type (in most cases). One case where they aren't is when the 
underlying type is a template parameter (which is what this patch is trying to 
solve).


> Why isn't this handled in VisitNamedDecl?

The Decl is actually visited in `VisitNamedDecl`, however as it is a 
`TypeAliasDecl` which we do not have a check for in the addToken function it 
will not get highlighted in that visit.

Actually, could add a check for `TypeAliasDecl` in `addToken` (should probably 
be a check for `TypedefNameDecl` to cover both `using ...` and `typedef ...`) 
and move the code from the `VisitTypedefNameDecl` to the `addToken` function 
inside that check instead.



> We don't seem to call this function for TypedefNameDecl at all and it 
> actually weird. Is this because we attempt to highlight typedefs as their 
> underlying types?


Don't understand what you mean. What function? 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66516



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


[PATCH] D66732: [Clangd] ExtractFunction Added checks for broken control flow

2019-08-26 Thread Shaurya Gupta via Phabricator via cfe-commits
SureYeaah created this revision.
SureYeaah added reviewers: sammccall, kadircet.
Herald added subscribers: cfe-commits, arphaman, jkorous, MaskRay, 
ilya-biryukov.
Herald added a project: clang.

- Added a SelectionTreeVisitor to check for broken control flow
- Added unittests


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66732

Files:
  clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
  clang-tools-extra/clangd/unittests/TweakTests.cpp

Index: clang-tools-extra/clangd/unittests/TweakTests.cpp
===
--- clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -625,14 +625,22 @@
   // FIXME: ExtractFunction should be unavailable inside loop construct
   // initalizer/condition.
   EXPECT_THAT(apply(" for([[int i = 0;]];);"), HasSubstr("extracted"));
+  // We should be able to extract break/continue with a parent loop/switch.
+  EXPECT_THAT(apply(" [[for(;;) if(1) break;]] "), HasSubstr("extracted"));
+  EXPECT_THAT(apply(" for(;;) [[while(1) break;]] "), HasSubstr("extracted"));
+  EXPECT_THAT(apply(" [[switch(1) { break; }]]"), HasSubstr("extracted"));
+  EXPECT_THAT(apply(" [[while(1) switch(1) { continue; }]]"),
+  HasSubstr("extracted"));
   // Don't extract because needs hoisting.
   EXPECT_THAT(apply(" [[int a = 5;]] a++; "), StartsWith("fail"));
   // Don't extract return
   EXPECT_THAT(apply(" if(true) [[return;]] "), StartsWith("fail"));
-  // Don't extract break and continue.
-  // FIXME: We should be able to extract this since it's non broken.
-  EXPECT_THAT(apply(" [[for(;;) break;]] "), StartsWith("fail"));
-  EXPECT_THAT(apply(" for(;;) [[continue;]] "), StartsWith("fail"));
+  // Don't extract break and continue without a loop/switch parent.
+  EXPECT_THAT(apply(" for(;;) [[if(1) continue;]] "), StartsWith("fail"));
+  EXPECT_THAT(apply(" while(1) [[if(1) break;]] "), StartsWith("fail"));
+  EXPECT_THAT(apply(" switch(1) { [[break;]] }"), StartsWith("fail"));
+  EXPECT_THAT(apply(" for(;;) { [[while(1) break; break;]] }"),
+  StartsWith("fail"));
 }
 
 TEST_F(ExtractFunctionTest, FileTest) {
Index: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
@@ -28,7 +28,6 @@
 //   - Always passed by l-value reference
 // - No return
 // - Cannot move declarations before extracting
-// - Doesn't check for broken control flow
 //
 // 1. ExtractFunction is the tweak subclass
 //- Prepare does basic analysis of the selection and is therefore fast.
@@ -39,8 +38,9 @@
 //enclosing function.
 // 3. NewFunction stores properties of the extracted function and provides
 //methods for rendering it.
-// 4. CapturedZoneInfo uses a RAV to capture information about the extraction
-//like declarations, existing return statements, broken control flow, etc.
+// 4. CapturedZoneInfo uses a RAV and SelectionTreeVisitor to capture
+//information about the extraction like declarations, existing return
+//statements, broken control flow, etc.
 // 5. getExtractedFunction is responsible for analyzing the CapturedZoneInfo and
 //creating a NewFunction.
 // Design Doc at 
@@ -55,6 +55,7 @@
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Stmt.h"
+#include "clang/AST/StmtCXX.h"
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
@@ -360,8 +361,8 @@
   llvm::DenseMap DeclInfoMap;
   // True if there is a return statement in zone.
   bool HasReturnStmt = false;
-  // For now we just care whether there exists a break/continue in zone.
-  bool HasBreakOrContinue = false;
+  // True if extracting break or continue without corresponding loop/switch.
+  bool BrokenControlFlow = false;
   // FIXME: capture TypeAliasDecl and UsingDirectiveDecl
   // FIXME: Capture type information as well.
   // Return reference for a Decl, adding it if not already present.
@@ -403,7 +404,8 @@
   class ExtractionZoneVisitor
   : public clang::RecursiveASTVisitor {
   public:
-ExtractionZoneVisitor(const ExtractionZone &ExtZone) : ExtZone(ExtZone) {
+ExtractionZoneVisitor(CapturedZoneInfo &Info, const ExtractionZone &ExtZone)
+: Info(Info), ExtZone(ExtZone) {
   TraverseDecl(const_cast(
   ExtZone.EnclosingFunction->ASTNode.get()));
 }
@@ -424,12 +426,61 @@
 Info.HasReturnStmt = true;
   return true;
 }
-
-CapturedZoneInfo Info;
+CapturedZoneInfo &Info;
 const ExtractionZone &ExtZone;
   };
-  ExtractionZoneVisitor Visitor(ExtZone);
-  return std::move(Visitor.Info);
+
+  class SelectionTreeVisitor {
+// Returns tuple denoting whether we can Break/Continue out of a node.
+   

[PATCH] D14484: Formatting constructor initializer lists by putting them always on different lines

2019-08-26 Thread Robert F-C via Phabricator via cfe-commits
rfairliecuninghame added a comment.

I also think this feature bears further consideration.

I understand that google and other coding standard currently allows this, but I 
feel there's a certain degree of inconsistency in their doing so. 
None of the open main coding standards would recommend or allow putting 
multiple variable initializations/assignments per line but this is effectively 
what is occurring in allowing this. 
After all,

  MyClass::MyClass(long _state1Long, short _state2Short, int *_state3Ptr)
: state1Long(_state1Long), state2Short(_state2Short), 
state3Ptr(*_state3Ptr) {
  }

is conceptually much the same as

  MyClass::MyClass(long _state1Long, short _state2Short, int *_state3Ptr) {
state1Long = _state1Long; state2Short = _state2Short; state3Ptr = 
*_state3Ptr;
  }

which you would of course never allow.
I'm sure this conceptual inconsistency is apparent to a fair number of other 
C++ style guide writers where a one-per-line limitation on constructor 
initializers is mandated. [I'm in a similar position to JVApen and have had to 
patch the program to order to meet this requirement at my workplace.] Anyway, 
just an observation on the matter.


Repository:
  rL LLVM

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

https://reviews.llvm.org/D14484



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


[clang-tools-extra] r369893 - [clangd] Added a colorizer to the vscode extension.

2019-08-26 Thread Johan Vikstrom via cfe-commits
Author: jvikstrom
Date: Mon Aug 26 04:36:11 2019
New Revision: 369893

URL: http://llvm.org/viewvc/llvm-project?rev=369893&view=rev
Log:
[clangd] Added a colorizer to the vscode extension.

Summary:
Adds the main colorizer component. It colorizes every time clangd sends a 
publishSemanticHighlighting notification.
Every time it colorizes it does a full recolorization (removes all decorations 
from the editor and applies new ones). The reason for this is that all ranges 
for the same scope share a TextEditorDecorationType. This is due to 
TextEditorDecorationTypes being very expensive to create. The prototype used 
one DecorationType per range but that ran into very big performance problems 
(it took >100 ms to apply 600 lines of highlightings which froze the editor).

This version does not share the problem of being extremly slow, but there is 
probably potential to optimize it even more.

No document/texteditor lifecycle management code in this CL, that will come in 
the next one.

Reviewers: hokein, ilya-biryukov

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

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts

clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts

clang-tools-extra/trunk/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts

Modified: clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts?rev=369893&r1=369892&r2=369893&view=diff
==
--- clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts 
(original)
+++ clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts Mon 
Aug 26 04:36:11 2019
@@ -1,5 +1,6 @@
 import * as vscode from 'vscode';
 import * as vscodelc from 'vscode-languageclient';
+import * as semanticHighlighting from './semantic-highlighting';
 
 /**
  * Method to get workspace configuration option
@@ -108,6 +109,17 @@ export function activate(context: vscode
 
   const clangdClient = new ClangdLanguageClient('Clang Language Server',
 serverOptions, clientOptions);
+  const semanticHighlightingFeature =
+  new semanticHighlighting.SemanticHighlightingFeature();
+  clangdClient.registerFeature(semanticHighlightingFeature);
+  // The notification handler must be registered after the client is ready or
+  // the client will crash.
+  clangdClient.onReady().then(
+  () => clangdClient.onNotification(
+  semanticHighlighting.NotificationType,
+  semanticHighlightingFeature.handleNotification.bind(
+  semanticHighlightingFeature)));
+
   console.log('Clang Language Server is now active!');
   context.subscriptions.push(clangdClient.start());
   context.subscriptions.push(vscode.commands.registerCommand(

Modified: 
clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts?rev=369893&r1=369892&r2=369893&view=diff
==
--- 
clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
 (original)
+++ 
clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
 Mon Aug 26 04:36:11 2019
@@ -34,6 +34,13 @@ interface SemanticHighlightingToken {
   // The TextMate scope index to the clangd scope lookup table.
   scopeIndex: number;
 }
+// A line of decoded highlightings from the data clangd sent.
+export interface SemanticHighlightingLine {
+  // The zero-based line position in the text document.
+  line: number;
+  // All SemanticHighlightingTokens on the line.
+  tokens: SemanticHighlightingToken[];
+}
 
 // Language server push notification providing the semantic highlighting
 // information for a text document.
@@ -47,8 +54,8 @@ export class SemanticHighlightingFeature
   // The TextMate scope lookup table. A token with scope index i has the scopes
   // on index i in the lookup table.
   scopeLookupTable: string[][];
-  // The rules for the current theme.
-  themeRuleMatcher: ThemeRuleMatcher;
+  // The object that applies the highlightings clangd sends.
+  highlighter: Highlighter;
   fillClientCapabilities(capabilities: vscodelc.ClientCapabilities) {
 // Extend the ClientCapabilities type and add semantic highlighting
 // capability to the object.
@@ -61,9 +68,10 @@ export class SemanticHighlightingFeature
   }
 
   async loadCurrentTheme() {
-this.themeRuleMatcher = new ThemeRuleMatcher(
+const themeRuleMatcher = new ThemeRuleMatcher(
 await loadTheme(vscode.workspace.getConfiguration('workbench')
 .

[PATCH] D66219: [clangd] Added a colorizer to the vscode extension.

2019-08-26 Thread Johan Vikström via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
jvikstrom marked 10 inline comments as done.
Closed by commit rL369893: [clangd] Added a colorizer to the vscode extension. 
(authored by jvikstrom, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D66219?vs=217099&id=217115#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D66219

Files:
  clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts
  
clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
  
clang-tools-extra/trunk/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts

Index: clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts
===
--- clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts
+++ clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts
@@ -1,5 +1,6 @@
 import * as vscode from 'vscode';
 import * as vscodelc from 'vscode-languageclient';
+import * as semanticHighlighting from './semantic-highlighting';
 
 /**
  * Method to get workspace configuration option
@@ -108,6 +109,17 @@
 
   const clangdClient = new ClangdLanguageClient('Clang Language Server',
 serverOptions, clientOptions);
+  const semanticHighlightingFeature =
+  new semanticHighlighting.SemanticHighlightingFeature();
+  clangdClient.registerFeature(semanticHighlightingFeature);
+  // The notification handler must be registered after the client is ready or
+  // the client will crash.
+  clangdClient.onReady().then(
+  () => clangdClient.onNotification(
+  semanticHighlighting.NotificationType,
+  semanticHighlightingFeature.handleNotification.bind(
+  semanticHighlightingFeature)));
+
   console.log('Clang Language Server is now active!');
   context.subscriptions.push(clangdClient.start());
   context.subscriptions.push(vscode.commands.registerCommand(
Index: clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
===
--- clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
+++ clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
@@ -34,6 +34,13 @@
   // The TextMate scope index to the clangd scope lookup table.
   scopeIndex: number;
 }
+// A line of decoded highlightings from the data clangd sent.
+export interface SemanticHighlightingLine {
+  // The zero-based line position in the text document.
+  line: number;
+  // All SemanticHighlightingTokens on the line.
+  tokens: SemanticHighlightingToken[];
+}
 
 // Language server push notification providing the semantic highlighting
 // information for a text document.
@@ -47,8 +54,8 @@
   // The TextMate scope lookup table. A token with scope index i has the scopes
   // on index i in the lookup table.
   scopeLookupTable: string[][];
-  // The rules for the current theme.
-  themeRuleMatcher: ThemeRuleMatcher;
+  // The object that applies the highlightings clangd sends.
+  highlighter: Highlighter;
   fillClientCapabilities(capabilities: vscodelc.ClientCapabilities) {
 // Extend the ClientCapabilities type and add semantic highlighting
 // capability to the object.
@@ -61,9 +68,10 @@
   }
 
   async loadCurrentTheme() {
-this.themeRuleMatcher = new ThemeRuleMatcher(
+const themeRuleMatcher = new ThemeRuleMatcher(
 await loadTheme(vscode.workspace.getConfiguration('workbench')
 .get('colorTheme')));
+this.highlighter.initialize(themeRuleMatcher);
   }
 
   initialize(capabilities: vscodelc.ServerCapabilities,
@@ -76,10 +84,18 @@
 if (!serverCapabilities.semanticHighlighting)
   return;
 this.scopeLookupTable = serverCapabilities.semanticHighlighting.scopes;
+// Important that highlighter is created before the theme is loading as
+// otherwise it could try to update the themeRuleMatcher without the
+// highlighter being created.
+this.highlighter = new Highlighter(this.scopeLookupTable);
 this.loadCurrentTheme();
   }
 
-  handleNotification(params: SemanticHighlightingParams) {}
+  handleNotification(params: SemanticHighlightingParams) {
+const lines: SemanticHighlightingLine[] = params.lines.map(
+(line) => ({line : line.line, tokens : decodeTokens(line.tokens)}));
+this.highlighter.highlight(params.textDocument.uri, lines);
+  }
 }
 
 // Converts a string of base64 encoded tokens into the corresponding array of
@@ -101,6 +117,100 @@
   return retTokens;
 }
 
+// The main class responsible for processing of highlightings that clangd
+// sends.
+export class Highlighter {
+  // Maps uris with currently open TextDocuments to the current highlightings

[PATCH] D66733: [analyzer] Add a checker option to detect nested dead stores

2019-08-26 Thread Balázs Benics via Phabricator via cfe-commits
steakhal created this revision.
steakhal added reviewers: NoQ, krememek, Szelethus, baloghadamsoftware.
Herald added subscribers: cfe-commits, Charusso, donat.nagy, dexonsmith, 
mikhail.ramalho, a.sidorin, rnkovacs, szepet, xazax.hun, whisperity.
Herald added a project: clang.

Enables the users to specify an optional flag which would warn for more dead 
stores.
Previously it ignored if the dead store happened e.g. in an if condition.

  if ((X = generate())) { // dead store to X
  }

This patch introduces the `WarnForDeadNestedAssignments` option to the checker, 
which is `false` by default - so this change would not affect any previous 
users.
I have updated the code, tests and the docs as well. If I missed something, 
tell me.

I also ran the analysis on Clang which generated 14 more reports compared to 
the unmodified version. All of them seemed reasonable for me.
Shouldn't we enable this option by default?
You can check those at this CodeChecker instance 
.
 Note that this link will no longer work after the patch has been accepted.

Related previous patches:
rGf224820b45c6847b91071da8d7ade59f373b96f3 



Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66733

Files:
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/dead-stores.c
  clang/test/Analysis/dead-stores.cpp

Index: clang/test/Analysis/dead-stores.cpp
===
--- clang/test/Analysis/dead-stores.cpp
+++ clang/test/Analysis/dead-stores.cpp
@@ -1,11 +1,14 @@
 // RUN: %clang_analyze_cc1 -fcxx-exceptions -fexceptions -fblocks -std=c++11 -analyzer-checker=deadcode.DeadStores -verify -Wno-unreachable-code %s
 // RUN: %clang_analyze_cc1 -fcxx-exceptions -fexceptions -fblocks -std=c++11 -analyzer-store=region -analyzer-checker=deadcode.DeadStores -verify -Wno-unreachable-code %s
+// RUN: %clang_analyze_cc1 -fcxx-exceptions -fexceptions -fblocks -std=c++11 -analyzer-checker=deadcode.DeadStores -analyzer-config deadcode.DeadStores:WarnForDeadNestedAssignments=true -verify -Wno-unreachable-code -DWARN_FOR_DEAD_NESTED %s
+
 
 //===--===//
 // Basic dead store checking (but in C++ mode).
 //===--===//
 
 int j;
+int make_int();
 void test1() {
   int x = 4;
 
@@ -17,6 +20,15 @@
 (void)x;
 break;
   }
+
+  int y;
+  (void)y;
+#ifdef WARN_FOR_DEAD_NESTED
+  if ((y = make_int())) // expected-warning{{Although the value stored}}
+#else
+  if ((y = make_int())) // no-warning
+#endif
+return;
 }
 
 //===--===//
Index: clang/test/Analysis/dead-stores.c
===
--- clang/test/Analysis/dead-stores.c
+++ clang/test/Analysis/dead-stores.c
@@ -1,5 +1,6 @@
 // RUN: %clang_analyze_cc1 -Wunused-variable -analyzer-checker=core,deadcode.DeadStores -fblocks -verify -Wno-unreachable-code -analyzer-opt-analyze-nested-blocks %s
 // RUN: %clang_analyze_cc1 -Wunused-variable -analyzer-checker=core,deadcode.DeadStores -analyzer-store=region -fblocks -verify -Wno-unreachable-code -analyzer-opt-analyze-nested-blocks %s
+// RUN: %clang_analyze_cc1 -Wunused-variable -analyzer-checker=core,deadcode.DeadStores -analyzer-config deadcode.DeadStores:WarnForDeadNestedAssignments=true -fblocks -verify -Wno-unreachable-code -analyzer-opt-analyze-nested-blocks -DWARN_FOR_DEAD_NESTED %s
 
 void f1() {
   int k, y; // expected-warning{{unused variable 'k'}} expected-warning{{unused variable 'y'}}
@@ -77,7 +78,11 @@
 // to see a real bug in this scenario.
 int f8(int *p) {
   extern int *baz();
+#ifdef WARN_FOR_DEAD_NESTED
+  if ((p = baz())) // expected-warning{{Although the value stored}}
+#else
   if ((p = baz())) // no-warning
+#endif
 return 1;
   return 0;
 }
@@ -152,8 +157,11 @@
 // to see a real bug in this scenario.
 int f16(int x) {
   x = x * 2;
-  x = sizeof(int [x = (x || x + 1) * 2])
-  ? 5 : 8;
+#ifdef WARN_FOR_DEAD_NESTED
+  x = sizeof(int [x = (x || x + 1) * 2]) ? 5 : 8; // expected-warning{{Although the value stored}}
+#else
+  x = sizeof(int [x = (x || x + 1) * 2]) ? 5 : 8; // no-warning
+#endif
   return x;
 }
 
@@ -182,7 +190,11 @@
 
 int f18_a() {
int x = 0; // no-warning
+#ifdef WARN_FOR_DEAD_NESTED
+   return (x = 10); // expected-warning{{Although the value stored}}
+#else
return (x = 10); // no-war

[PATCH] D66733: [analyzer] Add a checker option to detect nested dead stores

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

I really-really like this change. The results look great, though I'm not sure 
what happened here 
,
 are we sure that this originates from the analyzer, and is not some storing 
error?

In any case, please use `clang-format-diff.py` on this patch, otherwise LGTM.




Comment at: clang/include/clang/StaticAnalyzer/Checkers/Checkers.td:644
+  "E.g.: if ((P = f())) where P is unused."
+  "It will likely report false positives.",
+  "false",

Mmm, how about we soften this warning? :)

`"Enabling this may result in some false positive finds.`



Comment at: clang/include/clang/StaticAnalyzer/Checkers/Checkers.td:646
+  "false",
+  InAlpha>
+  ]>,

We mark checker options that are still in development with `InAlpha`, but I 
feel like this feature is as good as it gets. Feel free to mark it as 
`Released`, so it'll be user facing!



Comment at: clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp:223
 
-  case Enclosing:
-// Don't report issues in this case, e.g.: "if (x = foo())",
-// where 'x' is unused later.  We have yet to see a case where
-// this is a real bug.
-return;
+  case Enclosing: // eg.:f((x = foo()))
+if (!WarnForDeadNestedAssignments)

Could you please move this comment to the previous line?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66733



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


[PATCH] D65526: [Clangd] First version of ExtractFunction

2019-08-26 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:29
+//   - Always passed by l-value reference
+// - No return
+// - Cannot move declarations before extracting

did you mean no return *type* ?



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:30
+// - No return
+// - Cannot move declarations before extracting
+// - Doesn't check for broken control flow

don't understand what you meant here



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:31
+// - Cannot move declarations before extracting
+// - Doesn't check for broken control flow
+//

could you elaborate on that one?

You can ignore this comment if it is gonna be explained in the design doc(and 
you are planning to attach it before landing this revision)



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:42
+//methods for rendering it.
+// 4. CapturedZoneInfo uses a RAV to capture information about the extraction
+//like declarations, existing return statements, broken control flow, etc.

Tried hard to figure out what RAV is :D could you rather say 
`RecursiveASTVisitor(RAV)` ?



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:122
+return ZoneRelative::OutsideFunc;
+  if (Loc < ZoneRange.getBegin())
+return ZoneRelative::Before;

IIRC, `<` operator in `SourceLocation`s are merely for implementing hashing and 
doesn't really carry `less than` semantics. Could you rather use 
`SM.isBeforeInSLocAddrSpace`?



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:124
+return ZoneRelative::Before;
+  if (Loc < ZoneRange.getEnd())
+return ZoneRelative::Inside;

same here



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:133
+// Finds the function in which the zone lies.
+const Node *computeEnclosingFunction(const Node *CommonAnc) {
+  // Walk up the SelectionTree until we find a function Decl

Can you rather return a `FunctionDecl` ?



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:152
+
+// Find the union of source ranges of all child nodes of Parent. Returns an
+// invalid SourceRange if it fails to do so.

maybe rather return an llvm::Optional/Expected ?



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:165
+else
+  SR.setEnd(ChildFileRange->getEnd());
+  }

I suppose this relies on the fact that "AST contains the nodes ordered by their 
begin location"? Could you add an assertion for that?



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:176
+  const LangOptions &LangOpts) {
+  return *toHalfOpenFileRange(SM, LangOpts,
+  EnclosingFunction->ASTNode.getSourceRange());

what makes this fail-free ?



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:180
+
+// Check if all child nodes of (unselected) Parent are RootStmts.
+bool hasOnlyRootStmtChildren(const Node *Parent) {

This explains *what* the function is doing, but lacks the *reason why*

Could you explain the reason either in here or in the call site?



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:181
+// Check if all child nodes of (unselected) Parent are RootStmts.
+bool hasOnlyRootStmtChildren(const Node *Parent) {
+  for (const Node *Child : Parent->Children) {

`hasOnlyRootStmtsAsChildren` ?



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:215
+const Node *Parent = CommonAnc->Parent;
+// If parent is a DeclStmt, even though it's unselected, we consider it a
+// root statement and return its parent.

why ?



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:225
+// enclosingFunction.
+std::shared_ptr getExtractionZone(const Node *CommonAnc,
+  const SourceManager &SM,

why is this function returning a shared_ptr ?



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:332
+  if (WithTypeAndQualifiers) {
+if (IsConst)
+  Result += "const ";

why don't we infer this const from QualType ?



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:347
+ZoneRelative DeclaredIn;
+// Stores the numbering of this declaration(i for the i-th Decl)
+unsigned DeclIndex;

what does `numbering` mean ?


=

[PATCH] D66735: [clangd] Handling text editor/document lifetimes in vscode extension.

2019-08-26 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom created this revision.
jvikstrom added reviewers: hokein, ilya-biryukov.
Herald added subscribers: cfe-commits, kadircet, arphaman, jkorous, MaskRay.
Herald added a project: clang.

Just reapplies highlightings for all files when visible text editors change. 
Could find the correct text editor that should be reapplied but going for a 
simple implementation instead.
Removes the associated highlighting entry from the Colorizer when a text 
document is closed.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66735

Files:
  clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
  
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts


Index: 
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
===
--- 
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
+++ 
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
@@ -155,5 +155,19 @@
 highlighter.getDecorationRanges('file1'),
 createHighlightingScopeRanges(
 [ highlightingsInLine1, ...highlightingsInLine.slice(1) ]));
+// Opening a text editor reapplies all highlightings.
+highlighter.onDidChangeVisibleTextEditors();
+assert.deepEqual(
+highlighter.applicationUriHistory,
+[ 'file1', 'file1', 'file1', 'file2', 'file1', 'file1', 'file2' ]);
+assert.deepEqual(
+highlighter.getDecorationRanges('file1'),
+createHighlightingScopeRanges(
+[ highlightingsInLine1, ...highlightingsInLine.slice(1) ]));
+assert.deepEqual(highlighter.getDecorationRanges('file2'),
+ createHighlightingScopeRanges([ highlightingsInLine1 ]));
+// Closing a text document removes all highlightings for the file.
+highlighter.onDidCloseTextDocument('file1');
+assert.deepEqual(highlighter.getDecorationRanges('file1'), []);
   });
 });
Index: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
@@ -89,6 +89,11 @@
 // highlighter being created.
 this.highlighter = new Highlighter(this.scopeLookupTable);
 this.loadCurrentTheme();
+// Event handling for handling with TextDocuments/Editors lifetimes.
+vscode.window.onDidChangeVisibleTextEditors(
+() => this.highlighter.onDidChangeVisibleTextEditors());
+vscode.workspace.onDidCloseTextDocument(
+(doc) => this.highlighter.onDidCloseTextDocument(doc.uri.toString()));
   }
 
   handleNotification(params: SemanticHighlightingParams) {
@@ -150,12 +155,7 @@
   };
   return vscode.window.createTextEditorDecorationType(options);
 });
-this.getVisibleTextEditorUris().forEach((fileUri) => {
-  // A TextEditor might not be a cpp file. So we must check we have
-  // highlightings for the file before applying them.
-  if (this.files.has(fileUri))
-this.applyHighlights(fileUri);
-})
+this.reapplyAllHighlightings();
   }
 
   // Adds incremental highlightings to the current highlightings for the file
@@ -171,6 +171,25 @@
 this.applyHighlights(fileUri);
   }
 
+  // Called when a text document is closed. Removes any highlighting entries 
for
+  // the text document that was closed.
+  public onDidCloseTextDocument(fileUri: string) {
+// If there exists no entry the call to delete just returns false.
+this.files.delete(fileUri);
+  }
+
+  // Called when the currently visible text editors have changed. Reapplies
+  // highlightings to all visible text editors that highlightings exist for.
+  public onDidChangeVisibleTextEditors() { this.reapplyAllHighlightings(); }
+
+  protected reapplyAllHighlightings() {
+this.getVisibleTextEditorUris().forEach((fileUri) => {
+  // A TextEditor might not be a cpp file. So we must check we have
+  // highlightings for the file before applying them.
+  if (this.files.has(fileUri))
+this.applyHighlights(fileUri);
+});
+  }
   // Gets the uris as strings for the currently visible text editors.
   protected getVisibleTextEditorUris(): string[] {
 return vscode.window.visibleTextEditors.map((e) =>
@@ -180,6 +199,11 @@
   // Returns the ranges that should be used when decorating. Index i in the
   // range array has the decoration type at index i of this.decorationTypes.
   protected getDecorationRanges(fileUri: string): vscode.Range[][] {
+if (!this.files.has(fileUri))
+  // this.files should always have an entry for fileUri if we are here. But
+  // if there isn't one we don't want to crash the extension. This is also
+  // useful for tests.
+  return [];
 const lines: SemanticHighlightingLine[] =

[PATCH] D65526: [Clangd] First version of ExtractFunction

2019-08-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:46
+//creating a NewFunction.
+// Design Doc at 
+//===--===//

please fix or remove comment



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:88
+
+// The ExtractionZone class forms a view of the code wrt to Zone.
+// A RootStmt is a statement that's fully selected including all it's children

nit: "wrt to" -> wrt



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:104
+  SourceRange EnclosingFuncRange;
+  const SourceManager &SM;
+

remove from struct and pass as a parameter?
This isn't really data



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:112
+  }
+  const Node *getLastRootStmt() const {
+return Parent ? Parent->Children.back() : nullptr;

document why this is important, or just inline it?



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:113
+  const Node *getLastRootStmt() const {
+return Parent ? Parent->Children.back() : nullptr;
+  }

don't bother handling the null parent case. When can that happen? We should 
avoid creating an ExtractionZone struct entirely then.

Also none of the callsites bother to check for null...



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:132
+}
+// Finds the function in which the zone lies.
+const Node *computeEnclosingFunction(const Node *CommonAnc) {

nit: consistently one blank line between functions (in this file you alternate 
between 1/0)



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:157
+  SourceRange SR;
+  for (const Node *Child : Parent->Children) {
+auto ChildFileRange =

why are you doing this with a loop, isn't it just {first->begin,last->end}?



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:181
+// Check if all child nodes of (unselected) Parent are RootStmts.
+bool hasOnlyRootStmtChildren(const Node *Parent) {
+  for (const Node *Child : Parent->Children) {

kadircet wrote:
> `hasOnlyRootStmtsAsChildren` ?
nit: I think this would be clearer as
`canBeRootStmt(const Node*)` and write the callsite as 
`llvm::any_of(CommonAnc->Children, canBeRootStmt)`. Up to you though



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:225
+// enclosingFunction.
+std::shared_ptr getExtractionZone(const Node *CommonAnc,
+  const SourceManager &SM,

kadircet wrote:
> why is this function returning a shared_ptr ?
avoid shared_ptr unless there's a strong reason. `Optional` 
seems fine here?



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:257
+unsigned OrderPriority; // Lower value parameters are preferred first.
+std::string render(bool WithTypeAndQualifiers) const;
+bool operator<(const Parameter &Other) const {

there's no need for the WithTypeAndQualifiers=false version, that's just 
"fn.name"



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:270
+  tooling::ExtractionSemicolonPolicy SemicolonPolicy;
+  NewFunction(SourceRange BodyRange, SourceLocation InsertionPoint,
+  tooling::ExtractionSemicolonPolicy SemicolonPolicy,

this is just initializing public fields, drop the constructor?
(The callsite is clearer here if you initialize them by name)



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:280
+  // Add a new parameter for the function.
+  void addParam(llvm::StringRef Name, QualType TypeInfo, bool IsConst,
+bool IsReference, unsigned OrderPriority);

this is just push_back, inline into caller



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:285
+  const SourceManager &SM;
+  std::string renderParameters(bool WithTypeAndQualifiers) const;
+  // Generate the function body.

again, avoid sharing code between the complicated declaration case, and the 
trivial callsite case. It makes changes harder and obscures the hard case.



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp:326
+std::string spellType(QualType TypeInfo) {
+  return TypeInfo.getUnqualifiedType().getNonReferenceType().getAsString();
+};

use `printType` from AST.h?

(You'll want to drop qualifiers/refs before calling that, but it's not at all 
obvious from the function name here that they're dropped, so that should be at 
the callsite anyway)


===

[PATCH] D66735: [clangd] Handling text editor/document lifetimes in vscode extension.

2019-08-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts:94
+vscode.window.onDidChangeVisibleTextEditors(
+() => this.highlighter.onDidChangeVisibleTextEditors());
+vscode.workspace.onDidCloseTextDocument(

I think we can do it like 
`vscode.window.onDidChangeVisibleTextEditors((TextEditor[] editors) => { // 
call applyHighlight for each text editor })`.



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts:176
+  // the text document that was closed.
+  public onDidCloseTextDocument(fileUri: string) {
+// If there exists no entry the call to delete just returns false.

the name is a bit weird `onDidCloseTextDocument` in the `Highlighter`, I would 
name it `removeFileHighlights`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66735



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


[PATCH] D66736: clang-format: [JS] handle `as const`.

2019-08-26 Thread Martin Probst via Phabricator via cfe-commits
mprobst created this revision.
mprobst added a reviewer: krasimir.
Herald added a project: clang.

TypeScript 3.4 supports casting into a const type using `as const`:

  const x = {x: 1} as const;

Previously, clang-format would insert a space after the `const`. With
this patch, no space is inserted after the sequence `as const`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66736

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTestJS.cpp


Index: clang/unittests/Format/FormatTestJS.cpp
===
--- clang/unittests/Format/FormatTestJS.cpp
+++ clang/unittests/Format/FormatTestJS.cpp
@@ -1479,6 +1479,9 @@
   ".someFunction(aa);");
   verifyFormat("const xIsALongIdent:\n""YJustBarelyFitsLinex[];",
   getGoogleJSStyleWithColumns(20));
+  verifyFormat("const x = {\n"
+   "  y: 1\n"
+   "} as const;");
 }
 
 TEST_F(FormatTestJS, UnionIntersectionTypes) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2746,6 +2746,10 @@
tok::kw_void))
 return true;
 }
+// `foo as const;` casts into a const type.
+if (Left.endsSequence(tok::kw_const, Keywords.kw_as)) {
+  return false;
+}
 if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
   tok::kw_const) ||
  // "of" is only a keyword if it appears after another identifier


Index: clang/unittests/Format/FormatTestJS.cpp
===
--- clang/unittests/Format/FormatTestJS.cpp
+++ clang/unittests/Format/FormatTestJS.cpp
@@ -1479,6 +1479,9 @@
   ".someFunction(aa);");
   verifyFormat("const xIsALongIdent:\n""YJustBarelyFitsLinex[];",
   getGoogleJSStyleWithColumns(20));
+  verifyFormat("const x = {\n"
+   "  y: 1\n"
+   "} as const;");
 }
 
 TEST_F(FormatTestJS, UnionIntersectionTypes) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2746,6 +2746,10 @@
tok::kw_void))
 return true;
 }
+// `foo as const;` casts into a const type.
+if (Left.endsSequence(tok::kw_const, Keywords.kw_as)) {
+  return false;
+}
 if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
   tok::kw_const) ||
  // "of" is only a keyword if it appears after another identifier
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D66735: [clangd] Handling text editor/document lifetimes in vscode extension.

2019-08-26 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom marked an inline comment as done.
jvikstrom added inline comments.



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts:94
+vscode.window.onDidChangeVisibleTextEditors(
+() => this.highlighter.onDidChangeVisibleTextEditors());
+vscode.workspace.onDidCloseTextDocument(

hokein wrote:
> I think we can do it like 
> `vscode.window.onDidChangeVisibleTextEditors((TextEditor[] editors) => { // 
> call applyHighlight for each text editor })`.
There might be TextEditors that are not a c++ file/haven't gotten highlightings 
yet.

So we'd still need to do the this.files.has(fileUri) check which we also do in 
the initialize function. 

Maybe I should just expose the reapplyAllHighlightings function and call that 
one instead?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66735



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


[PATCH] D66676: [clang-tidy] TransformerClangTidyCheck: change choice of location for diagnostic message.

2019-08-26 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr added inline comments.



Comment at: 
clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp:106
+// argument, while the change spans only the argument AND there are two such
+// matches.  Here, we expect a conflict between the two matches and the second
+// to be ignored.

Sorry, I don't quite understand the comment -- the test has two replacements 
(both arguments to the macro are replaced), but the comment says that we only 
expect one.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66676



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


[PATCH] D66735: [clangd] Handling text editor/document lifetimes in vscode extension.

2019-08-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts:94
+vscode.window.onDidChangeVisibleTextEditors(
+() => this.highlighter.onDidChangeVisibleTextEditors());
+vscode.workspace.onDidCloseTextDocument(

jvikstrom wrote:
> hokein wrote:
> > I think we can do it like 
> > `vscode.window.onDidChangeVisibleTextEditors((TextEditor[] editors) => { // 
> > call applyHighlight for each text editor })`.
> There might be TextEditors that are not a c++ file/haven't gotten 
> highlightings yet.
> 
> So we'd still need to do the this.files.has(fileUri) check which we also do 
> in the initialize function. 
> 
> Maybe I should just expose the reapplyAllHighlightings function and call that 
> one instead?
if the file is not a c++, the current implementation of `applyHighlights` is 
tolerant with that I think, it doesn't do anything (we get an empty decoration 
ranges).

I think we can do the ` this.files.has(fileUri)` check in `applyHighlights`. 




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66735



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


[PATCH] D66486: [LifetimeAnalysis] Detect more cases when the address of a local variable escapes

2019-08-26 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr added inline comments.



Comment at: clang/lib/Sema/SemaInit.cpp:6775
+if (!pathOnlyInitializesGslPointer(Path))
+  Init = const_cast(Init->skipRValueSubobjectAdjustments());
 

xazax.hun wrote:
> gribozavr wrote:
> > I'm afraid this change could disable some other analysis, which would hide 
> > other lifetime issues. For example, while 'ptr' can't itself dangle, if 
> > 'Temp().ptr' is bound to a local reference, it might be subject to complex 
> > lifetime extension rules, which this warning originally tried to check for.
> I understand your concern, and I thin this code path is very tricky as it is 
> doing multiple things at once: lifetime extension and emitting warnings. 
> There are two cases when `pathOnlyInitializesGslPointer(Path)` returns true:
> * We are initializing a gsl::Pointer, so no references involved, we should 
> not do lifetime extension.
> * We are visiting the initialization of a reference (like walking a def-use 
> chain) that was used to 
> 
> In the second case, the reference initialization was already visited earlier 
> (when we first saw the initialization and did not follow any use of the 
> reference). In this earlier instance, since the reference is not a 
> gsl::Pointer, the call to `pathOnlyInitializesGslPointer` is evaluated to 
> false, and we did the lifetime extension. 
> 
> To observe this behavior you can dump the AST for the following code:
> ```
> namespace std {
> template
> struct reference_wrapper {
>   reference_wrapper(T &&);
> };
> 
> template
> reference_wrapper ref(T& t) noexcept;
> }
> 
> std::reference_wrapper treatForwardingRefAsLifetimeConst() {
>   const int &b = int(6);
>   return std::ref(b); 
> }
> ```
> 
> The result for me is:
> ```
> `-FunctionDecl 0xfa5828  line:34:35 
> treatForwardingRefAsLifetimeConst 'std::reference_wrapper ()'
>   `-CompoundStmt 0xfa7848 
> |-DeclStmt 0xfa5e58 
> | `-VarDecl 0xfa5cf0  col:14 used b 'const int &' cinit
> |   `-ExprWithCleanups 0xfa5de8  'const int' lvalue
> | `-MaterializeTemporaryExpr 0xfa5db8  'const int' 
> lvalue extended by Var 0xfa5cf0 'b' 'const int &'
> |   `-CXXFunctionalCastExpr 0xfa5d90  'int' 
> functional cast to int 
> | `-IntegerLiteral 0xfa5d70  'int' 6
> `-ReturnStmt 0xfa7838 
>   `-ExprWithCleanups 0xfa7820  
> 'std::reference_wrapper':'std::reference_wrapper'
> `-CXXConstructExpr 0xfa77f0  
> 'std::reference_wrapper':'std::reference_wrapper' 'void 
> (std::reference_wrapper &&) noexcept' elidable
>   `-MaterializeTemporaryExpr 0xfa7798  
> 'reference_wrapper':'std::reference_wrapper' xvalue
> `-CallExpr 0xfa7300  'reference_wrapper int>':'std::reference_wrapper'
>   |-ImplicitCastExpr 0xfa72e8  
> 'reference_wrapper (*)(const int &) noexcept' 
> 
>   | `-DeclRefExpr 0xfa7250  
> 'reference_wrapper (const int &) noexcept' lvalue Function 
> 0xfa7150 'ref' 'reference_wrapper (const int &) noexcept' 
> (FunctionTemplate 0xfa5500 'ref')
>   `-DeclRefExpr 0xfa5ed8  'const int' lvalue Var 0xfa5cf0 
> 'b' 'const int &'
> ```
> 
> Please let me know if you had a different example in mind.
> 
> (Also, this unfortunately is a false negative example for now, as we tend to 
> start with the less risky warnings :))
Thank you for the explanation. I don't feel I understand this code enough to 
accept such a subtle explanation for a change with potentially far-reaching 
consequences.

The "path" abstraction that this analysis is designed to catch problems with 
lifetime extension, and so far it seemed like we could tack our analysis onto 
it, but now it looks like the wrong abstraction for this purpose.

If you can find another reviewer who is more comfortable with this code, and 
they accept the patch, I have no objections though.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66486



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


[PATCH] D66738: [clangd] Added highlighting for structured bindings.

2019-08-26 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom created this revision.
jvikstrom added reviewers: hokein, ilya-biryukov.
Herald added subscribers: cfe-commits, kadircet, arphaman, jkorous, MaskRay.
Herald added a project: clang.

Structured bindings are in a BindingDecl. The decl the declRefExpr points to 
are the BindingDecls. So this adds an additional if statement in the addToken 
function to highlight them. First tries to find the "underlying" decl and 
highlight as that decl (for example, if it's a field it should be highligted as 
a field). If that does not work, it will be highlighted as a variable.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66738

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp


Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -431,6 +431,23 @@
 assert($Variable[[x]] != $Variable[[y]]);
 assert($Variable[[x]] != $Function[[f]]());
   }
+)cpp",
+R"cpp(
+  struct $Class[[S]] {
+$Primitive[[float]] $Field[[Member]];
+  };
+  $Class[[S]] $Function[[foo]]();
+  $Primitive[[void]] $Function[[f]]() {
+$Primitive[[int]] $Variable[[A]][2] = {1,2};
+auto [$Variable[[B1]], $Variable[[B2]]] = $Variable[[A]];
+auto& [$Variable[[R1]], $Variable[[R2]]] = $Variable[[A]];
+$Class[[auto]] [$Field[[M1]]] = $Class[[S]]();
+$Class[[auto]] [$Field[[F1]]] = $Function[[foo]]();
+$Field[[M1]] += 12.2;
+$Variable[[B1]] += 2;
+$Class[[S]] $Variable[[SArr]][2] = {$Class[[S]](), $Class[[S]]()};
+auto [$Variable[[S1]], $Variable[[S2]]] = $Variable[[SArr]];
+  }
 )cpp"};
   for (const auto &TestCase : TestCases) {
 checkHighlightings(TestCase);
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -229,6 +229,21 @@
   addToken(Loc, HighlightingKind::Variable);
   return;
 }
+if (const auto *B = dyn_cast(D)) {
+  // If we can find the underlying decl and highlight that we should do it.
+  // So first try to find and highlight the underlying NamedDecl for the
+  // binding if one exist.
+  if (const auto *BB = B->getBinding())
+if (const auto *RD = BB->getReferencedDeclOfCallee())
+  if (const auto *D = dyn_cast(RD)) {
+addToken(Loc, D);
+return;
+  }
+  // Could not find a more specific decl for this BindingDecl. So just
+  // highlight as a normal variable.
+  addToken(Loc, HighlightingKind::Variable);
+  return;
+}
 if (isa(D)) {
   addToken(Loc, HighlightingKind::Function);
   return;


Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -431,6 +431,23 @@
 assert($Variable[[x]] != $Variable[[y]]);
 assert($Variable[[x]] != $Function[[f]]());
   }
+)cpp",
+R"cpp(
+  struct $Class[[S]] {
+$Primitive[[float]] $Field[[Member]];
+  };
+  $Class[[S]] $Function[[foo]]();
+  $Primitive[[void]] $Function[[f]]() {
+$Primitive[[int]] $Variable[[A]][2] = {1,2};
+auto [$Variable[[B1]], $Variable[[B2]]] = $Variable[[A]];
+auto& [$Variable[[R1]], $Variable[[R2]]] = $Variable[[A]];
+$Class[[auto]] [$Field[[M1]]] = $Class[[S]]();
+$Class[[auto]] [$Field[[F1]]] = $Function[[foo]]();
+$Field[[M1]] += 12.2;
+$Variable[[B1]] += 2;
+$Class[[S]] $Variable[[SArr]][2] = {$Class[[S]](), $Class[[S]]()};
+auto [$Variable[[S1]], $Variable[[S2]]] = $Variable[[SArr]];
+  }
 )cpp"};
   for (const auto &TestCase : TestCases) {
 checkHighlightings(TestCase);
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -229,6 +229,21 @@
   addToken(Loc, HighlightingKind::Variable);
   return;
 }
+if (const auto *B = dyn_cast(D)) {
+  // If we can find the underlying decl and highlight that we should do it.
+  // So first try to find and highlight the underlying NamedDecl for the
+  // binding if one exist.
+  if (const auto *BB = B->getBinding())
+if (const auto *RD = BB->getReferencedDeclOfCallee())
+  if (const auto *D = dyn_cast(RD)) {
+add

[PATCH] D66735: [clangd] Handling text editor/document lifetimes in vscode extension.

2019-08-26 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom updated this revision to Diff 217131.
jvikstrom added a comment.

Address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66735

Files:
  clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
  
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts


Index: 
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
===
--- 
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
+++ 
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
@@ -155,5 +155,11 @@
 highlighter.getDecorationRanges('file1'),
 createHighlightingScopeRanges(
 [ highlightingsInLine1, ...highlightingsInLine.slice(1) ]));
+// Closing a text document removes all highlightings for the file and no
+// other files.
+highlighter.removeHighlightings('file1');
+assert.deepEqual(highlighter.getDecorationRanges('file1'), []);
+assert.deepEqual(highlighter.getDecorationRanges('file2'),
+ createHighlightingScopeRanges([ highlightingsInLine1 ]));
   });
 });
Index: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
@@ -89,6 +89,13 @@
 // highlighter being created.
 this.highlighter = new Highlighter(this.scopeLookupTable);
 this.loadCurrentTheme();
+// Event handling for handling with TextDocuments/Editors lifetimes.
+vscode.window.onDidChangeVisibleTextEditors(
+(editors: vscode.TextEditor[]) =>
+editors.forEach((e) => this.highlighter.applyHighlights(
+e.document.uri.toString(;
+vscode.workspace.onDidCloseTextDocument(
+(doc) => this.highlighter.removeHighlightings(doc.uri.toString()));
   }
 
   handleNotification(params: SemanticHighlightingParams) {
@@ -150,12 +157,8 @@
   };
   return vscode.window.createTextEditorDecorationType(options);
 });
-this.getVisibleTextEditorUris().forEach((fileUri) => {
-  // A TextEditor might not be a cpp file. So we must check we have
-  // highlightings for the file before applying them.
-  if (this.files.has(fileUri))
-this.applyHighlights(fileUri);
-})
+this.getVisibleTextEditorUris().forEach((fileUri) =>
+this.applyHighlights(fileUri));
   }
 
   // Adds incremental highlightings to the current highlightings for the file
@@ -171,6 +174,13 @@
 this.applyHighlights(fileUri);
   }
 
+  // Called when a text document is closed. Removes any highlighting entries 
for
+  // the text document that was closed.
+  public removeHighlightings(fileUri: string) {
+// If there exists no entry the call to delete just returns false.
+this.files.delete(fileUri);
+  }
+
   // Gets the uris as strings for the currently visible text editors.
   protected getVisibleTextEditorUris(): string[] {
 return vscode.window.visibleTextEditors.map((e) =>
@@ -180,6 +190,11 @@
   // Returns the ranges that should be used when decorating. Index i in the
   // range array has the decoration type at index i of this.decorationTypes.
   protected getDecorationRanges(fileUri: string): vscode.Range[][] {
+if (!this.files.has(fileUri))
+  // this.files should always have an entry for fileUri if we are here. But
+  // if there isn't one we don't want to crash the extension. This is also
+  // useful for tests.
+  return [];
 const lines: SemanticHighlightingLine[] =
 Array.from(this.files.get(fileUri).values());
 const decorations: vscode.Range[][] = this.decorationTypes.map(() => []);
@@ -193,8 +208,12 @@
 return decorations;
   }
 
-  // Applies all the highlightings currently stored for a file with fileUri.
-  protected applyHighlights(fileUri: string) {
+  // Applies all the highlightings currently stored for a file with fileUri. If
+  public applyHighlights(fileUri: string) {
+if (!this.files.has(fileUri))
+  // There are no highlightings for this file, must return early or will 
get
+  // out of bounds when applying the decorations below.
+  return;
 if (!this.decorationTypes.length)
   // Can't apply any decorations when there is no theme loaded.
   return;


Index: clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.te

[PATCH] D66572: [analyzer] BugReporter Separation Ep.I.

2019-08-26 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr added a comment.

Sorry for the silly comments, but my main point is, I guess, that I don't quite 
understand the design towards which you are refactoring, and to meaningfully 
review patches I need to be on the same page.




Comment at: clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h:75
 /// individual bug reports.
 class BugReport : public llvm::ilist_node {
 public:

Szelethus wrote:
> Shouldn't we make this an abstract class?
I'm not sure that intrusive linked list is the right data structure for the 
job. I'd personally put bug reports into a vector and make a custom data 
structure if a vector becomes a performance problem.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h:122
+  /// Get the location on which the report should be uniqued.
+  virtual PathDiagnosticLocation getUniqueingLocation() const {
+return Location;

Where can I read about the uniqueing logic? Does it mean that out of two bug 
reports with the same location only one gets displayed, regardless of other 
properties?



Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h:126-135
+  /// Get the declaration containing the uniqueing location.
+  virtual const Decl *getUniqueingDecl() const {
+return DeclWithIssue;
+  }
+
+  /// Return the canonical declaration, be it a method or class, where
+  /// this issue semantically occurred.

I don't think `getUniqueingDecl()` and `getDeclWithIssue()` make sense for most 
ClangTidy checkers.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h:159
+  // FIXME: Instead of making an overload, we could have default-initialized
+  // Ranges with {}, however it crashes the MSVC 2013 compiler.
+  void addNote(StringRef Msg, const PathDiagnosticLocation &Pos) {

We don't care about MSVC 2013 now.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h:174
+  ///  This location is used by clients rendering diagnostics.
+  virtual PathDiagnosticLocation getLocation(const SourceManager &SM) const {
+assert(Location.isValid());

Another location-related method... I guess I would appreciate a more abstract 
writeup about what BugReport's data model is (in its doc comment).



Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h:186
+  /// ranges.
+  void addRange(SourceRange R) {
+assert((R.isValid() || Ranges.empty()) && "Invalid range can only be used "

Ranges should be associated with a message.


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

https://reviews.llvm.org/D66572



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


[PATCH] D66735: [clangd] Handling text editor/document lifetimes in vscode extension.

2019-08-26 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom updated this revision to Diff 217134.
jvikstrom added a comment.

Fixed changes that weren't supposed to be made.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66735

Files:
  clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
  
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts

Index: clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
@@ -107,7 +107,7 @@
 highlighter.highlight('file1', []);
 assert.deepEqual(highlighter.applicationUriHistory, [ 'file1' ]);
 highlighter.initialize(tm);
-assert.deepEqual(highlighter.applicationUriHistory, [ 'file1', 'file1' ]);
+assert.deepEqual(highlighter.applicationUriHistory, [ 'file1', 'file1', 'file2' ]);
 // Groups decorations into the scopes used.
 let highlightingsInLine: semanticHighlighting.SemanticHighlightingLine[] = [
   {
@@ -129,7 +129,7 @@
 
 highlighter.highlight('file1', highlightingsInLine);
 assert.deepEqual(highlighter.applicationUriHistory,
- [ 'file1', 'file1', 'file1' ]);
+ [ 'file1', 'file1', 'file2', 'file1' ]);
 assert.deepEqual(highlighter.getDecorationRanges('file1'),
  createHighlightingScopeRanges(highlightingsInLine));
 // Keeps state separate between files.
@@ -142,18 +142,24 @@
 };
 highlighter.highlight('file2', [ highlightingsInLine1 ]);
 assert.deepEqual(highlighter.applicationUriHistory,
- [ 'file1', 'file1', 'file1', 'file2' ]);
+ [ 'file1', 'file1', 'file2', 'file1', 'file2' ]);
 assert.deepEqual(highlighter.getDecorationRanges('file2'),
  createHighlightingScopeRanges([ highlightingsInLine1 ]));
 // Does full colorizations.
 highlighter.highlight('file1', [ highlightingsInLine1 ]);
 assert.deepEqual(highlighter.applicationUriHistory,
- [ 'file1', 'file1', 'file1', 'file2', 'file1' ]);
+ [ 'file1', 'file1', 'file2', 'file1', 'file2', 'file1' ]);
 // After the incremental update to line 1, the old highlightings at line 1
 // will no longer exist in the array.
 assert.deepEqual(
 highlighter.getDecorationRanges('file1'),
 createHighlightingScopeRanges(
 [ highlightingsInLine1, ...highlightingsInLine.slice(1) ]));
+// Closing a text document removes all highlightings for the file and no
+// other files.
+highlighter.removeFileHighlightings('file1');
+assert.deepEqual(highlighter.getDecorationRanges('file1'), []);
+assert.deepEqual(highlighter.getDecorationRanges('file2'),
+ createHighlightingScopeRanges([ highlightingsInLine1 ]));
   });
 });
Index: clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
@@ -89,6 +89,13 @@
 // highlighter being created.
 this.highlighter = new Highlighter(this.scopeLookupTable);
 this.loadCurrentTheme();
+// Event handling for handling with TextDocuments/Editors lifetimes.
+vscode.window.onDidChangeVisibleTextEditors(
+(editors: vscode.TextEditor[]) =>
+editors.forEach((e) => this.highlighter.applyHighlights(
+e.document.uri.toString(;
+vscode.workspace.onDidCloseTextDocument(
+(doc) => this.highlighter.removeFileHighlightings(doc.uri.toString()));
   }
 
   handleNotification(params: SemanticHighlightingParams) {
@@ -150,12 +157,8 @@
   };
   return vscode.window.createTextEditorDecorationType(options);
 });
-this.getVisibleTextEditorUris().forEach((fileUri) => {
-  // A TextEditor might not be a cpp file. So we must check we have
-  // highlightings for the file before applying them.
-  if (this.files.has(fileUri))
-this.applyHighlights(fileUri);
-})
+this.getVisibleTextEditorUris().forEach((fileUri) =>
+this.applyHighlights(fileUri));
   }
 
   // Adds incremental highlightings to the current highlightings for the file
@@ -171,6 +174,13 @@
 this.applyHighlights(fileUri);
   }
 
+  // Called when a text document is closed. Removes any highlighting entries for
+  // the text document that was closed.
+  public removeFileHighlightings(fileUri: string) {
+// If there exists no entry the call to delete just returns false.
+this.files.delete(fileU

[PATCH] D59692: [ASTImporter] Fix name conflict handling

2019-08-26 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 217135.
martong added a comment.
Herald added a project: LLDB.
Herald added a subscriber: lldb-commits.

- Use resulting Name from HandleNameConflict if set
- Add ODRHandling strategies
- Refactor tests, to avoid some code repetition


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59692

Files:
  clang/include/clang/AST/ASTImporter.h
  clang/lib/AST/ASTImporter.cpp
  clang/test/Analysis/Inputs/ctu-other.c
  clang/unittests/AST/ASTImporterFixtures.cpp
  clang/unittests/AST/ASTImporterFixtures.h
  clang/unittests/AST/ASTImporterTest.cpp
  lldb/include/lldb/Symbol/ClangASTImporter.h

Index: lldb/include/lldb/Symbol/ClangASTImporter.h
===
--- lldb/include/lldb/Symbol/ClangASTImporter.h
+++ lldb/include/lldb/Symbol/ClangASTImporter.h
@@ -252,7 +252,9 @@
 : clang::ASTImporter(*target_ctx, master.m_file_manager, *source_ctx,
  master.m_file_manager, true /*minimal*/),
   m_decls_to_deport(nullptr), m_decls_already_deported(nullptr),
-  m_master(master), m_source_ctx(source_ctx) {}
+  m_master(master), m_source_ctx(source_ctx) {
+setODRHandling(clang::ASTImporter::ODRHandlingType::Liberal);
+  }
 
 /// Scope guard that attaches a CxxModuleHandler to an ASTImporterDelegate
 /// and deattaches it at the end of the scope. Supports being used multiple
Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -1879,7 +1879,7 @@
   auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
   // We expect one (ODR) warning during the import.
   EXPECT_EQ(1u, ToTU->getASTContext().getDiagnostics().getNumWarnings());
-  EXPECT_EQ(2u,
+  EXPECT_EQ(1u,
 DeclCounter().match(ToTU, recordDecl(hasName("X";
 }
 
@@ -2432,6 +2432,62 @@
   EXPECT_EQ(ToD1, ToD2);
 }
 
+TEST_P(ImportFunctionTemplates,
+   ImportFunctionWhenThereIsAFunTemplateWithSameName) {
+  getToTuDecl(
+  R"(
+  template 
+  void foo(T) {}
+  void foo();
+  )",
+  Lang_CXX);
+  Decl *FromTU = getTuDecl("void foo();", Lang_CXX);
+  auto *FromD = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("foo")));
+  auto *ImportedD = Import(FromD, Lang_CXX);
+  EXPECT_TRUE(ImportedD);
+}
+
+TEST_P(ImportFunctionTemplates,
+   ImportConstructorWhenThereIsAFunTemplateWithSameName) {
+  auto Code =
+  R"(
+  struct Foo {
+template 
+Foo(T) {}
+Foo();
+  };
+  )";
+  getToTuDecl(Code, Lang_CXX);
+  Decl *FromTU = getTuDecl(Code, Lang_CXX);
+  auto *FromD =
+  LastDeclMatcher().match(FromTU, cxxConstructorDecl());
+  auto *ImportedD = Import(FromD, Lang_CXX);
+  EXPECT_TRUE(ImportedD);
+}
+
+TEST_P(ImportFunctionTemplates,
+   ImportOperatorWhenThereIsAFunTemplateWithSameName) {
+  getToTuDecl(
+  R"(
+  template 
+  void operator<(T,T) {}
+  struct X{};
+  void operator<(X, X);
+  )",
+  Lang_CXX);
+  Decl *FromTU = getTuDecl(
+  R"(
+  struct X{};
+  void operator<(X, X);
+  )",
+  Lang_CXX);
+  auto *FromD = LastDeclMatcher().match(
+  FromTU, functionDecl(hasOverloadedOperatorName("<")));
+  auto *ImportedD = Import(FromD, Lang_CXX);
+  EXPECT_TRUE(ImportedD);
+}
+
 struct ImportFriendFunctions : ImportFunctions {};
 
 TEST_P(ImportFriendFunctions, ImportFriendFunctionRedeclChainProto) {
@@ -5127,15 +5183,6 @@
   }
 }
 
-INSTANTIATE_TEST_CASE_P(ParameterizedTests, ErrorHandlingTest,
-DefaultTestValuesForRunOptions, );
-
-INSTANTIATE_TEST_CASE_P(ParameterizedTests, DeclContextTest,
-::testing::Values(ArgVector()), );
-
-INSTANTIATE_TEST_CASE_P(ParameterizedTests, CanonicalRedeclChain,
-::testing::Values(ArgVector()), );
-
 TEST_P(ASTImporterOptionSpecificTestBase, LambdaInFunctionBody) {
   Decl *FromTU = getTuDecl(
   R"(
@@ -5233,8 +5280,8 @@
   // prototype (inside 'friend') for it comes first in the AST and is not
   // linked to the definition.
   EXPECT_EQ(ImportedDef, ToClassDef);
-}  
-  
+}
+
 struct LLDBLookupTest : ASTImporterOptionSpecificTestBase {
   LLDBLookupTest() {
 Creator = [](ASTContext &ToContext, FileManager &ToFileManager,
@@ -5362,10 +5409,388 @@
   EXPECT_EQ(ImportedX->isAggregate(), FromX->isAggregate());
 }
 
+// FIXME Put ODR handling strategy related tests into their own test file. And
+// create type parameterized tests for them like we do in
+// ASTImporterGenericRedeclTest.cpp
+struct ConflictingDeclsWithConservativeStrategy
+: ASTImporterOptionSpecificTestBase {};
+
+struct ConflictingDeclsWithLiberalStrategy : ASTImporterOptionSpecificTestBase {
+  ConflictingDeclsWithLiberalStrateg

[PATCH] D66735: [clangd] Handling text editor/document lifetimes in vscode extension.

2019-08-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

I think there is one more case  -- we need to cleanup the highlighting cache if 
clangd crashes, the extension will automatically restart clangd up to 5 times 
if it sees clangd crashes, you can see how filestatus 

 handles it.




Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts:177
 
+  // Called when a text document is closed. Removes any highlighting entries 
for
+  // the text document that was closed.

I think `remove all highlightings for the file with the given fileUri.` is 
enough.



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts:211
 
-  // Applies all the highlightings currently stored for a file with fileUri.
-  protected applyHighlights(fileUri: string) {
+  // Applies all the highlightings currently stored for a file with fileUri. If
+  public applyHighlights(fileUri: string) {

nit: the trailing `If`? 



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts:212
+  // Applies all the highlightings currently stored for a file with fileUri. If
+  public applyHighlights(fileUri: string) {
+if (!this.files.has(fileUri))

could you move this method after `highlight`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66735



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


[PATCH] D59692: [ASTImporter] Fix name conflict handling with different strategies

2019-08-26 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

@shafik I have updated the patch with ODR handling strategies as per our 
discusson.

For the record I copy our discussion here:

On Sat, Aug 24, 2019 at 12:50 AM Shafik Yaghmour  
wrote:

> Apologies, I missed this earlier!
> 
> On Wed, Aug 21, 2019 at 2:44 AM Gábor Márton  wrote:
>  >
>  > Hi Shafik,
>  >
>  > > Right now you will end up w/ an arbitrary one of them but we do want to 
> support
>  > a way to choose between them eventually.
>  >
>  > Actually, right now (if the patch is not merged) we end up having both of 
> them in the AST. Some parts of the AST reference the existing definition, 
> while some other parts reference the new definition. Also, the regular lookup 
> will find both definitions.
>  >
>  > If the patch is merged then only the first (the existing) definition is 
> kept and an error is reported.
>  >
>  > > AFAICT this would prevent such a solution. At least that is how the
>  > new test case for RecordDecl make it appear
>  >
>  > Yes, you will never be able to remove an existing node from the AST, so I 
> don't think an either-or choosing mechanism is feasible. But you may be able 
> to decide whether you want to add the new and conflicting node. And you may 
> be able to use a different name for the new conflicting node. This may help 
> clients to see which node they are using.
>  > I want to create an additional patch which builds on this patch. Here is 
> the essence of what I'd like to have:
>  >   if (!ConflictingDecls.empty()) {
>  > Expected Resolution = Importer.HandleNameConflict(
>  > Name, DC, Decl::IDNS_Member, ConflictingDecls.data(),
>  > ConflictingDecls.size());
>  > if (Resolution)
>  >   Name = Resolution.get();
>  > else
>  >   return Resolution.takeError();
>  >   }
>  > Consider the "else" branch. I'd like to have such an "else" branch 
> everywhere. The point is to use the result of HandleNameConflict (if it is 
> set to something). This way it is possible to create any kind of ODR handling 
> by overwriting HandleNameConflict in the descendant classes.
>  >
>  > We identified 3 possible strategies so far:
>  >
>  > Conservative. In case of name conflict propagate the error. This should be 
> the default behavior.
>  > Liberal. In case of name conflict create a new node with the same name and 
> do not propagate the error.
>  > Rename. In case of name conflict create a new node with a different name 
> (e.g. with a prefix of the TU's name). Do not propagate the error.
>  >
>  >
>  > If we add a new conflicting node beside the exiting one, then some clients 
> of the AST which rely on lookup will be confused. The CTU client does not 
> rely on lookup so that is not really a problem there, but I don't know what 
> this could cause with LLDB. Perhaps the renaming strategy could work there 
> too.
>  > The Conservative and Liberal strategies are very easy to implement, and I 
> am going to create patches for that if we have consensus.
> 
> We know currently we do have cases where we have ODR violations w/
>  RecordDecl due to use of an opaque struct in the API headers and a
>  concrete instance internally e.g.:
> 
> //opaque
>  struct A {
> 
>   char buf[16];
> 
> };
> 
> //concrete
>  struct A {
> 
>   double d;
>   int64_t x;
> 
> };
> 
> and we don't want this to become an error.
> 
> I think we would at least one the choice of Conservative or Liberal to
>  be configurable and maybe LLDB would default to Liberal. This would
>  enable us to keep the status quo and not break existing cases any
>  worse than they already are.
> 
> I would prefer that would be done in this PR since I don't want to be
>  in a situation where we branch internally and we have this change but
>  not the follow-up change.
> 
>> >  I don't see how like you comment says this does not effect CXXRecordDecl
>  >
>  > In my comment I do not say that CXXRecordDecls are exceptions from the 
> general way of handling ODR violations.
>  > The comment is about that we shall not report ODR errors if we are not 
> 100% sure that we face one.
>  > So we should report an ODR error only if the found Decl and the newly 
> imported Decl have the same kind.
>  > I.e. both are CXXRecordDecls.
>  > For example, let's assume we import a CXXRecordDecl and we find an 
> existing ClassTemplateDecl with the very same Name.
>  > Then we should not report an ODR violation.
> 
> Thank you for the clarification, I misunderstood the comment, now it
>  makes more sense.
> 
>> Thanks,
>  > Gabor
>  >
>  >
>  > On Mon, Aug 19, 2019 at 5:46 PM Shafik Yaghmour 
>  wrote:
>  >>
>  >> Have a nice vacation :-)
>  >>
>  >> On Mon, Aug 19, 2019 at 8:40 AM Gábor Márton  
> wrote:
>  >> >
>  >> > Hi Shafik,
>  >> >
>  >> > I'll have an answer for you on Wednesday, I'm on vacation until then.
>  >> >
>  >> > Thanks,
>  >> > Gábor
>  >> >
>  >> > On Sat, 17 Aug 2019, 04:30 Shafik Yaghmour,  
> wrote:
>  >> >>
>  >> >> Hello Gábor,
>  >> >>
>  >> >> I was looking at

[clang-tools-extra] r369911 - [clangd] Handling text editor/document lifetimes in vscode extension.

2019-08-26 Thread Johan Vikstrom via cfe-commits
Author: jvikstrom
Date: Mon Aug 26 06:56:45 2019
New Revision: 369911

URL: http://llvm.org/viewvc/llvm-project?rev=369911&view=rev
Log:
[clangd] Handling text editor/document lifetimes in vscode extension.

Summary:
Just reapplies highlightings for all files when visible text editors change. 
Could find the correct text editor that should be reapplied but going for a 
simple implementation instead.
Removes the associated highlighting entry from the Colorizer when a text 
document is closed.

Reviewers: hokein, ilya-biryukov

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

Tags: #clang

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

Modified:

clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts

clang-tools-extra/trunk/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts

Modified: 
clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts?rev=369911&r1=369910&r2=369911&view=diff
==
--- 
clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
 (original)
+++ 
clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
 Mon Aug 26 06:56:45 2019
@@ -89,6 +89,13 @@ export class SemanticHighlightingFeature
 // highlighter being created.
 this.highlighter = new Highlighter(this.scopeLookupTable);
 this.loadCurrentTheme();
+// Event handling for handling with TextDocuments/Editors lifetimes.
+vscode.window.onDidChangeVisibleTextEditors(
+(editors: vscode.TextEditor[]) =>
+editors.forEach((e) => this.highlighter.applyHighlights(
+e.document.uri.toString(;
+vscode.workspace.onDidCloseTextDocument(
+(doc) => this.highlighter.removeFileHighlightings(doc.uri.toString()));
   }
 
   handleNotification(params: SemanticHighlightingParams) {
@@ -150,12 +157,8 @@ export class Highlighter {
   };
   return vscode.window.createTextEditorDecorationType(options);
 });
-this.getVisibleTextEditorUris().forEach((fileUri) => {
-  // A TextEditor might not be a cpp file. So we must check we have
-  // highlightings for the file before applying them.
-  if (this.files.has(fileUri))
-this.applyHighlights(fileUri);
-})
+this.getVisibleTextEditorUris().forEach((fileUri) =>
+this.applyHighlights(fileUri));
   }
 
   // Adds incremental highlightings to the current highlightings for the file
@@ -171,6 +174,13 @@ export class Highlighter {
 this.applyHighlights(fileUri);
   }
 
+  // Called when a text document is closed. Removes any highlighting entries 
for
+  // the text document that was closed.
+  public removeFileHighlightings(fileUri: string) {
+// If there exists no entry the call to delete just returns false.
+this.files.delete(fileUri);
+  }
+
   // Gets the uris as strings for the currently visible text editors.
   protected getVisibleTextEditorUris(): string[] {
 return vscode.window.visibleTextEditors.map((e) =>
@@ -180,6 +190,11 @@ export class Highlighter {
   // Returns the ranges that should be used when decorating. Index i in the
   // range array has the decoration type at index i of this.decorationTypes.
   protected getDecorationRanges(fileUri: string): vscode.Range[][] {
+if (!this.files.has(fileUri))
+  // this.files should always have an entry for fileUri if we are here. But
+  // if there isn't one we don't want to crash the extension. This is also
+  // useful for tests.
+  return [];
 const lines: SemanticHighlightingLine[] =
 Array.from(this.files.get(fileUri).values());
 const decorations: vscode.Range[][] = this.decorationTypes.map(() => []);
@@ -194,7 +209,11 @@ export class Highlighter {
   }
 
   // Applies all the highlightings currently stored for a file with fileUri.
-  protected applyHighlights(fileUri: string) {
+  public applyHighlights(fileUri: string) {
+if (!this.files.has(fileUri))
+  // There are no highlightings for this file, must return early or will 
get
+  // out of bounds when applying the decorations below.
+  return;
 if (!this.decorationTypes.length)
   // Can't apply any decorations when there is no theme loaded.
   return;

Modified: 
clang-tools-extra/trunk/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts?rev=369911&r1=369910&r2=369911&view=diff
==
--- 
clang-tools-extra/trunk/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
 (original)
+++ 
clang-tools-ext

[PATCH] D66740: [clangd] Add docs for configuration knobs in clangd

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

This is a first step in documenting different configuration knobs we
have in clangd.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66740

Files:
  clang-tools-extra/docs/clangd/Configuration.rst
  clang-tools-extra/docs/clangd/index.rst


Index: clang-tools-extra/docs/clangd/index.rst
===
--- clang-tools-extra/docs/clangd/index.rst
+++ clang-tools-extra/docs/clangd/index.rst
@@ -7,6 +7,7 @@
 
Installation
Features
+   Configuration
 
 What is clangd?
 ===
Index: clang-tools-extra/docs/clangd/Configuration.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clangd/Configuration.rst
@@ -0,0 +1,41 @@
+
+Configuration
+
+
+.. contents::
+
+.. role:: raw-html(raw)
+   :format: html
+
+Clangd has a bunch of command-line options and LSP capabilities that can change
+its behaviour in certain situations. This page aims to define those
+configuration knobs.
+
+--query-driver
+==
+
+Clangd makes use of clang behind the scenes, so it might fail to detect your
+standard library or built-in headers if your project is making use of a custom
+toolchain. That is quite common in hardware-related projects, especially for 
the
+ones making use of gcc (e.g. ARM's `arm-none-eabi-gcc`).
+
+To get over this clangd can query your toolchain driver to extract implicit
+include paths that are unknown to clang. Since this requires executing a 
binary,
+we require users of this feature to whitelist their driver using the
+`--query-driver` flag. It accepts a comma-separated list of globs, which will
+match against the compiler driver paths specified in your
+`compile_commands.json`.
+
+For example if you have your compilers at
+`/path/to/my-custom-toolchain/arm-none-eabi-gcc` and
+`/path/to/my-custom-toolchain/arm-none-eabi-g++`; you
+can provide clangd with `--query-driver=**/my-custom-toolchain/arm-none-eabi*`
+to enable execution of any binary that has a name starting with `arm-none-eabi`
+and under a directory called `my-custom-toolchain`.
+
+By default this flag is empty, which disallows execution of any driver.
+
+Full list of flags
+==
+
+You can find rest of the flags in `source code 
`__.


Index: clang-tools-extra/docs/clangd/index.rst
===
--- clang-tools-extra/docs/clangd/index.rst
+++ clang-tools-extra/docs/clangd/index.rst
@@ -7,6 +7,7 @@
 
Installation
Features
+   Configuration
 
 What is clangd?
 ===
Index: clang-tools-extra/docs/clangd/Configuration.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clangd/Configuration.rst
@@ -0,0 +1,41 @@
+
+Configuration
+
+
+.. contents::
+
+.. role:: raw-html(raw)
+   :format: html
+
+Clangd has a bunch of command-line options and LSP capabilities that can change
+its behaviour in certain situations. This page aims to define those
+configuration knobs.
+
+--query-driver
+==
+
+Clangd makes use of clang behind the scenes, so it might fail to detect your
+standard library or built-in headers if your project is making use of a custom
+toolchain. That is quite common in hardware-related projects, especially for the
+ones making use of gcc (e.g. ARM's `arm-none-eabi-gcc`).
+
+To get over this clangd can query your toolchain driver to extract implicit
+include paths that are unknown to clang. Since this requires executing a binary,
+we require users of this feature to whitelist their driver using the
+`--query-driver` flag. It accepts a comma-separated list of globs, which will
+match against the compiler driver paths specified in your
+`compile_commands.json`.
+
+For example if you have your compilers at
+`/path/to/my-custom-toolchain/arm-none-eabi-gcc` and
+`/path/to/my-custom-toolchain/arm-none-eabi-g++`; you
+can provide clangd with `--query-driver=**/my-custom-toolchain/arm-none-eabi*`
+to enable execution of any binary that has a name starting with `arm-none-eabi`
+and under a directory called `my-custom-toolchain`.
+
+By default this flag is empty, which disallows execution of any driver.
+
+Full list of flags
+==
+
+You can find rest of the flags in `source code `__.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D66676: [clang-tidy] TransformerClangTidyCheck: change choice of location for diagnostic message.

2019-08-26 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 217146.
ymandel added a comment.

fixed comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66676

Files:
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
  clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
@@ -18,18 +18,18 @@
 namespace tidy {
 namespace utils {
 namespace {
+using namespace ::clang::ast_matchers;
+
 using tooling::change;
 using tooling::IncludeFormat;
+using tooling::node;
 using tooling::RewriteRule;
+using tooling::statement;
 using tooling::text;
 using tooling::stencil::cat;
 
 // Invert the code of an if-statement, while maintaining its semantics.
 RewriteRule invertIf() {
-  using namespace ::clang::ast_matchers;
-  using tooling::node;
-  using tooling::statement;
-
   StringRef C = "C", T = "T", E = "E";
   RewriteRule Rule = tooling::makeRule(
   ifStmt(hasCondition(expr().bind(C)), hasThen(stmt().bind(T)),
@@ -67,6 +67,56 @@
   EXPECT_EQ(Expected, test::runCheckOnCode(Input));
 }
 
+class IntLitCheck : public TransformerClangTidyCheck {
+public:
+  IntLitCheck(StringRef Name, ClangTidyContext *Context)
+  : TransformerClangTidyCheck(tooling::makeRule(integerLiteral(),
+change(text("LIT")),
+text("no message")),
+  Name, Context) {}
+};
+
+// Tests that two changes in a single macro expansion do not lead to conflicts
+// in applying the changes.
+TEST(TransformerClangTidyCheckTest, TwoChangesInOneMacroExpansion) {
+  const std::string Input = R"cc(
+#define PLUS(a,b) (a) + (b)
+int f() { return PLUS(3, 4); }
+  )cc";
+  const std::string Expected = R"cc(
+#define PLUS(a,b) (a) + (b)
+int f() { return PLUS(LIT, LIT); }
+  )cc";
+
+  EXPECT_EQ(Expected, test::runCheckOnCode(Input));
+}
+
+class BinOpCheck : public TransformerClangTidyCheck {
+public:
+  BinOpCheck(StringRef Name, ClangTidyContext *Context)
+  : TransformerClangTidyCheck(
+tooling::makeRule(
+binaryOperator(hasOperatorName("+"), hasRHS(expr().bind("r"))),
+change(node("r"), text("RIGHT")), text("no message")),
+Name, Context) {}
+};
+
+// Tests case where the rule's match spans both source from the macro and its
+// argument, while the change spans only the argument AND there are two such
+// matches. We verify that both replacements succeed.
+TEST(TransformerClangTidyCheckTest, TwoMatchesInMacroExpansion) {
+  const std::string Input = R"cc(
+#define M(a,b) (1 + a) * (1 + b)
+int f() { return M(3, 4); }
+  )cc";
+  const std::string Expected = R"cc(
+#define M(a,b) (1 + a) * (1 + b)
+int f() { return M(RIGHT, RIGHT); }
+  )cc";
+
+  EXPECT_EQ(Expected, test::runCheckOnCode(Input));
+}
+
 // A trivial rewrite-rule generator that requires Objective-C code.
 Optional needsObjC(const LangOptions &LangOpts,
 const ClangTidyCheck::OptionsView &Options) {
Index: clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
===
--- clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
+++ clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
@@ -71,14 +71,6 @@
   if (Result.Context->getDiagnostics().hasErrorOccurred())
 return;
 
-  // Verify the existence and validity of the AST node that roots this rule.
-  const ast_matchers::BoundNodes::IDToNodeMap &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.");
-
   assert(Rule && "check() should not fire if Rule is None");
   RewriteRule::Case Case = tooling::detail::findSelectedCase(Result, *Rule);
   Expected> Transformations =
@@ -99,10 +91,12 @@
  << llvm::toString(Explanation.takeError()) << "\n";
 return;
   }
-  DiagnosticBuilder Diag = diag(RootLoc, *Explanation);
-  for (const auto &T : *Transformations) {
+
+  // Associate the diagnostic with the location of the first change.
+  DiagnosticBuilder Diag =
+  diag((*Transformations)[0].Range.getBegin(), *Explanation);
+  for (const auto &T : *Transformations)
 Diag << FixItHint::CreateReplacement(T.Range, T.Replacement);
-  }
 
   for (const auto &I : Case.AddedIncludes) {
 auto &Heade

[PATCH] D66676: [clang-tidy] TransformerClangTidyCheck: change choice of location for diagnostic message.

2019-08-26 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked an inline comment as done.
ymandel added inline comments.



Comment at: 
clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp:106
+// argument, while the change spans only the argument AND there are two such
+// matches.  Here, we expect a conflict between the two matches and the second
+// to be ignored.

gribozavr wrote:
> Sorry, I don't quite understand the comment -- the test has two replacements 
> (both arguments to the macro are replaced), but the comment says that we only 
> expect one.
Right, that comment needs to be updated. It's leftover from while the fix 
wasn't done yet...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66676



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


[PATCH] D66735: [clangd] Handling text editor/document lifetimes in vscode extension.

2019-08-26 Thread Johan Vikström via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
jvikstrom marked 4 inline comments as done.
Closed by commit rG1c9aa70b042b: [clangd] Handling text editor/document 
lifetimes in vscode extension. (authored by jvikstrom).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66735

Files:
  clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
  
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts

Index: clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
@@ -107,7 +107,7 @@
 highlighter.highlight('file1', []);
 assert.deepEqual(highlighter.applicationUriHistory, [ 'file1' ]);
 highlighter.initialize(tm);
-assert.deepEqual(highlighter.applicationUriHistory, [ 'file1', 'file1' ]);
+assert.deepEqual(highlighter.applicationUriHistory, [ 'file1', 'file1', 'file2' ]);
 // Groups decorations into the scopes used.
 let highlightingsInLine: semanticHighlighting.SemanticHighlightingLine[] = [
   {
@@ -129,7 +129,7 @@
 
 highlighter.highlight('file1', highlightingsInLine);
 assert.deepEqual(highlighter.applicationUriHistory,
- [ 'file1', 'file1', 'file1' ]);
+ [ 'file1', 'file1', 'file2', 'file1' ]);
 assert.deepEqual(highlighter.getDecorationRanges('file1'),
  createHighlightingScopeRanges(highlightingsInLine));
 // Keeps state separate between files.
@@ -142,18 +142,24 @@
 };
 highlighter.highlight('file2', [ highlightingsInLine1 ]);
 assert.deepEqual(highlighter.applicationUriHistory,
- [ 'file1', 'file1', 'file1', 'file2' ]);
+ [ 'file1', 'file1', 'file2', 'file1', 'file2' ]);
 assert.deepEqual(highlighter.getDecorationRanges('file2'),
  createHighlightingScopeRanges([ highlightingsInLine1 ]));
 // Does full colorizations.
 highlighter.highlight('file1', [ highlightingsInLine1 ]);
 assert.deepEqual(highlighter.applicationUriHistory,
- [ 'file1', 'file1', 'file1', 'file2', 'file1' ]);
+ [ 'file1', 'file1', 'file2', 'file1', 'file2', 'file1' ]);
 // After the incremental update to line 1, the old highlightings at line 1
 // will no longer exist in the array.
 assert.deepEqual(
 highlighter.getDecorationRanges('file1'),
 createHighlightingScopeRanges(
 [ highlightingsInLine1, ...highlightingsInLine.slice(1) ]));
+// Closing a text document removes all highlightings for the file and no
+// other files.
+highlighter.removeFileHighlightings('file1');
+assert.deepEqual(highlighter.getDecorationRanges('file1'), []);
+assert.deepEqual(highlighter.getDecorationRanges('file2'),
+ createHighlightingScopeRanges([ highlightingsInLine1 ]));
   });
 });
Index: clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
@@ -89,6 +89,13 @@
 // highlighter being created.
 this.highlighter = new Highlighter(this.scopeLookupTable);
 this.loadCurrentTheme();
+// Event handling for handling with TextDocuments/Editors lifetimes.
+vscode.window.onDidChangeVisibleTextEditors(
+(editors: vscode.TextEditor[]) =>
+editors.forEach((e) => this.highlighter.applyHighlights(
+e.document.uri.toString(;
+vscode.workspace.onDidCloseTextDocument(
+(doc) => this.highlighter.removeFileHighlightings(doc.uri.toString()));
   }
 
   handleNotification(params: SemanticHighlightingParams) {
@@ -150,12 +157,8 @@
   };
   return vscode.window.createTextEditorDecorationType(options);
 });
-this.getVisibleTextEditorUris().forEach((fileUri) => {
-  // A TextEditor might not be a cpp file. So we must check we have
-  // highlightings for the file before applying them.
-  if (this.files.has(fileUri))
-this.applyHighlights(fileUri);
-})
+this.getVisibleTextEditorUris().forEach((fileUri) =>
+this.applyHighlights(fileUri));
   }
 
   // Adds incremental highlightings to the current highlightings for the file
@@ -171,6 +174,13 @@
 this.applyHighlights(fileUri);
   }
 
+  // Called when a text document is closed. Removes any highlighting entries for
+  // the text document that was closed.
+  public removeFileHighlightin

[PATCH] D66740: [clangd] Add docs for configuration knobs in clangd

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



Comment at: clang-tools-extra/docs/clangd/Configuration.rst:10
+
+Clangd has a bunch of command-line options and LSP capabilities that can change
+its behaviour in certain situations. This page aims to define those

LSP capabilities generally aren't user-servicable and probably shouldn't be 
covered here.



Comment at: clang-tools-extra/docs/clangd/Configuration.rst:12
+its behaviour in certain situations. This page aims to define those
+configuration knobs.
+

Maybe mention that clangd command-line options should be specified in an 
editor-specific way, and point back to the getting started page for details



Comment at: clang-tools-extra/docs/clangd/Configuration.rst:23
+To get over this clangd can query your toolchain driver to extract implicit
+include paths that are unknown to clang. Since this requires executing a 
binary,
+we require users of this feature to whitelist their driver using the

Skip the rationale here IMO - just "Specify your driver as a full path or list 
of globs,..."



Comment at: clang-tools-extra/docs/clangd/Configuration.rst:32
+`/path/to/my-custom-toolchain/arm-none-eabi-g++`; you
+can provide clangd with `--query-driver=**/my-custom-toolchain/arm-none-eabi*`
+to enable execution of any binary that has a name starting with `arm-none-eabi`

this example is insecure - include the whole prefix instead



Comment at: clang-tools-extra/docs/clangd/Configuration.rst:36
+
+By default this flag is empty, which disallows execution of any driver.
+

(I think we can drop this sentence, it seems obvious)



Comment at: clang-tools-extra/docs/clangd/Configuration.rst:41
+
+You can find rest of the flags in `source code 
`__.

I'd point them at clangd --help rather than the code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66740



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


[PATCH] D66743: [clangd] Cleans up the semantic highlighting resources if clangd crashes.

2019-08-26 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom created this revision.
jvikstrom added reviewers: hokein, ilya-biryukov.
Herald added subscribers: cfe-commits, kadircet, arphaman, jkorous, MaskRay.
Herald added a project: clang.

Disposes of the vscode listeners when clangd crashes and reuses the old 
highlighter when it restarts. The reason for reusing the highlighter is because 
this way the highlightings will not disappear as we won't have to dispose of 
them.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66743

Files:
  clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts
  clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
  
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts

Index: clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
@@ -107,7 +107,8 @@
 highlighter.highlight('file1', []);
 assert.deepEqual(highlighter.applicationUriHistory, [ 'file1' ]);
 highlighter.initialize(tm);
-assert.deepEqual(highlighter.applicationUriHistory, [ 'file1', 'file1', 'file2' ]);
+assert.deepEqual(highlighter.applicationUriHistory,
+ [ 'file1', 'file1', 'file2' ]);
 // Groups decorations into the scopes used.
 let highlightingsInLine: semanticHighlighting.SemanticHighlightingLine[] = [
   {
Index: clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
@@ -56,6 +56,8 @@
   scopeLookupTable: string[][];
   // The object that applies the highlightings clangd sends.
   highlighter: Highlighter;
+  // Any disposables that should be cleaned up when clangd crashes.
+  private disposables: vscode.Disposable[] = [];
   fillClientCapabilities(capabilities: vscodelc.ClientCapabilities) {
 // Extend the ClientCapabilities type and add semantic highlighting
 // capability to the object.
@@ -87,15 +89,19 @@
 // Important that highlighter is created before the theme is loading as
 // otherwise it could try to update the themeRuleMatcher without the
 // highlighter being created.
-this.highlighter = new Highlighter(this.scopeLookupTable);
+if (!this.highlighter)
+  // If there already is a highlighter existing there is no need to create a
+  // new one, just reset and keep using it.
+  this.highlighter = new Highlighter(this.scopeLookupTable);
+this.highlighter.clear();
 this.loadCurrentTheme();
 // Event handling for handling with TextDocuments/Editors lifetimes.
-vscode.window.onDidChangeVisibleTextEditors(
+this.disposables.push(vscode.window.onDidChangeVisibleTextEditors(
 (editors: vscode.TextEditor[]) =>
 editors.forEach((e) => this.highlighter.applyHighlights(
-e.document.uri.toString(;
-vscode.workspace.onDidCloseTextDocument(
-(doc) => this.highlighter.removeFileHighlightings(doc.uri.toString()));
+e.document.uri.toString();
+this.disposables.push(vscode.workspace.onDidCloseTextDocument(
+(doc) => this.highlighter.removeFileHighlightings(doc.uri.toString(;
   }
 
   handleNotification(params: SemanticHighlightingParams) {
@@ -103,6 +109,12 @@
 (line) => ({line : line.line, tokens : decodeTokens(line.tokens)}));
 this.highlighter.highlight(params.textDocument.uri, lines);
   }
+  // Disposes of any resources that are not reused if clangd crashes and
+  // restarts.
+  public crashDispose() {
+this.disposables.forEach((d) => d.dispose());
+this.disposables = [];
+  }
 }
 
 // Converts a string of base64 encoded tokens into the corresponding array of
@@ -138,6 +150,7 @@
   constructor(scopeLookupTable: string[][]) {
 this.scopeLookupTable = scopeLookupTable;
   }
+  public clear() { this.files.clear(); }
   // This function must be called at least once or no highlightings will be
   // done. Sets the theme that is used when highlighting. Also triggers a
   // recolorization for all current highlighters. Should be called whenever the
@@ -174,6 +187,27 @@
 this.applyHighlights(fileUri);
   }
 
+  // Applies all the highlightings currently stored for a file with fileUri.
+  public applyHighlights(fileUri: string) {
+if (!this.files.has(fileUri))
+  // There are no highlightings for this file, must return early or will get
+  // out of bounds when applying the decorations below.
+  return;
+if (!this.decorationTypes.length)
+  // Can't apply any decorations when there is no theme loaded.
+ 

Re: [clang-tools-extra] r369763 - [clang-tidy] Possibility of displaying duplicate warnings

2019-08-26 Thread Kristóf Umann via cfe-commits
Apologies for not picking this up, I just recently changed my commit email.
I can see that it was fixed in the meanwhile.

On Sat, 24 Aug 2019 at 01:45, Galina Kistanova via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Hello Kristof,
>
> This commit broke test to few builders:
>
>
> http://lab.llvm.org:8011/builders/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/builds/53703
>
> http://lab.llvm.org:8011/builders/llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast
>
> . . .
> Failing Tests (1):
> Clang Tools :: clang-tidy/duplicate-reports.cpp
>
> Please have a look ASAP?
>
> Thanks
>
> Galina
>
> On Fri, Aug 23, 2019 at 7:56 AM Kristof Umann via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> Author: szelethus
>> Date: Fri Aug 23 07:57:27 2019
>> New Revision: 369763
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=369763&view=rev
>> Log:
>> [clang-tidy] Possibility of displaying duplicate warnings
>>
>> Summary: In case a checker is registered multiple times as an alias, the
>> emitted warnings are uniqued by the report message. However, it is random
>> which checker name is included in the warning. When processing the output
>> of clang-tidy this behavior caused some problems. In this commit the
>> uniquing key contains the checker name too.
>>
>> Reviewers: alexfh, xazax.hun, Szelethus, aaron.ballman, lebedev.ri,
>> JonasToth, gribozavr
>>
>> Reviewed By: alexfh
>>
>> Subscribers: dkrupp, whisperity, rnkovacs, mgrang, cfe-commits
>>
>> Patch by Tibor Brunner!
>>
>> Tags: #clang
>>
>> Differential Revision: https://reviews.llvm.org/D65065
>>
>> Added:
>> clang-tools-extra/trunk/test/clang-tidy/duplicate-reports.cpp
>> Modified:
>> clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp
>>
>> Modified:
>> clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp
>> URL:
>> http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp?rev=369763&r1=369762&r2=369763&view=diff
>>
>> ==
>> --- clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp
>> (original)
>> +++ clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp
>> Fri Aug 23 07:57:27 2019
>> @@ -742,8 +742,9 @@ struct LessClangTidyError {
>>  const tooling::DiagnosticMessage &M1 = LHS.Message;
>>  const tooling::DiagnosticMessage &M2 = RHS.Message;
>>
>> -return std::tie(M1.FilePath, M1.FileOffset, M1.Message) <
>> -   std::tie(M2.FilePath, M2.FileOffset, M2.Message);
>> +return
>> +  std::tie(M1.FilePath, M1.FileOffset, LHS.DiagnosticName,
>> M1.Message) <
>> +  std::tie(M2.FilePath, M2.FileOffset, RHS.DiagnosticName,
>> M2.Message);
>>}
>>  };
>>  struct EqualClangTidyError {
>>
>> Added: clang-tools-extra/trunk/test/clang-tidy/duplicate-reports.cpp
>> URL:
>> http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/duplicate-reports.cpp?rev=369763&view=auto
>>
>> ==
>> --- clang-tools-extra/trunk/test/clang-tidy/duplicate-reports.cpp (added)
>> +++ clang-tools-extra/trunk/test/clang-tidy/duplicate-reports.cpp Fri Aug
>> 23 07:57:27 2019
>> @@ -0,0 +1,15 @@
>> +// RUN: %check_clang_tidy %s cert-err09-cpp,cert-err61-cpp %t
>> +
>> +void alwaysThrows() {
>> +  int ex = 42;
>> +  // CHECK-MESSAGES: warning: throw expression should throw anonymous
>> temporary values instead [cert-err09-cpp]
>> +  // CHECK-MESSAGES: warning: throw expression should throw anonymous
>> temporary values instead [cert-err61-cpp]
>> +  throw ex;
>> +}
>> +
>> +void doTheJob() {
>> +  try {
>> +alwaysThrows();
>> +  } catch (int&) {
>> +  }
>> +}
>>
>>
>> ___
>> cfe-commits mailing list
>> cfe-commits@lists.llvm.org
>> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D66676: [clang-tidy] TransformerClangTidyCheck: change choice of location for diagnostic message.

2019-08-26 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr accepted this revision.
gribozavr added a comment.
This revision is now accepted and ready to land.

I see, it all makes sense now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66676



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


[PATCH] D66740: [clangd] Add docs for configuration knobs in clangd

2019-08-26 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 217154.
kadircet marked 6 inline comments as done.
kadircet added a comment.

- Address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66740

Files:
  clang-tools-extra/docs/clangd/Configuration.rst
  clang-tools-extra/docs/clangd/index.rst


Index: clang-tools-extra/docs/clangd/index.rst
===
--- clang-tools-extra/docs/clangd/index.rst
+++ clang-tools-extra/docs/clangd/index.rst
@@ -7,6 +7,7 @@
 
Installation
Features
+   Configuration
 
 What is clangd?
 ===
Index: clang-tools-extra/docs/clangd/Configuration.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clangd/Configuration.rst
@@ -0,0 +1,39 @@
+
+Configuration
+
+
+.. contents::
+
+.. role:: raw-html(raw)
+   :format: html
+
+Clangd has a bunch of command-line options that can change its behaviour in
+certain situations. This page aims to define those configuration knobs.
+
+Those command line arguments needs to be specified in an editor-specific way.
+You can find some editor specific instructions in `here 
`__.
+
+--query-driver
+==
+
+Clangd makes use of clang behind the scenes, so it might fail to detect your
+standard library or built-in headers if your project is making use of a custom
+toolchain. That is quite common in hardware-related projects, especially for 
the
+ones making use of gcc (e.g. ARM's `arm-none-eabi-gcc`).
+
+You can specify your driver as a list of globs or full paths, then clangd will
+execute drivers and fetch necessary include paths to compile your code.
+
+For example if you have your compilers at:
+ - `/path/to/my-custom/toolchain1/arm-none-eabi-gcc`,
+ - `/path/to/my-custom/toolchain2/arm-none-eabi-g++`,
+ - `/path/to/my-custom2/toolchain/arm-none-eabi-g++`,
+you can provide clangd with
+`--query-driver=/path/to/my-custom/**/arm-none-eabi*` to enable execution of
+any binary that has a name starting with `arm-none-eabi` and under
+`/path/to/my-custom/`. This won't allow execution of the last compiler.
+
+Full list of flags
+==
+
+You can find out about the rest of the flags using `clangd --help`.


Index: clang-tools-extra/docs/clangd/index.rst
===
--- clang-tools-extra/docs/clangd/index.rst
+++ clang-tools-extra/docs/clangd/index.rst
@@ -7,6 +7,7 @@
 
Installation
Features
+   Configuration
 
 What is clangd?
 ===
Index: clang-tools-extra/docs/clangd/Configuration.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clangd/Configuration.rst
@@ -0,0 +1,39 @@
+
+Configuration
+
+
+.. contents::
+
+.. role:: raw-html(raw)
+   :format: html
+
+Clangd has a bunch of command-line options that can change its behaviour in
+certain situations. This page aims to define those configuration knobs.
+
+Those command line arguments needs to be specified in an editor-specific way.
+You can find some editor specific instructions in `here `__.
+
+--query-driver
+==
+
+Clangd makes use of clang behind the scenes, so it might fail to detect your
+standard library or built-in headers if your project is making use of a custom
+toolchain. That is quite common in hardware-related projects, especially for the
+ones making use of gcc (e.g. ARM's `arm-none-eabi-gcc`).
+
+You can specify your driver as a list of globs or full paths, then clangd will
+execute drivers and fetch necessary include paths to compile your code.
+
+For example if you have your compilers at:
+ - `/path/to/my-custom/toolchain1/arm-none-eabi-gcc`,
+ - `/path/to/my-custom/toolchain2/arm-none-eabi-g++`,
+ - `/path/to/my-custom2/toolchain/arm-none-eabi-g++`,
+you can provide clangd with
+`--query-driver=/path/to/my-custom/**/arm-none-eabi*` to enable execution of
+any binary that has a name starting with `arm-none-eabi` and under
+`/path/to/my-custom/`. This won't allow execution of the last compiler.
+
+Full list of flags
+==
+
+You can find out about the rest of the flags using `clangd --help`.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D66738: [clangd] Added highlighting for structured bindings.

2019-08-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:236
+  // binding if one exist.
+  if (const auto *BB = B->getBinding())
+if (const auto *RD = BB->getReferencedDeclOfCallee())

nit: could you spell out the type? it is not straight forward to infer from the 
method name.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:238
+if (const auto *RD = BB->getReferencedDeclOfCallee())
+  if (const auto *D = dyn_cast(RD)) {
+addToken(Loc, D);

nit: we can group the above two ifs into one, like `if (const auto* D = 
dyn_cast_or_null<...>(...getReferencedDecl)`.



Comment at: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp:437
+  struct $Class[[S]] {
+$Primitive[[float]] $Field[[Member]];
+  };

can we add a non-primitive field and test it? 



Comment at: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp:442
+$Primitive[[int]] $Variable[[A]][2] = {1,2};
+auto [$Variable[[B1]], $Variable[[B2]]] = $Variable[[A]];
+auto& [$Variable[[R1]], $Variable[[R2]]] = $Variable[[A]];

From the code, I can't tell the `Variable` for the binding decl is from the 
underlying namedDecl or the fallback, could you add a comment clarifying it?



Comment at: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp:447
+$Field[[M1]] += 12.2;
+$Variable[[B1]] += 2;
+$Class[[S]] $Variable[[SArr]][2] = {$Class[[S]](), $Class[[S]]()};

The above 4 lines seems not relevant to this patch, I think?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66738



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


[PATCH] D61879: WIP: Prototype of DSE optimizations for -ftrivial-auto-var-init

2019-08-26 Thread Alexander Potapenko via Phabricator via cfe-commits
glider added a comment.

In D61879#1621423 , @vitalybuka wrote:

> Fix https://godbolt.org/z/-PinQP


Please consider adding a test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D61879



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


[clang-tools-extra] r369914 - [clang-tidy] TransformerClangTidyCheck: change choice of location for diagnostic message.

2019-08-26 Thread Yitzhak Mandelbaum via cfe-commits
Author: ymandel
Date: Mon Aug 26 08:17:29 2019
New Revision: 369914

URL: http://llvm.org/viewvc/llvm-project?rev=369914&view=rev
Log:
[clang-tidy] TransformerClangTidyCheck: change choice of location for 
diagnostic message.

Summary:
This patch changes the location specified to the
`ClangTidyCheck::diag()`. Currently, the beginning of the matched range is
used. This patch uses the beginning of the first fix's range.  This change both
simplifies the code and (hopefully) gives a more intuitive result: the reported
location aligns with the fix(es) provided, rather than the (arbitrary) range of
the rule's match.

N.B. this patch will break the line offset numbers in lit tests if the first fix
is not at the beginning of the match.

Reviewers: gribozavr

Subscribers: xazax.hun, cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clang-tidy/utils/TransformerClangTidyCheck.cpp

clang-tools-extra/trunk/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp

Modified: clang-tools-extra/trunk/clang-tidy/utils/TransformerClangTidyCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/utils/TransformerClangTidyCheck.cpp?rev=369914&r1=369913&r2=369914&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/utils/TransformerClangTidyCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/utils/TransformerClangTidyCheck.cpp Mon 
Aug 26 08:17:29 2019
@@ -71,14 +71,6 @@ void TransformerClangTidyCheck::check(
   if (Result.Context->getDiagnostics().hasErrorOccurred())
 return;
 
-  // Verify the existence and validity of the AST node that roots this rule.
-  const ast_matchers::BoundNodes::IDToNodeMap &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.");
-
   assert(Rule && "check() should not fire if Rule is None");
   RewriteRule::Case Case = tooling::detail::findSelectedCase(Result, *Rule);
   Expected> Transformations =
@@ -99,10 +91,12 @@ void TransformerClangTidyCheck::check(
  << llvm::toString(Explanation.takeError()) << "\n";
 return;
   }
-  DiagnosticBuilder Diag = diag(RootLoc, *Explanation);
-  for (const auto &T : *Transformations) {
+
+  // Associate the diagnostic with the location of the first change.
+  DiagnosticBuilder Diag =
+  diag((*Transformations)[0].Range.getBegin(), *Explanation);
+  for (const auto &T : *Transformations)
 Diag << FixItHint::CreateReplacement(T.Range, T.Replacement);
-  }
 
   for (const auto &I : Case.AddedIncludes) {
 auto &Header = I.first;

Modified: 
clang-tools-extra/trunk/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp?rev=369914&r1=369913&r2=369914&view=diff
==
--- 
clang-tools-extra/trunk/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp 
(original)
+++ 
clang-tools-extra/trunk/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp 
Mon Aug 26 08:17:29 2019
@@ -18,18 +18,18 @@ namespace clang {
 namespace tidy {
 namespace utils {
 namespace {
+using namespace ::clang::ast_matchers;
+
 using tooling::change;
 using tooling::IncludeFormat;
+using tooling::node;
 using tooling::RewriteRule;
+using tooling::statement;
 using tooling::text;
 using tooling::stencil::cat;
 
 // Invert the code of an if-statement, while maintaining its semantics.
 RewriteRule invertIf() {
-  using namespace ::clang::ast_matchers;
-  using tooling::node;
-  using tooling::statement;
-
   StringRef C = "C", T = "T", E = "E";
   RewriteRule Rule = tooling::makeRule(
   ifStmt(hasCondition(expr().bind(C)), hasThen(stmt().bind(T)),
@@ -67,6 +67,56 @@ TEST(TransformerClangTidyCheckTest, Basi
   EXPECT_EQ(Expected, test::runCheckOnCode(Input));
 }
 
+class IntLitCheck : public TransformerClangTidyCheck {
+public:
+  IntLitCheck(StringRef Name, ClangTidyContext *Context)
+  : TransformerClangTidyCheck(tooling::makeRule(integerLiteral(),
+change(text("LIT")),
+text("no message")),
+  Name, Context) {}
+};
+
+// Tests that two changes in a single macro expansion do not lead to conflicts
+// in applying the changes.
+TEST(TransformerClangTidyCheckTest, TwoChangesInOneMacroExpansion) {
+  const std::string Input = R"cc(
+#define PLUS(a,b) (a) + (b)
+int f() { return PLUS(3, 4); }
+  )cc";
+  const std::string Expected = R"cc(
+#define PLUS

[PATCH] D66676: [clang-tidy] TransformerClangTidyCheck: change choice of location for diagnostic message.

2019-08-26 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL369914: [clang-tidy] TransformerClangTidyCheck: change 
choice of location for… (authored by ymandel, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D66676?vs=217146&id=217161#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D66676

Files:
  clang-tools-extra/trunk/clang-tidy/utils/TransformerClangTidyCheck.cpp
  clang-tools-extra/trunk/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp

Index: clang-tools-extra/trunk/clang-tidy/utils/TransformerClangTidyCheck.cpp
===
--- clang-tools-extra/trunk/clang-tidy/utils/TransformerClangTidyCheck.cpp
+++ clang-tools-extra/trunk/clang-tidy/utils/TransformerClangTidyCheck.cpp
@@ -71,14 +71,6 @@
   if (Result.Context->getDiagnostics().hasErrorOccurred())
 return;
 
-  // Verify the existence and validity of the AST node that roots this rule.
-  const ast_matchers::BoundNodes::IDToNodeMap &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.");
-
   assert(Rule && "check() should not fire if Rule is None");
   RewriteRule::Case Case = tooling::detail::findSelectedCase(Result, *Rule);
   Expected> Transformations =
@@ -99,10 +91,12 @@
  << llvm::toString(Explanation.takeError()) << "\n";
 return;
   }
-  DiagnosticBuilder Diag = diag(RootLoc, *Explanation);
-  for (const auto &T : *Transformations) {
+
+  // Associate the diagnostic with the location of the first change.
+  DiagnosticBuilder Diag =
+  diag((*Transformations)[0].Range.getBegin(), *Explanation);
+  for (const auto &T : *Transformations)
 Diag << FixItHint::CreateReplacement(T.Range, T.Replacement);
-  }
 
   for (const auto &I : Case.AddedIncludes) {
 auto &Header = I.first;
Index: clang-tools-extra/trunk/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
===
--- clang-tools-extra/trunk/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
+++ clang-tools-extra/trunk/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
@@ -18,18 +18,18 @@
 namespace tidy {
 namespace utils {
 namespace {
+using namespace ::clang::ast_matchers;
+
 using tooling::change;
 using tooling::IncludeFormat;
+using tooling::node;
 using tooling::RewriteRule;
+using tooling::statement;
 using tooling::text;
 using tooling::stencil::cat;
 
 // Invert the code of an if-statement, while maintaining its semantics.
 RewriteRule invertIf() {
-  using namespace ::clang::ast_matchers;
-  using tooling::node;
-  using tooling::statement;
-
   StringRef C = "C", T = "T", E = "E";
   RewriteRule Rule = tooling::makeRule(
   ifStmt(hasCondition(expr().bind(C)), hasThen(stmt().bind(T)),
@@ -67,6 +67,56 @@
   EXPECT_EQ(Expected, test::runCheckOnCode(Input));
 }
 
+class IntLitCheck : public TransformerClangTidyCheck {
+public:
+  IntLitCheck(StringRef Name, ClangTidyContext *Context)
+  : TransformerClangTidyCheck(tooling::makeRule(integerLiteral(),
+change(text("LIT")),
+text("no message")),
+  Name, Context) {}
+};
+
+// Tests that two changes in a single macro expansion do not lead to conflicts
+// in applying the changes.
+TEST(TransformerClangTidyCheckTest, TwoChangesInOneMacroExpansion) {
+  const std::string Input = R"cc(
+#define PLUS(a,b) (a) + (b)
+int f() { return PLUS(3, 4); }
+  )cc";
+  const std::string Expected = R"cc(
+#define PLUS(a,b) (a) + (b)
+int f() { return PLUS(LIT, LIT); }
+  )cc";
+
+  EXPECT_EQ(Expected, test::runCheckOnCode(Input));
+}
+
+class BinOpCheck : public TransformerClangTidyCheck {
+public:
+  BinOpCheck(StringRef Name, ClangTidyContext *Context)
+  : TransformerClangTidyCheck(
+tooling::makeRule(
+binaryOperator(hasOperatorName("+"), hasRHS(expr().bind("r"))),
+change(node("r"), text("RIGHT")), text("no message")),
+Name, Context) {}
+};
+
+// Tests case where the rule's match spans both source from the macro and its
+// argument, while the change spans only the argument AND there are two such
+// matches. We verify that both replacements succeed.
+TEST(TransformerClangTidyCheckTest, TwoMatchesInMacroExpansion) {
+  const std::string Input = R"cc(
+#define M(a,b) (1 + a) * (1 + b)
+int f() { return M(3, 4); }
+  )cc";
+  const std::string Expected = R"cc(
+#define M(a,b) (1

[clang-tools-extra] r369915 - [clang-tidy][NFC] Qualify `makeRule` call in test, for consistency with other calls.

2019-08-26 Thread Yitzhak Mandelbaum via cfe-commits
Author: ymandel
Date: Mon Aug 26 08:27:05 2019
New Revision: 369915

URL: http://llvm.org/viewvc/llvm-project?rev=369915&view=rev
Log:
[clang-tidy][NFC] Qualify `makeRule` call in test, for consistency with other 
calls.

One call `makeRule` is unqualified (and unintentionally relying on ADL to
resolve correctly). This revision qualifies that call for consistency and to
drop use of ADL.

Modified:

clang-tools-extra/trunk/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp

Modified: 
clang-tools-extra/trunk/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp?rev=369915&r1=369914&r2=369915&view=diff
==
--- 
clang-tools-extra/trunk/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp 
(original)
+++ 
clang-tools-extra/trunk/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp 
Mon Aug 26 08:27:05 2019
@@ -174,8 +174,9 @@ TEST(TransformerClangTidyCheckTest, Disa
 
 RewriteRule replaceCall(IncludeFormat Format) {
   using namespace ::clang::ast_matchers;
-  RewriteRule Rule = makeRule(callExpr(callee(functionDecl(hasName("f",
-  change(text("other()")), text("no message"));
+  RewriteRule Rule =
+  tooling::makeRule(callExpr(callee(functionDecl(hasName("f",
+change(text("other()")), text("no message"));
   addInclude(Rule, "clang/OtherLib.h", Format);
   return Rule;
 }


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


[PATCH] D66673: [OPENMP][NVPTX]Fix critical region codegen.

2019-08-26 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert accepted this revision.
jdoerfert added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rC Clang

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

https://reviews.llvm.org/D66673



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


[PATCH] D66733: [analyzer] Add a checker option to detect nested dead stores

2019-08-26 Thread Balázs Benics via Phabricator via cfe-commits
steakhal marked 3 inline comments as done.
steakhal added a comment.

Thank you for your response @Szelethus.
Fixed, updating the patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66733



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


[PATCH] D66733: [analyzer] Add a checker option to detect nested dead stores

2019-08-26 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 217162.
steakhal added a comment.

Reformatted using `clang-format-diff.py`.
Minor fixes which were requested by @Szelethus.


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

https://reviews.llvm.org/D66733

Files:
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/dead-stores.c
  clang/test/Analysis/dead-stores.cpp

Index: clang/test/Analysis/dead-stores.cpp
===
--- clang/test/Analysis/dead-stores.cpp
+++ clang/test/Analysis/dead-stores.cpp
@@ -1,11 +1,13 @@
 // RUN: %clang_analyze_cc1 -fcxx-exceptions -fexceptions -fblocks -std=c++11 -analyzer-checker=deadcode.DeadStores -verify -Wno-unreachable-code %s
 // RUN: %clang_analyze_cc1 -fcxx-exceptions -fexceptions -fblocks -std=c++11 -analyzer-store=region -analyzer-checker=deadcode.DeadStores -verify -Wno-unreachable-code %s
+// RUN: %clang_analyze_cc1 -fcxx-exceptions -fexceptions -fblocks -std=c++11 -analyzer-checker=deadcode.DeadStores -analyzer-config deadcode.DeadStores:WarnForDeadNestedAssignments=true -verify -Wno-unreachable-code -DWARN_FOR_DEAD_NESTED %s
 
 //===--===//
 // Basic dead store checking (but in C++ mode).
 //===--===//
 
 int j;
+int make_int();
 void test1() {
   int x = 4;
 
@@ -17,6 +19,15 @@
 (void)x;
 break;
   }
+
+  int y;
+  (void)y;
+#ifdef WARN_FOR_DEAD_NESTED
+  if ((y = make_int())) // expected-warning{{Although the value stored}}
+#else
+  if ((y = make_int())) // no-warning
+#endif
+return;
 }
 
 //===--===//
Index: clang/test/Analysis/dead-stores.c
===
--- clang/test/Analysis/dead-stores.c
+++ clang/test/Analysis/dead-stores.c
@@ -1,5 +1,6 @@
 // RUN: %clang_analyze_cc1 -Wunused-variable -analyzer-checker=core,deadcode.DeadStores -fblocks -verify -Wno-unreachable-code -analyzer-opt-analyze-nested-blocks %s
 // RUN: %clang_analyze_cc1 -Wunused-variable -analyzer-checker=core,deadcode.DeadStores -analyzer-store=region -fblocks -verify -Wno-unreachable-code -analyzer-opt-analyze-nested-blocks %s
+// RUN: %clang_analyze_cc1 -Wunused-variable -analyzer-checker=core,deadcode.DeadStores -analyzer-config deadcode.DeadStores:WarnForDeadNestedAssignments=true -fblocks -verify -Wno-unreachable-code -analyzer-opt-analyze-nested-blocks -DWARN_FOR_DEAD_NESTED %s
 
 void f1() {
   int k, y; // expected-warning{{unused variable 'k'}} expected-warning{{unused variable 'y'}}
@@ -77,7 +78,11 @@
 // to see a real bug in this scenario.
 int f8(int *p) {
   extern int *baz();
+#ifdef WARN_FOR_DEAD_NESTED
+  if ((p = baz())) // expected-warning{{Although the value stored}}
+#else
   if ((p = baz())) // no-warning
+#endif
 return 1;
   return 0;
 }
@@ -152,8 +157,11 @@
 // to see a real bug in this scenario.
 int f16(int x) {
   x = x * 2;
-  x = sizeof(int [x = (x || x + 1) * 2])
-  ? 5 : 8;
+#ifdef WARN_FOR_DEAD_NESTED
+  x = sizeof(int[x = (x || x + 1) * 2]) ? 5 : 8; // expected-warning{{Although the value stored}}
+#else
+  x = sizeof(int[x = (x || x + 1) * 2]) ? 5 : 8; // no-warning
+#endif
   return x;
 }
 
@@ -182,7 +190,11 @@
 
 int f18_a() {
int x = 0; // no-warning
+#ifdef WARN_FOR_DEAD_NESTED
+   return (x = 10); // expected-warning{{Although the value stored}}
+#else
return (x = 10); // no-warning
+#endif
 }
 
 void f18_b() {
@@ -535,7 +547,11 @@
 
 int rdar11185138_bar() {
   int y;
+#ifdef WARN_FOR_DEAD_NESTED
+  int x = y = 0; // expected-warning{{Although the value stored}}
+#else
   int x = y = 0; // no-warning
+#endif
   x = 2;
   y = 2;
   return x + y;
@@ -557,8 +573,14 @@
   x3 = (getInt(), getInt(), 0); // expected-warning{{Value stored to 'x3' is never read}}
   int x4 = (getInt(), (getInt(), 0)); // expected-warning{{unused variable 'x4'}}
   int y;
+
+#ifdef WARN_FOR_DEAD_NESTED
+  int x5 = (getInt(), (y = 0));// expected-warning{{unused variable 'x5'}} // expected-warning{{Although the value stored}}
+  int x6 = (getInt(), (y = getInt())); //expected-warning {{Value stored to 'x6' during its initialization is never read}} // expected-warning{{unused variable 'x6'}} // expected-warning{{Although the value stored}}
+#else
   int x5 = (getInt(), (y = 0)); // expected-warning{{unused variable 'x5'}}
   int x6 = (getInt(), (y = getInt())); //expected-warning {{Value stored to 'x6' during its initialization is never read}} // expected-warning{{unused variable 'x6'}}
+#endif
   int x7 = 0, x8 = getInt(); //expected-warning {{Value stored to 'x8' during its initialization is never read}} // expected-warning{{unused variable 'x8'}} // expected-warning{

r369916 - clang-format: [JS] handle `as const`.

2019-08-26 Thread Martin Probst via cfe-commits
Author: mprobst
Date: Mon Aug 26 08:37:05 2019
New Revision: 369916

URL: http://llvm.org/viewvc/llvm-project?rev=369916&view=rev
Log:
clang-format: [JS] handle `as const`.

Summary:
TypeScript 3.4 supports casting into a const type using `as const`:

const x = {x: 1} as const;

Previously, clang-format would insert a space after the `const`. With
this patch, no space is inserted after the sequence `as const`.

Reviewers: krasimir

Subscribers: cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestJS.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=369916&r1=369915&r2=369916&view=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Mon Aug 26 08:37:05 2019
@@ -2746,6 +2746,10 @@ bool TokenAnnotator::spaceRequiredBefore
tok::kw_void))
 return true;
 }
+// `foo as const;` casts into a const type.
+if (Left.endsSequence(tok::kw_const, Keywords.kw_as)) {
+  return false;
+}
 if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
   tok::kw_const) ||
  // "of" is only a keyword if it appears after another identifier

Modified: cfe/trunk/unittests/Format/FormatTestJS.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestJS.cpp?rev=369916&r1=369915&r2=369916&view=diff
==
--- cfe/trunk/unittests/Format/FormatTestJS.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestJS.cpp Mon Aug 26 08:37:05 2019
@@ -1479,6 +1479,9 @@ TEST_F(FormatTestJS, TypeAnnotations) {
   ".someFunction(aa);");
   verifyFormat("const xIsALongIdent:\n""YJustBarelyFitsLinex[];",
   getGoogleJSStyleWithColumns(20));
+  verifyFormat("const x = {\n"
+   "  y: 1\n"
+   "} as const;");
 }
 
 TEST_F(FormatTestJS, UnionIntersectionTypes) {


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


[PATCH] D66747: Moved GlobList into a separate header file

2019-08-26 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr created this revision.
Herald added subscribers: cfe-commits, mgorny.
Herald added a project: clang.

It is a separate abstraction that is used in more contexts than just
a helper for ClangTidyDiagnosticConsumer.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66747

Files:
  clang-tools-extra/clang-tidy/CMakeLists.txt
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
  clang-tools-extra/clang-tidy/GlobList.cpp
  clang-tools-extra/clang-tidy/GlobList.h
  clang-tools-extra/clang-tidy/fuchsia/RestrictSystemIncludesCheck.h
  clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
  clang-tools-extra/unittests/clang-tidy/CMakeLists.txt
  clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp
  clang-tools-extra/unittests/clang-tidy/GlobListTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/GlobListTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/GlobListTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/GlobListTest.cpp
@@ -1,33 +1,8 @@
-#include "ClangTidy.h"
-#include "ClangTidyTest.h"
+#include "GlobList.h"
 #include "gtest/gtest.h"
 
 namespace clang {
 namespace tidy {
-namespace test {
-
-class TestCheck : public ClangTidyCheck {
-public:
-  TestCheck(StringRef Name, ClangTidyContext *Context)
-  : ClangTidyCheck(Name, Context) {}
-  void registerMatchers(ast_matchers::MatchFinder *Finder) override {
-Finder->addMatcher(ast_matchers::varDecl().bind("var"), this);
-  }
-  void check(const ast_matchers::MatchFinder::MatchResult &Result) override {
-const auto *Var = Result.Nodes.getNodeAs("var");
-// Add diagnostics in the wrong order.
-diag(Var->getLocation(), "variable");
-diag(Var->getTypeSpecStartLoc(), "type specifier");
-  }
-};
-
-TEST(ClangTidyDiagnosticConsumer, SortsErrors) {
-  std::vector Errors;
-  runCheckOnCode("int a;", &Errors);
-  EXPECT_EQ(2ul, Errors.size());
-  EXPECT_EQ("type specifier", Errors[0].Message.Message);
-  EXPECT_EQ("variable", Errors[1].Message.Message);
-}
 
 TEST(GlobList, Empty) {
   GlobList Filter("");
@@ -89,6 +64,5 @@
   EXPECT_TRUE(Filter.contains("asdfqwEasdf"));
 }
 
-} // namespace test
 } // namespace tidy
 } // namespace clang
Index: clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp
@@ -29,66 +29,6 @@
   EXPECT_EQ("variable", Errors[1].Message.Message);
 }
 
-TEST(GlobList, Empty) {
-  GlobList Filter("");
-
-  EXPECT_TRUE(Filter.contains(""));
-  EXPECT_FALSE(Filter.contains("aaa"));
-}
-
-TEST(GlobList, Nothing) {
-  GlobList Filter("-*");
-
-  EXPECT_FALSE(Filter.contains(""));
-  EXPECT_FALSE(Filter.contains("a"));
-  EXPECT_FALSE(Filter.contains("-*"));
-  EXPECT_FALSE(Filter.contains("-"));
-  EXPECT_FALSE(Filter.contains("*"));
-}
-
-TEST(GlobList, Everything) {
-  GlobList Filter("*");
-
-  EXPECT_TRUE(Filter.contains(""));
-  EXPECT_TRUE(Filter.contains(""));
-  EXPECT_TRUE(Filter.contains("-*"));
-  EXPECT_TRUE(Filter.contains("-"));
-  EXPECT_TRUE(Filter.contains("*"));
-}
-
-TEST(GlobList, Simple) {
-  GlobList Filter("aaa");
-
-  EXPECT_TRUE(Filter.contains("aaa"));
-  EXPECT_FALSE(Filter.contains(""));
-  EXPECT_FALSE(Filter.contains("aa"));
-  EXPECT_FALSE(Filter.contains(""));
-  EXPECT_FALSE(Filter.contains("bbb"));
-}
-
-TEST(GlobList, WhitespacesAtBegin) {
-  GlobList Filter("-*,   a.b.*");
-
-  EXPECT_TRUE(Filter.contains("a.b.c"));
-  EXPECT_FALSE(Filter.contains("b.c"));
-}
-
-TEST(GlobList, Complex) {
-  GlobList Filter("*,-a.*, -b.*, \r  \n  a.1.* ,-a.1.A.*,-..,-...,-..+,-*$, -*qwe* ");
-
-  EXPECT_TRUE(Filter.contains("aaa"));
-  EXPECT_TRUE(Filter.contains("qqq"));
-  EXPECT_FALSE(Filter.contains("a."));
-  EXPECT_FALSE(Filter.contains("a.b"));
-  EXPECT_FALSE(Filter.contains("b."));
-  EXPECT_FALSE(Filter.contains("b.b"));
-  EXPECT_TRUE(Filter.contains("a.1.b"));
-  EXPECT_FALSE(Filter.contains("a.1.A.a"));
-  EXPECT_FALSE(Filter.contains("qwe"));
-  EXPECT_FALSE(Filter.contains("asdfqweasdf"));
-  EXPECT_TRUE(Filter.contains("asdfqwEasdf"));
-}
-
 } // namespace test
 } // namespace tidy
 } // namespace clang
Index: clang-tools-extra/unittests/clang-tidy/CMakeLists.txt
===
--- clang-tools-extra/unittests/clang-tidy/CMakeLists.txt
+++ clang-tools-extra/unittests/clang-tidy/CMakeLists.txt
@@ -10,6 +10,7 @@
   ClangTidyDiagnosticConsumerTest.cpp
   ClangTidyOptionsTest.cpp
   IncludeInserterTest.cpp
+  GlobListTest.cpp
   GoogleModuleTest.cpp
   LLVMModuleTest.cpp
   NamespaceAliaserTest.cpp
Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp

[PATCH] D66747: Moved GlobList into a separate header file

2019-08-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov accepted this revision.
ilya-biryukov added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66747



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


[PATCH] D66736: clang-format: [JS] handle `as const`.

2019-08-26 Thread Martin Probst via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5836472ac488: clang-format: [JS] handle `as const`. 
(authored by mprobst).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66736

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTestJS.cpp


Index: clang/unittests/Format/FormatTestJS.cpp
===
--- clang/unittests/Format/FormatTestJS.cpp
+++ clang/unittests/Format/FormatTestJS.cpp
@@ -1479,6 +1479,9 @@
   ".someFunction(aa);");
   verifyFormat("const xIsALongIdent:\n""YJustBarelyFitsLinex[];",
   getGoogleJSStyleWithColumns(20));
+  verifyFormat("const x = {\n"
+   "  y: 1\n"
+   "} as const;");
 }
 
 TEST_F(FormatTestJS, UnionIntersectionTypes) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2746,6 +2746,10 @@
tok::kw_void))
 return true;
 }
+// `foo as const;` casts into a const type.
+if (Left.endsSequence(tok::kw_const, Keywords.kw_as)) {
+  return false;
+}
 if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
   tok::kw_const) ||
  // "of" is only a keyword if it appears after another identifier


Index: clang/unittests/Format/FormatTestJS.cpp
===
--- clang/unittests/Format/FormatTestJS.cpp
+++ clang/unittests/Format/FormatTestJS.cpp
@@ -1479,6 +1479,9 @@
   ".someFunction(aa);");
   verifyFormat("const xIsALongIdent:\n""YJustBarelyFitsLinex[];",
   getGoogleJSStyleWithColumns(20));
+  verifyFormat("const x = {\n"
+   "  y: 1\n"
+   "} as const;");
 }
 
 TEST_F(FormatTestJS, UnionIntersectionTypes) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2746,6 +2746,10 @@
tok::kw_void))
 return true;
 }
+// `foo as const;` casts into a const type.
+if (Left.endsSequence(tok::kw_const, Keywords.kw_as)) {
+  return false;
+}
 if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
   tok::kw_const) ||
  // "of" is only a keyword if it appears after another identifier
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D66733: [analyzer] Add a checker option to detect nested dead stores

2019-08-26 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 217164.
steakhal added a comment.

Fix copy-paste mistake.
This time upload the correct version.


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

https://reviews.llvm.org/D66733

Files:
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/dead-stores.c
  clang/test/Analysis/dead-stores.cpp

Index: clang/test/Analysis/dead-stores.cpp
===
--- clang/test/Analysis/dead-stores.cpp
+++ clang/test/Analysis/dead-stores.cpp
@@ -1,11 +1,13 @@
 // RUN: %clang_analyze_cc1 -fcxx-exceptions -fexceptions -fblocks -std=c++11 -analyzer-checker=deadcode.DeadStores -verify -Wno-unreachable-code %s
 // RUN: %clang_analyze_cc1 -fcxx-exceptions -fexceptions -fblocks -std=c++11 -analyzer-store=region -analyzer-checker=deadcode.DeadStores -verify -Wno-unreachable-code %s
+// RUN: %clang_analyze_cc1 -fcxx-exceptions -fexceptions -fblocks -std=c++11 -analyzer-checker=deadcode.DeadStores -analyzer-config deadcode.DeadStores:WarnForDeadNestedAssignments=true -verify -Wno-unreachable-code -DWARN_FOR_DEAD_NESTED %s
 
 //===--===//
 // Basic dead store checking (but in C++ mode).
 //===--===//
 
 int j;
+int make_int();
 void test1() {
   int x = 4;
 
@@ -17,6 +19,15 @@
 (void)x;
 break;
   }
+
+  int y;
+  (void)y;
+#ifdef WARN_FOR_DEAD_NESTED
+  if ((y = make_int())) // expected-warning{{Although the value stored}}
+#else
+  if ((y = make_int())) // no-warning
+#endif
+return;
 }
 
 //===--===//
Index: clang/test/Analysis/dead-stores.c
===
--- clang/test/Analysis/dead-stores.c
+++ clang/test/Analysis/dead-stores.c
@@ -1,5 +1,6 @@
 // RUN: %clang_analyze_cc1 -Wunused-variable -analyzer-checker=core,deadcode.DeadStores -fblocks -verify -Wno-unreachable-code -analyzer-opt-analyze-nested-blocks %s
 // RUN: %clang_analyze_cc1 -Wunused-variable -analyzer-checker=core,deadcode.DeadStores -analyzer-store=region -fblocks -verify -Wno-unreachable-code -analyzer-opt-analyze-nested-blocks %s
+// RUN: %clang_analyze_cc1 -Wunused-variable -analyzer-checker=core,deadcode.DeadStores -analyzer-config deadcode.DeadStores:WarnForDeadNestedAssignments=true -fblocks -verify -Wno-unreachable-code -analyzer-opt-analyze-nested-blocks -DWARN_FOR_DEAD_NESTED %s
 
 void f1() {
   int k, y; // expected-warning{{unused variable 'k'}} expected-warning{{unused variable 'y'}}
@@ -77,7 +78,11 @@
 // to see a real bug in this scenario.
 int f8(int *p) {
   extern int *baz();
+#ifdef WARN_FOR_DEAD_NESTED
+  if ((p = baz())) // expected-warning{{Although the value stored}}
+#else
   if ((p = baz())) // no-warning
+#endif
 return 1;
   return 0;
 }
@@ -152,8 +157,11 @@
 // to see a real bug in this scenario.
 int f16(int x) {
   x = x * 2;
-  x = sizeof(int [x = (x || x + 1) * 2])
-  ? 5 : 8;
+#ifdef WARN_FOR_DEAD_NESTED
+  x = sizeof(int[x = (x || x + 1) * 2]) ? 5 : 8; // expected-warning{{Although the value stored}}
+#else
+  x = sizeof(int[x = (x || x + 1) * 2]) ? 5 : 8; // no-warning
+#endif
   return x;
 }
 
@@ -182,7 +190,11 @@
 
 int f18_a() {
int x = 0; // no-warning
+#ifdef WARN_FOR_DEAD_NESTED
+   return (x = 10); // expected-warning{{Although the value stored}}
+#else
return (x = 10); // no-warning
+#endif
 }
 
 void f18_b() {
@@ -535,7 +547,11 @@
 
 int rdar11185138_bar() {
   int y;
+#ifdef WARN_FOR_DEAD_NESTED
+  int x = y = 0; // expected-warning{{Although the value stored}}
+#else
   int x = y = 0; // no-warning
+#endif
   x = 2;
   y = 2;
   return x + y;
@@ -557,8 +573,14 @@
   x3 = (getInt(), getInt(), 0); // expected-warning{{Value stored to 'x3' is never read}}
   int x4 = (getInt(), (getInt(), 0)); // expected-warning{{unused variable 'x4'}}
   int y;
+
+#ifdef WARN_FOR_DEAD_NESTED
+  int x5 = (getInt(), (y = 0));// expected-warning{{unused variable 'x5'}} // expected-warning{{Although the value stored}}
+  int x6 = (getInt(), (y = getInt())); //expected-warning {{Value stored to 'x6' during its initialization is never read}} // expected-warning{{unused variable 'x6'}} // expected-warning{{Although the value stored}}
+#else
   int x5 = (getInt(), (y = 0)); // expected-warning{{unused variable 'x5'}}
   int x6 = (getInt(), (y = getInt())); //expected-warning {{Value stored to 'x6' during its initialization is never read}} // expected-warning{{unused variable 'x6'}}
+#endif
   int x7 = 0, x8 = getInt(); //expected-warning {{Value stored to 'x8' during its initialization is never read}} // expected-warning{{unused variable 'x8'}} // expected-warning{{unused variable 'x7'}}
   i

[clang-tools-extra] r369917 - [clangd] Add docs for configuration knobs in clangd

2019-08-26 Thread Kadir Cetinkaya via cfe-commits
Author: kadircet
Date: Mon Aug 26 08:42:16 2019
New Revision: 369917

URL: http://llvm.org/viewvc/llvm-project?rev=369917&view=rev
Log:
[clangd] Add docs for configuration knobs in clangd

Summary:
This is a first step in documenting different configuration knobs we
have in clangd.

Reviewers: sammccall

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

Tags: #clang

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

Added:
clang-tools-extra/trunk/docs/clangd/Configuration.rst
Modified:
clang-tools-extra/trunk/docs/clangd/index.rst

Added: clang-tools-extra/trunk/docs/clangd/Configuration.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clangd/Configuration.rst?rev=369917&view=auto
==
--- clang-tools-extra/trunk/docs/clangd/Configuration.rst (added)
+++ clang-tools-extra/trunk/docs/clangd/Configuration.rst Mon Aug 26 08:42:16 
2019
@@ -0,0 +1,39 @@
+
+Configuration
+
+
+.. contents::
+
+.. role:: raw-html(raw)
+   :format: html
+
+Clangd has a bunch of command-line options that can change its behaviour in
+certain situations. This page aims to define those configuration knobs.
+
+Those command line arguments needs to be specified in an editor-specific way.
+You can find some editor specific instructions in `here 
`__.
+
+--query-driver
+==
+
+Clangd makes use of clang behind the scenes, so it might fail to detect your
+standard library or built-in headers if your project is making use of a custom
+toolchain. That is quite common in hardware-related projects, especially for 
the
+ones making use of gcc (e.g. ARM's `arm-none-eabi-gcc`).
+
+You can specify your driver as a list of globs or full paths, then clangd will
+execute drivers and fetch necessary include paths to compile your code.
+
+For example if you have your compilers at:
+ - `/path/to/my-custom/toolchain1/arm-none-eabi-gcc`,
+ - `/path/to/my-custom/toolchain2/arm-none-eabi-g++`,
+ - `/path/to/my-custom2/toolchain/arm-none-eabi-g++`,
+you can provide clangd with
+`--query-driver=/path/to/my-custom/**/arm-none-eabi*` to enable execution of
+any binary that has a name starting with `arm-none-eabi` and under
+`/path/to/my-custom/`. This won't allow execution of the last compiler.
+
+Full list of flags
+==
+
+You can find out about the rest of the flags using `clangd --help`.

Modified: clang-tools-extra/trunk/docs/clangd/index.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clangd/index.rst?rev=369917&r1=369916&r2=369917&view=diff
==
--- clang-tools-extra/trunk/docs/clangd/index.rst (original)
+++ clang-tools-extra/trunk/docs/clangd/index.rst Mon Aug 26 08:42:16 2019
@@ -7,6 +7,7 @@ clangd
 
Installation
Features
+   Configuration
 
 What is clangd?
 ===


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


[PATCH] D66662: [clang-format] [PR43100] clang-format C# support does not add a space between "using" and paren

2019-08-26 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 217167.

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

https://reviews.llvm.org/D2

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


Index: clang/unittests/Format/FormatTestCSharp.cpp
===
--- clang/unittests/Format/FormatTestCSharp.cpp
+++ clang/unittests/Format/FormatTestCSharp.cpp
@@ -165,6 +165,21 @@
"public string Host {\n  set;\n  get;\n}");
 }
 
+TEST_F(FormatTestCSharp, CSharpUsing) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
+  Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
+  verifyFormat("public void foo() {\n"
+   "  using (StreamWriter sw = new StreamWriter (filenameA)) {}\n"
+   "}",
+   Style);
+
+  Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
+  verifyFormat("public void foo() {\n"
+   "  using(StreamWriter sw = new StreamWriter(filenameB)) {}\n"
+   "}",
+   Style);
+}
+
 TEST_F(FormatTestCSharp, CSharpRegions) {
   verifyFormat("#region aaa a "
"aaa long region");
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2611,6 +2611,10 @@
 return Style.Language == FormatStyle::LK_JavaScript ||
!Left.TokenText.endswith("=*/");
   if (Right.is(tok::l_paren)) {
+// using (FileStream fs...
+if (Style.isCSharp() && Left.is(tok::kw_using) &&
+Style.SpaceBeforeParens != FormatStyle::SBPO_Never)
+  return true;
 if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) ||
 (Left.is(tok::r_square) && Left.is(TT_AttributeSquare)))
   return true;


Index: clang/unittests/Format/FormatTestCSharp.cpp
===
--- clang/unittests/Format/FormatTestCSharp.cpp
+++ clang/unittests/Format/FormatTestCSharp.cpp
@@ -165,6 +165,21 @@
"public string Host {\n  set;\n  get;\n}");
 }
 
+TEST_F(FormatTestCSharp, CSharpUsing) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
+  Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
+  verifyFormat("public void foo() {\n"
+   "  using (StreamWriter sw = new StreamWriter (filenameA)) {}\n"
+   "}",
+   Style);
+
+  Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
+  verifyFormat("public void foo() {\n"
+   "  using(StreamWriter sw = new StreamWriter(filenameB)) {}\n"
+   "}",
+   Style);
+}
+
 TEST_F(FormatTestCSharp, CSharpRegions) {
   verifyFormat("#region aaa a "
"aaa long region");
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2611,6 +2611,10 @@
 return Style.Language == FormatStyle::LK_JavaScript ||
!Left.TokenText.endswith("=*/");
   if (Right.is(tok::l_paren)) {
+// using (FileStream fs...
+if (Style.isCSharp() && Left.is(tok::kw_using) &&
+Style.SpaceBeforeParens != FormatStyle::SBPO_Never)
+  return true;
 if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) ||
 (Left.is(tok::r_square) && Left.is(TT_AttributeSquare)))
   return true;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D64943: [Clang][OpenMP offload] Eliminate use of OpenMP linker script

2019-08-26 Thread Sergey Dmitriev via Phabricator via cfe-commits
sdmitriev added a comment.

Ping.


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

https://reviews.llvm.org/D64943



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


[PATCH] D66740: [clangd] Add docs for configuration knobs in clangd

2019-08-26 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3aeed0fd5ad5: [clangd] Add docs for configuration knobs in 
clangd (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66740

Files:
  clang-tools-extra/docs/clangd/Configuration.rst
  clang-tools-extra/docs/clangd/index.rst


Index: clang-tools-extra/docs/clangd/index.rst
===
--- clang-tools-extra/docs/clangd/index.rst
+++ clang-tools-extra/docs/clangd/index.rst
@@ -7,6 +7,7 @@
 
Installation
Features
+   Configuration
 
 What is clangd?
 ===
Index: clang-tools-extra/docs/clangd/Configuration.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clangd/Configuration.rst
@@ -0,0 +1,39 @@
+
+Configuration
+
+
+.. contents::
+
+.. role:: raw-html(raw)
+   :format: html
+
+Clangd has a bunch of command-line options that can change its behaviour in
+certain situations. This page aims to define those configuration knobs.
+
+Those command line arguments needs to be specified in an editor-specific way.
+You can find some editor specific instructions in `here 
`__.
+
+--query-driver
+==
+
+Clangd makes use of clang behind the scenes, so it might fail to detect your
+standard library or built-in headers if your project is making use of a custom
+toolchain. That is quite common in hardware-related projects, especially for 
the
+ones making use of gcc (e.g. ARM's `arm-none-eabi-gcc`).
+
+You can specify your driver as a list of globs or full paths, then clangd will
+execute drivers and fetch necessary include paths to compile your code.
+
+For example if you have your compilers at:
+ - `/path/to/my-custom/toolchain1/arm-none-eabi-gcc`,
+ - `/path/to/my-custom/toolchain2/arm-none-eabi-g++`,
+ - `/path/to/my-custom2/toolchain/arm-none-eabi-g++`,
+you can provide clangd with
+`--query-driver=/path/to/my-custom/**/arm-none-eabi*` to enable execution of
+any binary that has a name starting with `arm-none-eabi` and under
+`/path/to/my-custom/`. This won't allow execution of the last compiler.
+
+Full list of flags
+==
+
+You can find out about the rest of the flags using `clangd --help`.


Index: clang-tools-extra/docs/clangd/index.rst
===
--- clang-tools-extra/docs/clangd/index.rst
+++ clang-tools-extra/docs/clangd/index.rst
@@ -7,6 +7,7 @@
 
Installation
Features
+   Configuration
 
 What is clangd?
 ===
Index: clang-tools-extra/docs/clangd/Configuration.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clangd/Configuration.rst
@@ -0,0 +1,39 @@
+
+Configuration
+
+
+.. contents::
+
+.. role:: raw-html(raw)
+   :format: html
+
+Clangd has a bunch of command-line options that can change its behaviour in
+certain situations. This page aims to define those configuration knobs.
+
+Those command line arguments needs to be specified in an editor-specific way.
+You can find some editor specific instructions in `here `__.
+
+--query-driver
+==
+
+Clangd makes use of clang behind the scenes, so it might fail to detect your
+standard library or built-in headers if your project is making use of a custom
+toolchain. That is quite common in hardware-related projects, especially for the
+ones making use of gcc (e.g. ARM's `arm-none-eabi-gcc`).
+
+You can specify your driver as a list of globs or full paths, then clangd will
+execute drivers and fetch necessary include paths to compile your code.
+
+For example if you have your compilers at:
+ - `/path/to/my-custom/toolchain1/arm-none-eabi-gcc`,
+ - `/path/to/my-custom/toolchain2/arm-none-eabi-g++`,
+ - `/path/to/my-custom2/toolchain/arm-none-eabi-g++`,
+you can provide clangd with
+`--query-driver=/path/to/my-custom/**/arm-none-eabi*` to enable execution of
+any binary that has a name starting with `arm-none-eabi` and under
+`/path/to/my-custom/`. This won't allow execution of the last compiler.
+
+Full list of flags
+==
+
+You can find out about the rest of the flags using `clangd --help`.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r369918 - Moved GlobList into a separate header file

2019-08-26 Thread Dmitri Gribenko via cfe-commits
Author: gribozavr
Date: Mon Aug 26 08:44:32 2019
New Revision: 369918

URL: http://llvm.org/viewvc/llvm-project?rev=369918&view=rev
Log:
Moved GlobList into a separate header file

Summary:
It is a separate abstraction that is used in more contexts than just
a helper for ClangTidyDiagnosticConsumer.

Subscribers: mgorny, cfe-commits

Tags: #clang

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

Added:
clang-tools-extra/trunk/clang-tidy/GlobList.cpp
clang-tools-extra/trunk/clang-tidy/GlobList.h
clang-tools-extra/trunk/unittests/clang-tidy/GlobListTest.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/CMakeLists.txt
clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp
clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.h
clang-tools-extra/trunk/clang-tidy/fuchsia/RestrictSystemIncludesCheck.h
clang-tools-extra/trunk/clang-tidy/tool/ClangTidyMain.cpp
clang-tools-extra/trunk/unittests/clang-tidy/CMakeLists.txt

clang-tools-extra/trunk/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp

Modified: clang-tools-extra/trunk/clang-tidy/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/CMakeLists.txt?rev=369918&r1=369917&r2=369918&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/CMakeLists.txt Mon Aug 26 08:44:32 2019
@@ -10,6 +10,7 @@ add_clang_library(clangTidy
   ClangTidyOptions.cpp
   ClangTidyProfiling.cpp
   ExpandModularHeadersPPCallbacks.cpp
+  GlobList.cpp
 
   DEPENDS
   ClangSACheckers

Modified: clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp?rev=369918&r1=369917&r2=369918&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp Mon Aug 
26 08:44:32 2019
@@ -17,6 +17,7 @@
 
 #include "ClangTidyDiagnosticConsumer.h"
 #include "ClangTidyOptions.h"
+#include "GlobList.h"
 #include "clang/AST/ASTDiagnostic.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticOptions.h"
@@ -118,47 +119,6 @@ ClangTidyError::ClangTidyError(StringRef
 : tooling::Diagnostic(CheckName, DiagLevel, BuildDirectory),
   IsWarningAsError(IsWarningAsError) {}
 
-// Returns true if GlobList starts with the negative indicator ('-'), removes 
it
-// from the GlobList.
-static bool ConsumeNegativeIndicator(StringRef &GlobList) {
-  GlobList = GlobList.trim(" \r\n");
-  if (GlobList.startswith("-")) {
-GlobList = GlobList.substr(1);
-return true;
-  }
-  return false;
-}
-// Converts first glob from the comma-separated list of globs to Regex and
-// removes it and the trailing comma from the GlobList.
-static llvm::Regex ConsumeGlob(StringRef &GlobList) {
-  StringRef UntrimmedGlob = GlobList.substr(0, GlobList.find(','));
-  StringRef Glob = UntrimmedGlob.trim(' ');
-  GlobList = GlobList.substr(UntrimmedGlob.size() + 1);
-  SmallString<128> RegexText("^");
-  StringRef MetaChars("()^$|*+?.[]\\{}");
-  for (char C : Glob) {
-if (C == '*')
-  RegexText.push_back('.');
-else if (MetaChars.find(C) != StringRef::npos)
-  RegexText.push_back('\\');
-RegexText.push_back(C);
-  }
-  RegexText.push_back('$');
-  return llvm::Regex(RegexText);
-}
-
-GlobList::GlobList(StringRef Globs)
-: Positive(!ConsumeNegativeIndicator(Globs)), Regex(ConsumeGlob(Globs)),
-  NextGlob(Globs.empty() ? nullptr : new GlobList(Globs)) {}
-
-bool GlobList::contains(StringRef S, bool Contains) {
-  if (Regex.match(S))
-Contains = Positive;
-
-  if (NextGlob)
-Contains = NextGlob->contains(S, Contains);
-  return Contains;
-}
 
 class ClangTidyContext::CachedGlobList {
 public:

Modified: clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.h?rev=369918&r1=369917&r2=369918&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.h (original)
+++ clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.h Mon Aug 26 
08:44:32 2019
@@ -17,7 +17,6 @@
 #include "clang/Tooling/Refactoring.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringMap.h"
-#include "llvm/Support/Regex.h"
 #include "llvm/Support/Timer.h"
 
 namespace clang {
@@ -47,27 +46,6 @@ struct ClangTidyError : tooling::Diagnos
   bool IsWarningAsError;
 };
 
-/// Read-only set of strings represented as a list of positive and
-/// negative globs. Positive globs add all matched strings to the set, negative
-/// globs remove them in the order of appeara

[PATCH] D66748: [PowerPC][Altivec][Clang] Check compile-time constant for vec_dst*

2019-08-26 Thread Jinsong Ji via Phabricator via cfe-commits
jsji created this revision.
jsji added reviewers: nemanjai, hfinkel, echristo.
Herald added subscribers: cfe-commits, shchenz, MaskRay, kbarton.
Herald added a project: clang.
jsji added a reviewer: PowerPC.
Herald added a subscriber: wuzish.

This is follow up of https://reviews.llvm.org/D66699.
We might get ISEL ICE if we call vec_dss with non const 3rd arg.

  Cannot select: intrinsic %llvm.ppc.altivec.dst

We should check the constraints in clang and generate better error
messages.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66748

Files:
  clang/include/clang/Basic/BuiltinsPPC.def
  clang/test/CodeGen/builtins-ppc-error.c


Index: clang/test/CodeGen/builtins-ppc-error.c
===
--- clang/test/CodeGen/builtins-ppc-error.c
+++ clang/test/CodeGen/builtins-ppc-error.c
@@ -73,3 +73,11 @@
   __builtin_unpack_vector_int128(vsllli, index); //expected-error {{argument 
to '__builtin_unpack_vector_int128' must be a constant integer}}
   __builtin_unpack_vector_int128(vsllli, 5); //expected-error {{argument value 
5 is outside the valid range [0, 1]}}
 }
+
+
+void testDST(int index) {
+  vec_dst(&vsi, index, index); //expected-error {{argument to 
'__builtin_altivec_dst' must be a constant integer}}
+  vec_dstt(&vsi, index, index); //expected-error {{argument to 
'__builtin_altivec_dstt' must be a constant integer}}
+  vec_dstst(&vsi, index, index); //expected-error {{argument to 
'__builtin_altivec_dstst' must be a constant integer}}
+  vec_dststt(&vsi, index, index); //expected-error {{argument to 
'__builtin_altivec_dststt' must be a constant integer}}
+}
Index: clang/include/clang/Basic/BuiltinsPPC.def
===
--- clang/include/clang/Basic/BuiltinsPPC.def
+++ clang/include/clang/Basic/BuiltinsPPC.def
@@ -57,10 +57,10 @@
 
 BUILTIN(__builtin_altivec_dss, "vUi", "")
 BUILTIN(__builtin_altivec_dssall, "v", "")
-BUILTIN(__builtin_altivec_dst, "vvC*iUi", "")
-BUILTIN(__builtin_altivec_dstt, "vvC*iUi", "")
-BUILTIN(__builtin_altivec_dstst, "vvC*iUi", "")
-BUILTIN(__builtin_altivec_dststt, "vvC*iUi", "")
+BUILTIN(__builtin_altivec_dst, "vvC*iUIi", "")
+BUILTIN(__builtin_altivec_dstt, "vvC*iUIi", "")
+BUILTIN(__builtin_altivec_dstst, "vvC*iUIi", "")
+BUILTIN(__builtin_altivec_dststt, "vvC*iUIi", "")
 
 BUILTIN(__builtin_altivec_vexptefp, "V4fV4f", "")
 


Index: clang/test/CodeGen/builtins-ppc-error.c
===
--- clang/test/CodeGen/builtins-ppc-error.c
+++ clang/test/CodeGen/builtins-ppc-error.c
@@ -73,3 +73,11 @@
   __builtin_unpack_vector_int128(vsllli, index); //expected-error {{argument to '__builtin_unpack_vector_int128' must be a constant integer}}
   __builtin_unpack_vector_int128(vsllli, 5); //expected-error {{argument value 5 is outside the valid range [0, 1]}}
 }
+
+
+void testDST(int index) {
+  vec_dst(&vsi, index, index); //expected-error {{argument to '__builtin_altivec_dst' must be a constant integer}}
+  vec_dstt(&vsi, index, index); //expected-error {{argument to '__builtin_altivec_dstt' must be a constant integer}}
+  vec_dstst(&vsi, index, index); //expected-error {{argument to '__builtin_altivec_dstst' must be a constant integer}}
+  vec_dststt(&vsi, index, index); //expected-error {{argument to '__builtin_altivec_dststt' must be a constant integer}}
+}
Index: clang/include/clang/Basic/BuiltinsPPC.def
===
--- clang/include/clang/Basic/BuiltinsPPC.def
+++ clang/include/clang/Basic/BuiltinsPPC.def
@@ -57,10 +57,10 @@
 
 BUILTIN(__builtin_altivec_dss, "vUi", "")
 BUILTIN(__builtin_altivec_dssall, "v", "")
-BUILTIN(__builtin_altivec_dst, "vvC*iUi", "")
-BUILTIN(__builtin_altivec_dstt, "vvC*iUi", "")
-BUILTIN(__builtin_altivec_dstst, "vvC*iUi", "")
-BUILTIN(__builtin_altivec_dststt, "vvC*iUi", "")
+BUILTIN(__builtin_altivec_dst, "vvC*iUIi", "")
+BUILTIN(__builtin_altivec_dstt, "vvC*iUIi", "")
+BUILTIN(__builtin_altivec_dstst, "vvC*iUIi", "")
+BUILTIN(__builtin_altivec_dststt, "vvC*iUIi", "")
 
 BUILTIN(__builtin_altivec_vexptefp, "V4fV4f", "")
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D66538: [AST] AST structural equivalence to work internally with pairs.

2019-08-26 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

In D66538#1642999 , @balazske wrote:

> In D66538#1642883 , @martong wrote:
>
> > There is a third test which could be useful to test whether there is no 
> > faulty cache entries there:
> >
> >   +TEST_F(StructuralEquivalenceCacheTest, DISABLED_NonEq) {
> >   ...
> >   +}
> >
>
>
> This is somewhat the same check that is done in the current tests when the 
> `NonEquivalentDecls` is checked to not contain any pairs of equivalent Decls. 
> (Specially this line:
>
>   EXPECT_FALSE(isInNonEqCache(
> findDeclPair(TU, functionDecl(hasName("x");
>
>
> )


Ok, that looks good.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66538



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


[PATCH] D66336: [ASTImporter] Add development internals docs

2019-08-26 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 217171.
martong added a comment.

- Fix typo: getTemplatedDec -> getTemplatedDecl


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66336

Files:
  clang/docs/InternalsManual.rst

Index: clang/docs/InternalsManual.rst
===
--- clang/docs/InternalsManual.rst
+++ clang/docs/InternalsManual.rst
@@ -1447,6 +1447,495 @@
 are not ``Redeclarable`` -- in that case, a ``Mergeable`` base class is used
 instead).
 
+The ASTImporter
+---
+
+The ``ASTImporter`` class imports nodes of an ``ASTContext`` into another
+``ASTContext``. Please refer to the document :doc:`ASTImporter: Merging Clang
+ASTs ` for an introduction. And please read through the
+high-level `description of the import algorithm
+`_, this is essential for
+understanding further implementation details of the importer.
+
+.. _templated:
+
+Abstract Syntax Graph
+^
+
+Despite the name, the Clang AST is not a tree. It is a directed graph with
+cycles. One example of a cycle is the connection between a
+``ClassTemplateDecl`` and its "templated" ``CXXRecordDecl``. The *templated*
+``CXXRecordDecl`` represents all the fields and methods inside the class
+template, while the ``ClassTemplateDecl`` holds the information which is
+related to being a template, i.e. template arguments, etc. We can get the
+*templated* class (the ``CXXRecordDecl``) of a ``ClassTemplateDecl`` with
+``ClassTemplateDecl::getTemplatedDecl()``. And we can get back a pointer of the
+"described" class template from the *templated* class:
+``CXXRecordDecl::getDescribedTemplate()``. So, this is a cycle between two
+nodes: between the *templated* and the *described* node. There may be various
+other kinds of cycles in the AST especially in case of declarations.
+
+.. _structural-eq:
+
+Structural Equivalency
+^^
+
+Importing one AST node copies that node into the destination ``ASTContext``. To
+copy one node means that we create a new node in the "to" context then we set
+its properties to be equal to the properties of the source node. Before the
+copy, we make sure that the source node is not *structurally equivalent* to any
+existing node in the destination context. If it happens to be equivalent then
+we skip the copy.
+
+The informal definition of structural equivalency is the following:
+Two nodes are **structurally equivalent** if they are
+
+- builtin types and refer to the same type, e.g. ``int`` and ``int`` are
+  structurally equivalent,
+- function types and all their parameters have structurally equivalent types,
+- record types and all their fields in order of their definition have the same
+  identifier names and structurally equivalent types,
+- variable or function declarations and they have the same identifier name and
+  their types are structurally equivalent.
+
+In C, two types are structurally equivalent if they are *compatible types*. For
+a formal definition of *compatible types*, please refer to 6.2.7/1 in the C11
+standard. However, there is no definition for *compatible types* in the C++
+standard. Still, we extend the definition of structural equivalency to
+templates and their instantiations similarly: besides checking the previously
+mentioned properties, we have to check for equivalent template
+parameters/arguments, etc.
+
+The structural equivalent check can be and is used independently from the
+ASTImporter, e.g. the ``clang::Sema`` class uses it also.
+
+The equivalence of nodes may depend on the equivalency of other pairs of nodes.
+Thus, the check is implemented as a parallel graph traversal. We traverse
+through the nodes of both graphs at the same time. The actual implementation is
+similar to breadth-first-search. Let's say we start the traverse with the 
+pair of nodes. Whenever the traversal reaches a pair  then the following
+statements are true:
+
+- A and X are nodes from the same ASTContext.
+- B and Y are nodes from the same ASTContext.
+- A and B may or may not be from the same ASTContext.
+- if A == X (pointer equivalency) then (there is a cycle during the traverse)
+
+  - A and B are structurally equivalent if and only if
+
+- B and Y are part of the same redeclaration chain,
+- All dependent nodes on the path from  to  are structurally
+  equivalent.
+
+When we compare two classes or enums and one of them is incomplete or has
+unloaded external lexical declarations then we cannot descend to compare their
+contained declarations. So in these cases they are considered equal if they
+have the same names. This is the way how we compare forward declarations with
+definitions.
+
+.. TODO Should we elaborate the actual implementation of the graph traversal,
+.. which is a very weird BFS traversal?
+
+Redeclaration Chains
+
+
+The early version of the ``ASTImporter``'s merge mechanism squ

[PATCH] D66733: [analyzer] Add a checker option to detect nested dead stores

2019-08-26 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

@NoQ What do you think, should it be under a flag (as it would be now), or 
enabled by default?
I think these warnings are valuable and we should consider it enabling by 
default.
An interesting fact is that previously 
rGf224820b45c6847b91071da8d7ade59f373b96f3 
 patch 
disabled this warning saying that it generates too many false-positives without 
any real benefit.

But after seeing the reports on the LLVM codebase (CodeChecker instance for the 
diff 
)
 I still question this decision. What is your opinion?

Any comment how could this result in false-positives are welcomed.


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

https://reviews.llvm.org/D66733



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


[PATCH] D66747: Moved GlobList into a separate header file

2019-08-26 Thread Dmitri Gribenko via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa6fed93f0d10: Moved GlobList into a separate header file 
(authored by gribozavr).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66747

Files:
  clang-tools-extra/clang-tidy/CMakeLists.txt
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
  clang-tools-extra/clang-tidy/GlobList.cpp
  clang-tools-extra/clang-tidy/GlobList.h
  clang-tools-extra/clang-tidy/fuchsia/RestrictSystemIncludesCheck.h
  clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
  clang-tools-extra/unittests/clang-tidy/CMakeLists.txt
  clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp
  clang-tools-extra/unittests/clang-tidy/GlobListTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/GlobListTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/GlobListTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/GlobListTest.cpp
@@ -1,33 +1,8 @@
-#include "ClangTidy.h"
-#include "ClangTidyTest.h"
+#include "GlobList.h"
 #include "gtest/gtest.h"
 
 namespace clang {
 namespace tidy {
-namespace test {
-
-class TestCheck : public ClangTidyCheck {
-public:
-  TestCheck(StringRef Name, ClangTidyContext *Context)
-  : ClangTidyCheck(Name, Context) {}
-  void registerMatchers(ast_matchers::MatchFinder *Finder) override {
-Finder->addMatcher(ast_matchers::varDecl().bind("var"), this);
-  }
-  void check(const ast_matchers::MatchFinder::MatchResult &Result) override {
-const auto *Var = Result.Nodes.getNodeAs("var");
-// Add diagnostics in the wrong order.
-diag(Var->getLocation(), "variable");
-diag(Var->getTypeSpecStartLoc(), "type specifier");
-  }
-};
-
-TEST(ClangTidyDiagnosticConsumer, SortsErrors) {
-  std::vector Errors;
-  runCheckOnCode("int a;", &Errors);
-  EXPECT_EQ(2ul, Errors.size());
-  EXPECT_EQ("type specifier", Errors[0].Message.Message);
-  EXPECT_EQ("variable", Errors[1].Message.Message);
-}
 
 TEST(GlobList, Empty) {
   GlobList Filter("");
@@ -89,6 +64,5 @@
   EXPECT_TRUE(Filter.contains("asdfqwEasdf"));
 }
 
-} // namespace test
 } // namespace tidy
 } // namespace clang
Index: clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp
@@ -29,66 +29,6 @@
   EXPECT_EQ("variable", Errors[1].Message.Message);
 }
 
-TEST(GlobList, Empty) {
-  GlobList Filter("");
-
-  EXPECT_TRUE(Filter.contains(""));
-  EXPECT_FALSE(Filter.contains("aaa"));
-}
-
-TEST(GlobList, Nothing) {
-  GlobList Filter("-*");
-
-  EXPECT_FALSE(Filter.contains(""));
-  EXPECT_FALSE(Filter.contains("a"));
-  EXPECT_FALSE(Filter.contains("-*"));
-  EXPECT_FALSE(Filter.contains("-"));
-  EXPECT_FALSE(Filter.contains("*"));
-}
-
-TEST(GlobList, Everything) {
-  GlobList Filter("*");
-
-  EXPECT_TRUE(Filter.contains(""));
-  EXPECT_TRUE(Filter.contains(""));
-  EXPECT_TRUE(Filter.contains("-*"));
-  EXPECT_TRUE(Filter.contains("-"));
-  EXPECT_TRUE(Filter.contains("*"));
-}
-
-TEST(GlobList, Simple) {
-  GlobList Filter("aaa");
-
-  EXPECT_TRUE(Filter.contains("aaa"));
-  EXPECT_FALSE(Filter.contains(""));
-  EXPECT_FALSE(Filter.contains("aa"));
-  EXPECT_FALSE(Filter.contains(""));
-  EXPECT_FALSE(Filter.contains("bbb"));
-}
-
-TEST(GlobList, WhitespacesAtBegin) {
-  GlobList Filter("-*,   a.b.*");
-
-  EXPECT_TRUE(Filter.contains("a.b.c"));
-  EXPECT_FALSE(Filter.contains("b.c"));
-}
-
-TEST(GlobList, Complex) {
-  GlobList Filter("*,-a.*, -b.*, \r  \n  a.1.* ,-a.1.A.*,-..,-...,-..+,-*$, -*qwe* ");
-
-  EXPECT_TRUE(Filter.contains("aaa"));
-  EXPECT_TRUE(Filter.contains("qqq"));
-  EXPECT_FALSE(Filter.contains("a."));
-  EXPECT_FALSE(Filter.contains("a.b"));
-  EXPECT_FALSE(Filter.contains("b."));
-  EXPECT_FALSE(Filter.contains("b.b"));
-  EXPECT_TRUE(Filter.contains("a.1.b"));
-  EXPECT_FALSE(Filter.contains("a.1.A.a"));
-  EXPECT_FALSE(Filter.contains("qwe"));
-  EXPECT_FALSE(Filter.contains("asdfqweasdf"));
-  EXPECT_TRUE(Filter.contains("asdfqwEasdf"));
-}
-
 } // namespace test
 } // namespace tidy
 } // namespace clang
Index: clang-tools-extra/unittests/clang-tidy/CMakeLists.txt
===
--- clang-tools-extra/unittests/clang-tidy/CMakeLists.txt
+++ clang-tools-extra/unittests/clang-tidy/CMakeLists.txt
@@ -10,6 +10,7 @@
   ClangTidyDiagnosticConsumerTest.cpp
   ClangTidyOptionsTest.cpp
   IncludeInserterTest.cpp
+  GlobListTest.cpp
   GoogleModuleTest.cpp
   LLVMModuleTest.cpp
   NamespaceAliaserTest.cpp
Index: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
==

[PATCH] D66336: [ASTImporter] Add development internals docs

2019-08-26 Thread Gabor Marton via Phabricator via cfe-commits
martong marked 2 inline comments as done.
martong added inline comments.



Comment at: clang/docs/InternalsManual.rst:1470
+*templated* class (the ``CXXRecordDecl``) of a ``ClassTemplateDecl`` with
+``ClassTemplateDecl::getTemplatedDec()``. And we can get back a pointer of the
+"described" class template from the *templated* class:

a_sidorin wrote:
> martong wrote:
> > a_sidorin wrote:
> > > TemplatedDec_l_?
> > Could you please elaborate, I don't get the meaning of the comment.
> Sorry, I mean, you probably meant `ClassTemplateDecl::getTemplatedDecl` but 
> typed `getTemplatedDec()` (missing 'l' at the end). 
Ok, thanks now I see what you meant. Fixed it. Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66336



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


[PATCH] D66485: [Clang][Bundler] Use llvm-objcopy for creating fat object files

2019-08-26 Thread Sergey Dmitriev via Phabricator via cfe-commits
sdmitriev added a comment.

Any feedback?


Repository:
  rC Clang

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

https://reviews.llvm.org/D66485



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


[clang-tools-extra] r369920 - [clangd] Fix docs

2019-08-26 Thread Kadir Cetinkaya via cfe-commits
Author: kadircet
Date: Mon Aug 26 09:01:07 2019
New Revision: 369920

URL: http://llvm.org/viewvc/llvm-project?rev=369920&view=rev
Log:
[clangd] Fix docs

Modified:
clang-tools-extra/trunk/docs/clangd/Configuration.rst

Modified: clang-tools-extra/trunk/docs/clangd/Configuration.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clangd/Configuration.rst?rev=369920&r1=369919&r2=369920&view=diff
==
--- clang-tools-extra/trunk/docs/clangd/Configuration.rst (original)
+++ clang-tools-extra/trunk/docs/clangd/Configuration.rst Mon Aug 26 09:01:07 
2019
@@ -1,6 +1,6 @@
-
+=
 Configuration
-
+=
 
 .. contents::
 
@@ -28,6 +28,7 @@ For example if you have your compilers a
  - `/path/to/my-custom/toolchain1/arm-none-eabi-gcc`,
  - `/path/to/my-custom/toolchain2/arm-none-eabi-g++`,
  - `/path/to/my-custom2/toolchain/arm-none-eabi-g++`,
+   
 you can provide clangd with
 `--query-driver=/path/to/my-custom/**/arm-none-eabi*` to enable execution of
 any binary that has a name starting with `arm-none-eabi` and under


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


[PATCH] D66485: [Clang][Bundler] Use llvm-objcopy for creating fat object files

2019-08-26 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp:485
+"=" + InputFileNames[I]));
+ObjcopyArgs.push_back(InputFileNames[HostInputIndex]);
+ObjcopyArgs.push_back(OutputFileNames.front());

As I understand, the resulting object file has the same structure as before? 
And we still can get an access to the host object file using standard programs, 
like readelf, objdump, etc.?


Repository:
  rC Clang

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

https://reviews.llvm.org/D66485



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


Re: r369829 - PR40674: fix assertion failure if a structured binding declaration has a

2019-08-26 Thread Hans Wennborg via cfe-commits
Merged to release_90 in r369921.

On Sat, Aug 24, 2019 at 3:22 AM Richard Smith via cfe-commits
 wrote:
>
> Author: rsmith
> Date: Fri Aug 23 18:23:57 2019
> New Revision: 369829
>
> URL: http://llvm.org/viewvc/llvm-project?rev=369829&view=rev
> Log:
> PR40674: fix assertion failure if a structured binding declaration has a
> tuple-like decomposition that produces value-dependent reference
> bindings.
>
> Modified:
> cfe/trunk/lib/Sema/SemaDeclCXX.cpp
> cfe/trunk/test/CXX/dcl.decl/dcl.decomp/p3.cpp
>
> Modified: cfe/trunk/lib/Sema/SemaDeclCXX.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclCXX.cpp?rev=369829&r1=369828&r2=369829&view=diff
> ==
> --- cfe/trunk/lib/Sema/SemaDeclCXX.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaDeclCXX.cpp Fri Aug 23 18:23:57 2019
> @@ -1225,7 +1225,8 @@ static bool checkTupleLikeDecomposition(
>  if (E.isInvalid())
>return true;
>  RefVD->setInit(E.get());
> -RefVD->checkInitIsICE();
> +if (!E.get()->isValueDependent())
> +  RefVD->checkInitIsICE();
>
>  E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
> DeclarationNameInfo(B->getDeclName(), 
> Loc),
>
> Modified: cfe/trunk/test/CXX/dcl.decl/dcl.decomp/p3.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CXX/dcl.decl/dcl.decomp/p3.cpp?rev=369829&r1=369828&r2=369829&view=diff
> ==
> --- cfe/trunk/test/CXX/dcl.decl/dcl.decomp/p3.cpp (original)
> +++ cfe/trunk/test/CXX/dcl.decl/dcl.decomp/p3.cpp Fri Aug 23 18:23:57 2019
> @@ -127,7 +127,7 @@ void referenced_type() {
>using ConstInt3 = decltype(bcr2);
>  }
>
> -struct C { template int get(); };
> +struct C { template int get() const; };
>  template<> struct std::tuple_size { static const int value = 1; };
>  template<> struct std::tuple_element<0, C> { typedef int type; };
>
> @@ -138,6 +138,12 @@ int member_get() {
>return c;
>  }
>
> +constexpr C c = C();
> +template void dependent_binding_PR40674() {
> +  const auto &[c] = *p;
> +  (void)c;
> +}
> +
>  struct D {
>// FIXME: Emit a note here explaining why this was ignored.
>template struct get {};
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D66565: [analyzer] pr43036: Fix support for operator `sizeof...'.

2019-08-26 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus accepted this revision.
Szelethus added a comment.

(++LGTM)++


Repository:
  rC Clang

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

https://reviews.llvm.org/D66565



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


[PATCH] D66556: [clang-scan-deps] Minimizer: Correctly handle multi-line content with CR+LF line endings

2019-08-26 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea updated this revision to Diff 217179.
aganea added a comment.

Fixed unit tests.


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

https://reviews.llvm.org/D66556

Files:
  lib/Lex/DependencyDirectivesSourceMinimizer.cpp
  test/Lexer/minimize_source_to_dependency_directives_invalid_error.c

Index: test/Lexer/minimize_source_to_dependency_directives_invalid_error.c
===
--- test/Lexer/minimize_source_to_dependency_directives_invalid_error.c
+++ test/Lexer/minimize_source_to_dependency_directives_invalid_error.c
@@ -0,0 +1,16 @@
+// Test CF+LF are properly handled along with quoted, multi-line #error
+// RUN: cat %s | unix2dos | %clang_cc1 -DOTHER -print-dependency-directives-minimized-source 2>&1 | FileCheck %s
+
+#ifndef TEST
+#error "message \
+   more message \
+   even more"
+#endif
+
+#ifdef OTHER
+#include 
+#endif
+
+// CHECK:  #ifdef OTHER
+// CHECK-NEXT: #include 
+// CHECK-NEXT: #endif
Index: lib/Lex/DependencyDirectivesSourceMinimizer.cpp
===
--- lib/Lex/DependencyDirectivesSourceMinimizer.cpp
+++ lib/Lex/DependencyDirectivesSourceMinimizer.cpp
@@ -196,15 +196,29 @@
 ++First; // Finish off the string.
 }
 
-static void skipNewline(const char *&First, const char *End) {
-  assert(isVerticalWhitespace(*First));
-  ++First;
+// Returns the length of EOL, either 0 (no end-of-line), 1 (\n) or 2 (\r\n)
+static unsigned isEOL(const char *First, const char *const End) {
   if (First == End)
-return;
+return 0;
+  if (End - First > 1 && isVerticalWhitespace(First[0]) &&
+  isVerticalWhitespace(First[1]) && First[0] != First[1])
+return 2;
+  return !!isVerticalWhitespace(First[0]);
+}
 
-  // Check for "\n\r" and "\r\n".
-  if (LLVM_UNLIKELY(isVerticalWhitespace(*First) && First[-1] != First[0]))
-++First;
+// Returns the length of the skipped newline
+static unsigned skipNewline(const char *&First, const char *End) {
+  if (First == End)
+return 0;
+  assert(isVerticalWhitespace(*First));
+  unsigned Len = isEOL(First, End);
+  assert(Len && "expected newline");
+  First += Len;
+  return Len;
+}
+
+static bool wasLineContinuation(const char *First, unsigned EOLLen) {
+  return *(First - (int)EOLLen - 1) == '\\';
 }
 
 static void skipToNewlineRaw(const char *&First, const char *const End) {
@@ -212,17 +226,21 @@
 if (First == End)
   return;
 
-if (isVerticalWhitespace(*First))
+unsigned Len = isEOL(First, End);
+if (Len)
   return;
 
-while (!isVerticalWhitespace(*First))
+do {
   if (++First == End)
 return;
+  Len = isEOL(First, End);
+} while (!Len);
 
 if (First[-1] != '\\')
   return;
 
-++First; // Keep going...
+First += Len;
+// Keep skipping lines...
   }
 }
 
@@ -277,7 +295,7 @@
 }
 
 static void skipLine(const char *&First, const char *const End) {
-  do {
+  for (;;) {
 assert(First <= End);
 if (First == End)
   return;
@@ -322,9 +340,10 @@
   return;
 
 // Skip over the newline.
-assert(isVerticalWhitespace(*First));
-skipNewline(First, End);
-  } while (First[-2] == '\\'); // Continue past line-continuations.
+unsigned Len = skipNewline(First, End);
+if (!wasLineContinuation(First, Len)) // Continue past line-continuations.
+  break;
+  }
 }
 
 static void skipDirective(StringRef Name, const char *&First,
@@ -379,6 +398,8 @@
 // Print out the string.
 if (Last == End || Last == First || Last[-1] != '\\') {
   append(First, reverseOverSpaces(First, Last));
+  First = Last;
+  skipNewline(First, End);
   return;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r369925 - [clang-doc] Switch Generator::CreateResources to use llvm::Error

2019-08-26 Thread Julie Hockett via cfe-commits
Author: juliehockett
Date: Mon Aug 26 09:39:48 2019
New Revision: 369925

URL: http://llvm.org/viewvc/llvm-project?rev=369925&view=rev
Log:
[clang-doc] Switch Generator::CreateResources to use llvm::Error

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

Modified:
clang-tools-extra/trunk/clang-doc/Generators.cpp
clang-tools-extra/trunk/clang-doc/Generators.h
clang-tools-extra/trunk/clang-doc/HTMLGenerator.cpp
clang-tools-extra/trunk/clang-doc/tool/ClangDocMain.cpp

Modified: clang-tools-extra/trunk/clang-doc/Generators.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-doc/Generators.cpp?rev=369925&r1=369924&r2=369925&view=diff
==
--- clang-tools-extra/trunk/clang-doc/Generators.cpp (original)
+++ clang-tools-extra/trunk/clang-doc/Generators.cpp Mon Aug 26 09:39:48 2019
@@ -57,7 +57,9 @@ std::string getTagType(TagTypeKind AS) {
   llvm_unreachable("Unknown TagTypeKind");
 }
 
-bool Generator::createResources(ClangDocContext &CDCtx) { return true; }
+llvm::Error Generator::createResources(ClangDocContext &CDCtx) {
+  return llvm::Error::success();
+}
 
 // A function to add a reference to Info in Idx.
 // Given an Info X with the following namespaces: [B,A]; a reference to X will

Modified: clang-tools-extra/trunk/clang-doc/Generators.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-doc/Generators.h?rev=369925&r1=369924&r2=369925&view=diff
==
--- clang-tools-extra/trunk/clang-doc/Generators.h (original)
+++ clang-tools-extra/trunk/clang-doc/Generators.h Mon Aug 26 09:39:48 2019
@@ -32,7 +32,7 @@ public:
   // It can be overwritten by any of the inherited generators.
   // If the override method wants to run this it should call
   // Generator::createResources(CDCtx);
-  virtual bool createResources(ClangDocContext &CDCtx);
+  virtual llvm::Error createResources(ClangDocContext &CDCtx);
 
   static void addInfoToIndex(Index &Idx, const doc::Info *Info);
 };

Modified: clang-tools-extra/trunk/clang-doc/HTMLGenerator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-doc/HTMLGenerator.cpp?rev=369925&r1=369924&r2=369925&view=diff
==
--- clang-tools-extra/trunk/clang-doc/HTMLGenerator.cpp (original)
+++ clang-tools-extra/trunk/clang-doc/HTMLGenerator.cpp Mon Aug 26 09:39:48 2019
@@ -829,7 +829,7 @@ public:
 
   llvm::Error generateDocForInfo(Info *I, llvm::raw_ostream &OS,
  const ClangDocContext &CDCtx) override;
-  bool createResources(ClangDocContext &CDCtx) override;
+  llvm::Error createResources(ClangDocContext &CDCtx) override;
 };
 
 const char *HTMLGenerator::Format = "html";
@@ -883,7 +883,7 @@ static std::string getRefType(InfoType I
   llvm_unreachable("Unknown InfoType");
 }
 
-static bool SerializeIndex(ClangDocContext &CDCtx) {
+static llvm::Error SerializeIndex(ClangDocContext &CDCtx) {
   std::error_code OK;
   std::error_code FileErr;
   llvm::SmallString<128> FilePath;
@@ -891,8 +891,9 @@ static bool SerializeIndex(ClangDocConte
   llvm::sys::path::append(FilePath, "index_json.js");
   llvm::raw_fd_ostream OS(FilePath, FileErr, llvm::sys::fs::F_None);
   if (FileErr != OK) {
-llvm::errs() << "Error creating index file: " << FileErr.message() << "\n";
-return false;
+return llvm::make_error(
+"Error creating index file: " + FileErr.message() + "\n",
+llvm::inconvertibleErrorCode());
   }
   CDCtx.Idx.sort();
   llvm::json::OStream J(OS, 2);
@@ -911,7 +912,7 @@ static bool SerializeIndex(ClangDocConte
   OS << "var JsonIndex = `\n";
   IndexToJSON(CDCtx.Idx);
   OS << "`;\n";
-  return true;
+  return llvm::Error::success();
 }
 
 // Generates a main HTML node that has the main content of the file that shows
@@ -932,15 +933,16 @@ static std::unique_ptr genIndex
   return MainNode;
 }
 
-static bool GenIndex(const ClangDocContext &CDCtx) {
+static llvm::Error GenIndex(const ClangDocContext &CDCtx) {
   std::error_code FileErr, OK;
   llvm::SmallString<128> IndexPath;
   llvm::sys::path::native(CDCtx.OutDirectory, IndexPath);
   llvm::sys::path::append(IndexPath, "index.html");
   llvm::raw_fd_ostream IndexOS(IndexPath, FileErr, llvm::sys::fs::F_None);
   if (FileErr != OK) {
-llvm::errs() << "Error creating main index: " << FileErr.message() << "\n";
-return false;
+return llvm::make_error(
+"Error creating main index: " + FileErr.message() + "\n",
+llvm::inconvertibleErrorCode());
   }
 
   HTMLFile F;
@@ -958,10 +960,10 @@ static bool GenIndex(const ClangDocConte
 
   F.Render(IndexOS);
 
-  return true;
+  return llvm::Error::success();
 }
 
-static bool CopyFile(StringRef FilePath, StringRef OutDirectory) {
+static llvm::Error CopyFile(StringRef FilePath, StringRef OutDirectory) {
   ll

[PATCH] D66485: [Clang][Bundler] Use llvm-objcopy for creating fat object files

2019-08-26 Thread Sergey Dmitriev via Phabricator via cfe-commits
sdmitriev marked an inline comment as done.
sdmitriev added inline comments.



Comment at: clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp:485
+"=" + InputFileNames[I]));
+ObjcopyArgs.push_back(InputFileNames[HostInputIndex]);
+ObjcopyArgs.push_back(OutputFileNames.front());

ABataev wrote:
> As I understand, the resulting object file has the same structure as before? 
> And we still can get an access to the host object file using standard 
> programs, like readelf, objdump, etc.?
Yes, the structure is the same. The only difference is in the section flags 
that contain device objects - such sections used to have ALLOC attribute, but 
they do not have it now which I believe is a good think.

That is what we had earlier:

```
bash-4.2$ cat y.c
#pragma omp declare target
void foo() {}
#pragma omp end declare target
bash-4.2$ clang -fopenmp -fopenmp-targets=x86_64-pc-linux-gnu -c y.c
bash-4.2$ objdump -h y.o 

y.o: file format elf64-x86-64

Sections:
Idx Name  Size  VMA   LMA   File off  Algn
  0 .text 0008      0040  2**4
  CONTENTS, ALLOC, LOAD, READONLY, CODE
  1 .text.startup 0010      0050  2**4
  CONTENTS, ALLOC, LOAD, RELOC, READONLY, CODE
  2 __CLANG_OFFLOAD_BUNDLE__openmp-x86_64-pc-linux-gnu 03f8  
    0060  2**4
  CONTENTS, ALLOC, LOAD, READONLY, DATA
  3 __CLANG_OFFLOAD_BUNDLE__host-x86_64-unknown-linux-gnu 0630  
    0460  2**4
  CONTENTS, ALLOC, LOAD, READONLY, DATA
  4 .eh_frame 0058      0a90  2**3
  CONTENTS, ALLOC, LOAD, RELOC, READONLY, DATA
  5 .init_array.0 0008      0ae8  2**3
  CONTENTS, ALLOC, LOAD, RELOC, DATA
  6 .comment  006a      0af0  2**0
  CONTENTS, READONLY
  7 .note.GNU-stack       0b5a  2**0
  CONTENTS, READONLY
  8 .llvm_addrsig 0002      0b5a  2**0
  CONTENTS, READONLY, EXCLUDE
bash-4.2$ 
```

And here is what we have with this patch:

```
bash-4.2$ clang -fopenmp -fopenmp-targets=x86_64-pc-linux-gnu -c y.c
bash-4.2$ objdump -h y.o 

y.o: file format elf64-x86-64

Sections:
Idx Name  Size  VMA   LMA   File off  Algn
  0 .text 0006      0040  2**4
  CONTENTS, ALLOC, LOAD, READONLY, CODE
  1 .text.startup 0010      0050  2**4
  CONTENTS, ALLOC, LOAD, RELOC, READONLY, CODE
  2 .init_array.0 0008      0060  2**3
  CONTENTS, ALLOC, LOAD, RELOC, DATA
  3 .comment  006a      0068  2**0
  CONTENTS, READONLY
  4 .note.GNU-stack       00d2  2**0
  CONTENTS, READONLY
  5 .eh_frame 0058      00d8  2**3
  CONTENTS, ALLOC, LOAD, RELOC, READONLY, DATA
  6 .llvm_addrsig 0002      0238  2**0
  CONTENTS, READONLY, EXCLUDE
  7 __CLANG_OFFLOAD_BUNDLE__openmp-x86_64-pc-linux-gnu 03f8  
    0353  2**0
  CONTENTS, READONLY
  8 __CLANG_OFFLOAD_BUNDLE__host-x86_64-unknown-linux-gnu 0630  
    074b  2**0
  CONTENTS, READONLY
bash-4.2$ 
```



Repository:
  rC Clang

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

https://reviews.llvm.org/D66485



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


[PATCH] D66751: [clangd] Add targetDecl(), which determines what declaration an AST node refers to.

2019-08-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added reviewers: kadircet, ilya-biryukov.
Herald added subscribers: cfe-commits, jfb, arphaman, jkorous, MaskRay, mgorny.
Herald added a project: clang.

This is the first part of an effort to "unbundle" our libIndex use into separate
concerns (AST traversal, token<->node mapping, node<->decl mapping,
decl<->decl relationshipes).

Currently, clangd relies on libIndex to associate tokens, AST nodes, and decls.
This leads to rather convoluted implementations of e.g. hover and
extract-function, which are not naturally thought of as indexing applications.

The idea is that by decoupling different concerns, we make them easier
to use, test, and combine, and more efficient when only one part is needed.
There are some synergies between e.g. traversal and finding
relationships between decls, hopefully the benefits outweight these.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66751

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/FindTarget.cpp
  clang-tools-extra/clangd/FindTarget.h
  clang-tools-extra/clangd/unittests/ASTTests.cpp
  clang-tools-extra/clangd/unittests/CMakeLists.txt
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp

Index: clang-tools-extra/clangd/unittests/FindTargetTests.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -0,0 +1,458 @@
+//===-- FindSymbolsTests.cpp -*- C++ -*===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+#include "FindTarget.h"
+
+#include "Annotations.h"
+#include "Selection.h"
+#include "TestTU.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Testing/Support/Annotations.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+namespace clang {
+namespace clangd {
+namespace {
+
+struct PrintedDecl {
+  PrintedDecl(const char *Name, DeclRelationSet Relations = {})
+  : Name(Name), Relations(Relations) {}
+
+  std::string Name;
+  DeclRelationSet Relations;
+};
+bool operator==(const PrintedDecl &L, const PrintedDecl &R) {
+  return std::tie(L.Name, L.Relations) == std::tie(R.Name, R.Relations);
+}
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const PrintedDecl &D) {
+  return OS << D.Name << " Rel=" << D.Relations;
+}
+
+class TargetDeclTest : public ::testing::Test {
+protected:
+  using Rel = DeclRelation;
+  std::string Code;
+  std::vector Flags;
+
+  std::vector assertNodeAndPrintDecls(const char *NodeType) {
+Annotations A(Code);
+auto TU = TestTU::withCode(A.code());
+TU.ExtraArgs = Flags;
+auto AST = TU.build();
+EXPECT_THAT(AST.getDiagnostics(), ::testing::IsEmpty()) << Code;
+llvm::Annotations::Range R = A.llvm::Annotations::range();
+SelectionTree Selection(AST.getASTContext(), AST.getTokens(), R.Begin,
+R.End);
+const SelectionTree::Node *N = Selection.commonAncestor();
+if (!N) {
+  ADD_FAILURE() << "No node selected!\n" << Code;
+  return {};
+}
+EXPECT_EQ(N->kind(), NodeType) << Selection;
+
+std::vector ActualDecls;
+for (const auto &Entry : allTargetDecls(N->ASTNode)) {
+  std::string S;
+  llvm::raw_string_ostream OS(S);
+  Entry.first->print(OS);
+  llvm::StringRef FirstLine = llvm::StringRef(OS.str()).take_until(
+  [](char C) { return C == '\n'; });
+  FirstLine = FirstLine.rtrim(" {");
+  ActualDecls.emplace_back(FirstLine.str().c_str(), Entry.second);
+}
+return ActualDecls;
+  }
+};
+
+// This is a macro to preserve line numbers in assertion failures.
+// It takes the expected decls as varargs to work around comma-in-macro issues.
+#define EXPECT_DECLS(NodeType, ...)\
+  EXPECT_THAT(assertNodeAndPrintDecls(NodeType),   \
+  ::testing::UnorderedElementsAreArray(\
+  std::vector({__VA_ARGS__})))\
+  << Code
+using ExpectedDecls = std::vector;
+
+TEST_F(TargetDeclTest, Exprs) {
+  Code = R"cpp(
+int f();
+int x = [[f]]();
+  )cpp";
+  EXPECT_DECLS("DeclRefExpr", "int f()");
+
+  Code = R"cpp(
+struct S { S operator+(S) const; };
+auto X = S() [[+]] S();
+  )cpp";
+  EXPECT_DECLS("DeclRefExpr", "S operator+(S) const");
+}
+
+TEST_F(TargetDeclTest, UsingDecl) {
+  Code = R"cpp(
+namespace foo {
+  int f(int);
+  int f(char);
+}
+using foo::f;
+int x = [[f]](42);
+  )cpp";
+  // f(char) is not referenced!
+  EXPECT_DECLS("DeclRefExpr", {"using foo::f", Rel::Alias},
+   {"int f(int)", Rel::Underlying});
+
+  Code = R"cpp(
+  

[PATCH] D66502: [clang-doc] Switch Generator::CreateResources to use llvm::Error

2019-08-26 Thread Julie Hockett via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG72e1f7f960d5: [clang-doc] Switch Generator::CreateResources 
to use llvm::Error (authored by juliehockett).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66502

Files:
  clang-tools-extra/clang-doc/Generators.cpp
  clang-tools-extra/clang-doc/Generators.h
  clang-tools-extra/clang-doc/HTMLGenerator.cpp
  clang-tools-extra/clang-doc/tool/ClangDocMain.cpp

Index: clang-tools-extra/clang-doc/tool/ClangDocMain.cpp
===
--- clang-tools-extra/clang-doc/tool/ClangDocMain.cpp
+++ clang-tools-extra/clang-doc/tool/ClangDocMain.cpp
@@ -326,8 +326,11 @@
 return 1;
 
   llvm::outs() << "Generating assets for docs...\n";
-  if (!G->get()->createResources(CDCtx))
+  Err = G->get()->createResources(CDCtx);
+  if (Err) {
+llvm::errs() << toString(std::move(Err)) << "\n";
 return 1;
+  }
 
   return 0;
 }
Index: clang-tools-extra/clang-doc/HTMLGenerator.cpp
===
--- clang-tools-extra/clang-doc/HTMLGenerator.cpp
+++ clang-tools-extra/clang-doc/HTMLGenerator.cpp
@@ -829,7 +829,7 @@
 
   llvm::Error generateDocForInfo(Info *I, llvm::raw_ostream &OS,
  const ClangDocContext &CDCtx) override;
-  bool createResources(ClangDocContext &CDCtx) override;
+  llvm::Error createResources(ClangDocContext &CDCtx) override;
 };
 
 const char *HTMLGenerator::Format = "html";
@@ -883,7 +883,7 @@
   llvm_unreachable("Unknown InfoType");
 }
 
-static bool SerializeIndex(ClangDocContext &CDCtx) {
+static llvm::Error SerializeIndex(ClangDocContext &CDCtx) {
   std::error_code OK;
   std::error_code FileErr;
   llvm::SmallString<128> FilePath;
@@ -891,8 +891,9 @@
   llvm::sys::path::append(FilePath, "index_json.js");
   llvm::raw_fd_ostream OS(FilePath, FileErr, llvm::sys::fs::F_None);
   if (FileErr != OK) {
-llvm::errs() << "Error creating index file: " << FileErr.message() << "\n";
-return false;
+return llvm::make_error(
+"Error creating index file: " + FileErr.message() + "\n",
+llvm::inconvertibleErrorCode());
   }
   CDCtx.Idx.sort();
   llvm::json::OStream J(OS, 2);
@@ -911,7 +912,7 @@
   OS << "var JsonIndex = `\n";
   IndexToJSON(CDCtx.Idx);
   OS << "`;\n";
-  return true;
+  return llvm::Error::success();
 }
 
 // Generates a main HTML node that has the main content of the file that shows
@@ -932,15 +933,16 @@
   return MainNode;
 }
 
-static bool GenIndex(const ClangDocContext &CDCtx) {
+static llvm::Error GenIndex(const ClangDocContext &CDCtx) {
   std::error_code FileErr, OK;
   llvm::SmallString<128> IndexPath;
   llvm::sys::path::native(CDCtx.OutDirectory, IndexPath);
   llvm::sys::path::append(IndexPath, "index.html");
   llvm::raw_fd_ostream IndexOS(IndexPath, FileErr, llvm::sys::fs::F_None);
   if (FileErr != OK) {
-llvm::errs() << "Error creating main index: " << FileErr.message() << "\n";
-return false;
+return llvm::make_error(
+"Error creating main index: " + FileErr.message() + "\n",
+llvm::inconvertibleErrorCode());
   }
 
   HTMLFile F;
@@ -958,10 +960,10 @@
 
   F.Render(IndexOS);
 
-  return true;
+  return llvm::Error::success();
 }
 
-static bool CopyFile(StringRef FilePath, StringRef OutDirectory) {
+static llvm::Error CopyFile(StringRef FilePath, StringRef OutDirectory) {
   llvm::SmallString<128> PathWrite;
   llvm::sys::path::native(OutDirectory, PathWrite);
   llvm::sys::path::append(PathWrite, llvm::sys::path::filename(FilePath));
@@ -970,24 +972,33 @@
   std::error_code OK;
   std::error_code FileErr = llvm::sys::fs::copy_file(PathRead, PathWrite);
   if (FileErr != OK) {
-llvm::errs() << "Error creating file "
- << llvm::sys::path::filename(FilePath) << ": "
- << FileErr.message() << "\n";
-return false;
+return llvm::make_error(
+"Error creating file " + llvm::sys::path::filename(FilePath) + ": " +
+FileErr.message() + "\n",
+llvm::inconvertibleErrorCode());
   }
-  return true;
+  return llvm::Error::success();
 }
 
-bool HTMLGenerator::createResources(ClangDocContext &CDCtx) {
-  if (!SerializeIndex(CDCtx) || !GenIndex(CDCtx))
-return false;
-  for (const auto &FilePath : CDCtx.UserStylesheets)
-if (!CopyFile(FilePath, CDCtx.OutDirectory))
-  return false;
-  for (const auto &FilePath : CDCtx.FilesToCopy)
-if (!CopyFile(FilePath, CDCtx.OutDirectory))
-  return false;
-  return true;
+llvm::Error HTMLGenerator::createResources(ClangDocContext &CDCtx) {
+  auto Err = SerializeIndex(CDCtx);
+  if (Err)
+return Err;
+  Err = GenIndex(CDCtx);
+  if (Err)
+return Err;
+
+  for (const auto &FilePath : CDCtx.UserStylesheets) {
+Err = CopyFile(FilePath, CDCtx.OutDirectory);
+if (E

[PATCH] D66485: [Clang][Bundler] Use llvm-objcopy for creating fat object files

2019-08-26 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/test/Driver/clang-offload-bundler.c:233
+// RUN: clang-offload-bundler -type=o 
-targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu
 -inputs=%t.o,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.o -### 2>&1 \
+// RUN: | FileCheck %s -DHOST=%itanium_abi_triple -DINOBJ1=%t.o 
-DINOBJ2=%t.tgt1 -DINOBJ3=%t.tgt2 -DOUTOBJ=%t.bundle3.o --check-prefix 
CK-OBJ-CMD
+// CK-OBJ-CMD: llvm-objcopy{{(.exe)?}}" 
"--add-section=__CLANG_OFFLOAD_BUNDLE__host-[[HOST]]=[[INOBJ1]]" 
"--add-section=__CLANG_OFFLOAD_BUNDLE__openmp-powerpc64le-ibm-linux-gnu=[[INOBJ2]]"
 "--add-section=__CLANG_OFFLOAD_BUNDLE__openmp-x86_64-pc-linux-gnu=[[INOBJ3]]" 
"[[INOBJ1]]" "[[OUTOBJ]]"

Why does FileCheck have all these strange options?


Repository:
  rC Clang

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

https://reviews.llvm.org/D66485



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


r369926 - Fix -dA flag, it is not a preprocessor flag.

2019-08-26 Thread Erich Keane via cfe-commits
Author: erichkeane
Date: Mon Aug 26 10:00:13 2019
New Revision: 369926

URL: http://llvm.org/viewvc/llvm-project?rev=369926&view=rev
Log:
Fix -dA flag, it is not a preprocessor flag.

-dA was in the d_group, which is a preprocessor state dumping group.
However -dA is a debug flag to cause a verbose asm.  It was already
implemented to do the same thing as -fverbose-asm, so make it just be an
alias.

Modified:
cfe/trunk/docs/ClangCommandLineReference.rst
cfe/trunk/include/clang/Driver/Options.td
cfe/trunk/lib/Driver/ToolChains/Clang.cpp

Modified: cfe/trunk/docs/ClangCommandLineReference.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ClangCommandLineReference.rst?rev=369926&r1=369925&r2=369926&view=diff
==
--- cfe/trunk/docs/ClangCommandLineReference.rst (original)
+++ cfe/trunk/docs/ClangCommandLineReference.rst Mon Aug 26 10:00:13 2019
@@ -1147,8 +1147,6 @@ Flags allowing the state of the preproce
 .. option:: -d
 .. program:: clang
 
-.. option:: -dA
-
 .. option:: -dD
 
 Print macro definitions in -E mode in addition to normal output
@@ -2012,7 +2010,7 @@ Use the given vector functions library
 
 Enable the loop vectorization passes
 
-.. option:: -fverbose-asm, -fno-verbose-asm
+.. option:: -fverbose-asm, -fno-verbose-asm, -dA
 
 .. option:: -fvisibility-inlines-hidden
 

Modified: cfe/trunk/include/clang/Driver/Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=369926&r1=369925&r2=369926&view=diff
==
--- cfe/trunk/include/clang/Driver/Options.td (original)
+++ cfe/trunk/include/clang/Driver/Options.td Mon Aug 26 10:00:13 2019
@@ -595,7 +595,6 @@ def fhip_dump_offload_linker_script : Fl
   Group, Flags<[NoArgumentUnused, HelpHidden]>;
 def libomptarget_nvptx_path_EQ : Joined<["--"], "libomptarget-nvptx-path=">, 
Group,
   HelpText<"Path to libomptarget-nvptx libraries">;
-def dA : Flag<["-"], "dA">, Group;
 def dD : Flag<["-"], "dD">, Group, Flags<[CC1Option]>,
   HelpText<"Print macro definitions in -E mode in addition to normal output">;
 def dI : Flag<["-"], "dI">, Group, Flags<[CC1Option]>,
@@ -1808,6 +1807,7 @@ def fuse_init_array : Flag<["-"], "fuse-
   HelpText<"Use .init_array instead of .ctors">;
 def fno_var_tracking : Flag<["-"], "fno-var-tracking">, 
Group;
 def fverbose_asm : Flag<["-"], "fverbose-asm">, Group;
+def dA : Flag<["-"], "dA">, Alias;
 def fvisibility_EQ : Joined<["-"], "fvisibility=">, Group,
   HelpText<"Set the default symbol visibility for all global declarations">, 
Values<"hidden,default">;
 def fvisibility_inlines_hidden : Flag<["-"], "fvisibility-inlines-hidden">, 
Group,

Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=369926&r1=369925&r2=369926&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Mon Aug 26 10:00:13 2019
@@ -4080,8 +4080,7 @@ void Clang::ConstructJob(Compilation &C,
   // toolchains which have the integrated assembler on by default.
   bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
   if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
-   IsIntegratedAssemblerDefault) ||
-  Args.hasArg(options::OPT_dA))
+   IsIntegratedAssemblerDefault))
 CmdArgs.push_back("-masm-verbose");
 
   if (!TC.useIntegratedAs())


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


r369928 - [NFC] Add comments to some bool arguments for better readability

2019-08-26 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Mon Aug 26 10:03:01 2019
New Revision: 369928

URL: http://llvm.org/viewvc/llvm-project?rev=369928&view=rev
Log:
[NFC] Add comments to some bool arguments for better readability

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

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=369928&r1=369927&r2=369928&view=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Mon Aug 26 10:03:01 2019
@@ -6648,9 +6648,11 @@ static void handleGslAnnotatedTypes(Indi
 Path.push_back({IndirectLocalPathEntry::GslPointerInit, Arg, D});
 if (Arg->isGLValue())
   visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
-Visit, true);
+Visit,
+/*EnableLifetimeWarnings=*/true);
 else
-  visitLocalsRetainedByInitializer(Path, Arg, Visit, true, true);
+  visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
+   /*EnableLifetimeWarnings=*/true);
 Path.pop_back();
   };
 
@@ -6725,9 +6727,11 @@ static void visitLifetimeBoundArguments(
 Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
 if (Arg->isGLValue())
   visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
-Visit, false);
+Visit,
+/*EnableLifetimeWarnings=*/false);
 else
-  visitLocalsRetainedByInitializer(Path, Arg, Visit, true, false);
+  visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
+   /*EnableLifetimeWarnings=*/false);
 Path.pop_back();
   };
 


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


[PATCH] D66686: [LifetimeAnalysis] Make it possible to disable the new warnings

2019-08-26 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun marked an inline comment as done.
xazax.hun added inline comments.



Comment at: clang/lib/Sema/SemaInit.cpp:6651
   visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
-Visit);
+Visit, true);
 else

mgehre wrote:
> Could we have argument comments here `/*EnableLifetimeWarnings=*/true,
> and especially below where multiple bool literals are passed?
Done in r369928.


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

https://reviews.llvm.org/D66686



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


[PATCH] D66485: [Clang][Bundler] Use llvm-objcopy for creating fat object files

2019-08-26 Thread Sergey Dmitriev via Phabricator via cfe-commits
sdmitriev marked an inline comment as done.
sdmitriev added inline comments.



Comment at: clang/test/Driver/clang-offload-bundler.c:233
+// RUN: clang-offload-bundler -type=o 
-targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu
 -inputs=%t.o,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.o -### 2>&1 \
+// RUN: | FileCheck %s -DHOST=%itanium_abi_triple -DINOBJ1=%t.o 
-DINOBJ2=%t.tgt1 -DINOBJ3=%t.tgt2 -DOUTOBJ=%t.bundle3.o --check-prefix 
CK-OBJ-CMD
+// CK-OBJ-CMD: llvm-objcopy{{(.exe)?}}" 
"--add-section=__CLANG_OFFLOAD_BUNDLE__host-[[HOST]]=[[INOBJ1]]" 
"--add-section=__CLANG_OFFLOAD_BUNDLE__openmp-powerpc64le-ibm-linux-gnu=[[INOBJ2]]"
 "--add-section=__CLANG_OFFLOAD_BUNDLE__openmp-x86_64-pc-linux-gnu=[[INOBJ3]]" 
"[[INOBJ1]]" "[[OUTOBJ]]"

ABataev wrote:
> Why does FileCheck have all these strange options?
Well, -DVAR=VALUE is a standard FileCheck option which allows to define 
variable that can be used in the check pattern (please see 
http://www.llvm.org/docs/CommandGuide/FileCheck.html)

```
-D
Sets a filecheck pattern variable VAR with value VALUE that can be used in 
CHECK: lines.
```

I am using these options for defining variables which contain input and output 
object names as well as the host triple.


Repository:
  rC Clang

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

https://reviews.llvm.org/D66485



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


[PATCH] D66556: [clang-scan-deps] Minimizer: Correctly handle multi-line content with CR+LF line endings

2019-08-26 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman accepted this revision.
arphaman added a comment.
This revision is now accepted and ready to land.

LGTM


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

https://reviews.llvm.org/D66556



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


[PATCH] D66485: [Clang][Bundler] Use llvm-objcopy for creating fat object files

2019-08-26 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev accepted this revision.
ABataev added a comment.
This revision is now accepted and ready to land.

LG


Repository:
  rC Clang

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

https://reviews.llvm.org/D66485



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


[PATCH] D65907: Introduce FileEntryRef and use it when handling includes to report correct dependencies when the FileManager is reused across invocations

2019-08-26 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

In D65907#1643800 , @JamesNagurne 
wrote:

> In D65907#1643650 , @arphaman wrote:
>
> > No the windows test failure was different, there were no Deps at all. I'm 
> > currently investigating it on a windows VM.
> >
> > @JamesNagurne I think there's some issue with the working directory, which 
> > is not added in your case. Which platform are you running your build/test 
> > on? Which cmake options are you using?
>
>
> I apologize for not giving such information in the first reply. Unfortunately 
> this isn't an easy remote reproduction, as our ToolChain and some integral 
> changes aren't upstreamed. This is an embedded ARM cross-compiled on Linux. 
> Might be able to reproduce with arm-none-none-eabi.
>  LLVM is built as an external project. Looking at the build system, it looks 
> like we have the CMAKE_ARGS:
>
>  
>   -DLLVM_DEFAULT_TARGET_TRIPLE=arm-ti-none-eabi
>   -DLLVM_EXTERNAL_CLANG_SOURCE_DIR=${CMAKE_SOURCE_DIR}/llvm-project/clang
>   -DLLVM_TARGETS_TO_BUILD=ARM
>   -DCMAKE_BUILD_TYPE=Release
>   -DCMAKE_CXX_COMPILER=clang++
>   -DCMAKE_C_COMPILER=clang
>   -DLLVM_USE_LINKER=gold
>   -GNinja
>   
>
> Nothing suspicious, except maybe the default triple and ARM target.
>  Looking at our (not upstream) toolchain file, we do have some RTLibs, 
> LibInternal, libcxx, and System include changes, along with a -nostdsysteminc 
> to avoid pulling host includes into our cross compiler. However, none of this 
> should affect general "#include" behavior, correct?
>  Another glance at your changes don't seem to affect any target-specific 
> handling either, at least directly.


Yes, I don't see anything in your changes that is an obvious thing to blame.

> I might have to just bite the bullet and drop into the test with a debugger.

I fixed the Windows issue, and it was completely unrelated to your issue. It 
looks like the FileManager isn't constructing absolute paths when accessing the 
files, which is somewhat unexpected. It would be useful to debug invocations of 
`getFileEntryRef`, to see if the `InterndFilename` in the function is getting 
changed into an absolute path or not.


Repository:
  rL LLVM

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

https://reviews.llvm.org/D65907



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


[PATCH] D66705: FileManager: Use llvm::Expected in new getFileRef API

2019-08-26 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman accepted this revision.
arphaman added a comment.
This revision is now accepted and ready to land.

LGTM


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

https://reviews.llvm.org/D66705



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


[PATCH] D66713: ContentCache: Drop getBuffer's dependency on SourceManager

2019-08-26 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman accepted this revision.
arphaman added a comment.
This revision is now accepted and ready to land.

LGTM


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

https://reviews.llvm.org/D66713



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


[PATCH] D66710: ASTReader: Bypass overridden files when reading PCHs

2019-08-26 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

Missing full context


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

https://reviews.llvm.org/D66710



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


r369931 - [libclang][index][NFCi] Refactor machinery for skipping function bodies

2019-08-26 Thread Jan Korous via cfe-commits
Author: jkorous
Date: Mon Aug 26 10:25:23 2019
New Revision: 369931

URL: http://llvm.org/viewvc/llvm-project?rev=369931&view=rev
Log:
[libclang][index][NFCi] Refactor machinery for skipping function bodies

Refactor machinery for skipping inline function bodies that have already
been parsed in other frontend actions.

Preparations for moving this code to libIndex.

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

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

Modified: cfe/trunk/tools/libclang/Indexing.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/libclang/Indexing.cpp?rev=369931&r1=369930&r2=369931&view=diff
==
--- cfe/trunk/tools/libclang/Indexing.cpp (original)
+++ cfe/trunk/tools/libclang/Indexing.cpp Mon Aug 26 10:25:23 2019
@@ -120,43 +120,62 @@ namespace llvm {
 
 namespace {
 
-class SessionSkipBodyData {
+/// Keeps track of function bodies that have already been parsed.
+///
+/// Is thread-safe.
+class SharedParsedRegionsStorage {
   std::mutex Mux;
   PPRegionSetTy ParsedRegions;
 
 public:
-  ~SessionSkipBodyData() = default;
+  ~SharedParsedRegionsStorage() = default;
 
   void copyTo(PPRegionSetTy &Set) {
 std::lock_guard MG(Mux);
 Set = ParsedRegions;
   }
 
-  void update(ArrayRef Regions) {
+  void merge(ArrayRef Regions) {
 std::lock_guard MG(Mux);
 ParsedRegions.insert(Regions.begin(), Regions.end());
   }
 };
 
-class TUSkipBodyControl {
-  SessionSkipBodyData &SessionData;
+/// Provides information whether source locations have already been parsed in
+/// another FrontendAction.
+///
+/// Is NOT thread-safe.
+class ParsedSrcLocationsTracker {
+  SharedParsedRegionsStorage &ParsedRegionsStorage;
   PPConditionalDirectiveRecord &PPRec;
   Preprocessor &PP;
 
+  /// Snapshot of the shared state at the point when this instance was
+  /// constructed.
   PPRegionSetTy ParsedRegions;
+  /// Regions that were queried during this instance lifetime.
   SmallVector NewParsedRegions;
+
+  /// Caching the last queried region.
   PPRegion LastRegion;
   bool LastIsParsed;
 
 public:
-  TUSkipBodyControl(SessionSkipBodyData &sessionData,
-PPConditionalDirectiveRecord &ppRec,
-Preprocessor &pp)
-: SessionData(sessionData), PPRec(ppRec), PP(pp) {
-SessionData.copyTo(ParsedRegions);
+  /// Creates snapshot of \p ParsedRegionsStorage.
+  ParsedSrcLocationsTracker(SharedParsedRegionsStorage &ParsedRegionsStorage,
+PPConditionalDirectiveRecord &ppRec,
+Preprocessor &pp)
+  : ParsedRegionsStorage(ParsedRegionsStorage), PPRec(ppRec), PP(pp) {
+ParsedRegionsStorage.copyTo(ParsedRegions);
   }
 
-  bool isParsed(SourceLocation Loc, FileID FID, const FileEntry *FE) {
+  /// \returns true iff \p Loc has already been parsed.
+  ///
+  /// Can provide false-negative in case the location was parsed after this
+  /// instance had been constructed.
+  bool hasAlredyBeenParsed(SourceLocation Loc, FileID FID,
+   const FileEntry *FE) {
+assert(FE);
 PPRegion region = getRegion(Loc, FID, FE);
 if (region.isInvalid())
   return false;
@@ -166,40 +185,42 @@ public:
   return LastIsParsed;
 
 LastRegion = region;
+// Source locations can't be revisited during single TU parsing.
+// That means if we hit the same region again, it's a different location in
+// the same region and so the "is parsed" value from the snapshot is still
+// correct.
 LastIsParsed = ParsedRegions.count(region);
 if (!LastIsParsed)
-  NewParsedRegions.push_back(region);
+  NewParsedRegions.emplace_back(std::move(region));
 return LastIsParsed;
   }
 
-  void finished() {
-SessionData.update(NewParsedRegions);
-  }
+  /// Updates ParsedRegionsStorage with newly parsed regions.
+  void syncWithStorage() { ParsedRegionsStorage.merge(NewParsedRegions); }
 
 private:
   PPRegion getRegion(SourceLocation Loc, FileID FID, const FileEntry *FE) {
-SourceLocation RegionLoc = PPRec.findConditionalDirectiveRegionLoc(Loc);
-if (RegionLoc.isInvalid()) {
+assert(FE);
+auto Bail = [this, FE]() {
   if (isParsedOnceInclude(FE)) {
 const llvm::sys::fs::UniqueID &ID = FE->getUniqueID();
 return PPRegion(ID, 0, FE->getModificationTime());
   }
   return PPRegion();
-}
+};
 
-const SourceManager &SM = PPRec.getSourceManager();
+SourceLocation RegionLoc = PPRec.findConditionalDirectiveRegionLoc(Loc);
 assert(RegionLoc.isFileID());
+if (RegionLoc.isInvalid())
+  return Bail();
+
 FileID RegionFID;
 unsigned RegionOffset;
-std::tie(RegionFID, RegionOffset) = SM.getDecomposedLoc(RegionLoc);
+std::tie(RegionFID, RegionOffset) =
+PPRec.getSourceManager().getDecomposedLoc(RegionLoc);
 
-if (RegionFID != FID) {
-  if (isParsedOnceInclude(FE)) {
-const l

[PATCH] D66694: [libclang][index][NFCi] Refactor machinery for skipping already parsed function bodies

2019-08-26 Thread Jan Korous via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb1c90791024b: [libclang][index][NFCi] Refactor machinery for 
skipping function bodies (authored by jkorous).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66694

Files:
  clang/tools/libclang/Indexing.cpp

Index: clang/tools/libclang/Indexing.cpp
===
--- clang/tools/libclang/Indexing.cpp
+++ clang/tools/libclang/Indexing.cpp
@@ -120,43 +120,62 @@
 
 namespace {
 
-class SessionSkipBodyData {
+/// Keeps track of function bodies that have already been parsed.
+///
+/// Is thread-safe.
+class SharedParsedRegionsStorage {
   std::mutex Mux;
   PPRegionSetTy ParsedRegions;
 
 public:
-  ~SessionSkipBodyData() = default;
+  ~SharedParsedRegionsStorage() = default;
 
   void copyTo(PPRegionSetTy &Set) {
 std::lock_guard MG(Mux);
 Set = ParsedRegions;
   }
 
-  void update(ArrayRef Regions) {
+  void merge(ArrayRef Regions) {
 std::lock_guard MG(Mux);
 ParsedRegions.insert(Regions.begin(), Regions.end());
   }
 };
 
-class TUSkipBodyControl {
-  SessionSkipBodyData &SessionData;
+/// Provides information whether source locations have already been parsed in
+/// another FrontendAction.
+///
+/// Is NOT thread-safe.
+class ParsedSrcLocationsTracker {
+  SharedParsedRegionsStorage &ParsedRegionsStorage;
   PPConditionalDirectiveRecord &PPRec;
   Preprocessor &PP;
 
+  /// Snapshot of the shared state at the point when this instance was
+  /// constructed.
   PPRegionSetTy ParsedRegions;
+  /// Regions that were queried during this instance lifetime.
   SmallVector NewParsedRegions;
+
+  /// Caching the last queried region.
   PPRegion LastRegion;
   bool LastIsParsed;
 
 public:
-  TUSkipBodyControl(SessionSkipBodyData &sessionData,
-PPConditionalDirectiveRecord &ppRec,
-Preprocessor &pp)
-: SessionData(sessionData), PPRec(ppRec), PP(pp) {
-SessionData.copyTo(ParsedRegions);
+  /// Creates snapshot of \p ParsedRegionsStorage.
+  ParsedSrcLocationsTracker(SharedParsedRegionsStorage &ParsedRegionsStorage,
+PPConditionalDirectiveRecord &ppRec,
+Preprocessor &pp)
+  : ParsedRegionsStorage(ParsedRegionsStorage), PPRec(ppRec), PP(pp) {
+ParsedRegionsStorage.copyTo(ParsedRegions);
   }
 
-  bool isParsed(SourceLocation Loc, FileID FID, const FileEntry *FE) {
+  /// \returns true iff \p Loc has already been parsed.
+  ///
+  /// Can provide false-negative in case the location was parsed after this
+  /// instance had been constructed.
+  bool hasAlredyBeenParsed(SourceLocation Loc, FileID FID,
+   const FileEntry *FE) {
+assert(FE);
 PPRegion region = getRegion(Loc, FID, FE);
 if (region.isInvalid())
   return false;
@@ -166,40 +185,42 @@
   return LastIsParsed;
 
 LastRegion = region;
+// Source locations can't be revisited during single TU parsing.
+// That means if we hit the same region again, it's a different location in
+// the same region and so the "is parsed" value from the snapshot is still
+// correct.
 LastIsParsed = ParsedRegions.count(region);
 if (!LastIsParsed)
-  NewParsedRegions.push_back(region);
+  NewParsedRegions.emplace_back(std::move(region));
 return LastIsParsed;
   }
 
-  void finished() {
-SessionData.update(NewParsedRegions);
-  }
+  /// Updates ParsedRegionsStorage with newly parsed regions.
+  void syncWithStorage() { ParsedRegionsStorage.merge(NewParsedRegions); }
 
 private:
   PPRegion getRegion(SourceLocation Loc, FileID FID, const FileEntry *FE) {
-SourceLocation RegionLoc = PPRec.findConditionalDirectiveRegionLoc(Loc);
-if (RegionLoc.isInvalid()) {
+assert(FE);
+auto Bail = [this, FE]() {
   if (isParsedOnceInclude(FE)) {
 const llvm::sys::fs::UniqueID &ID = FE->getUniqueID();
 return PPRegion(ID, 0, FE->getModificationTime());
   }
   return PPRegion();
-}
+};
 
-const SourceManager &SM = PPRec.getSourceManager();
+SourceLocation RegionLoc = PPRec.findConditionalDirectiveRegionLoc(Loc);
 assert(RegionLoc.isFileID());
+if (RegionLoc.isInvalid())
+  return Bail();
+
 FileID RegionFID;
 unsigned RegionOffset;
-std::tie(RegionFID, RegionOffset) = SM.getDecomposedLoc(RegionLoc);
+std::tie(RegionFID, RegionOffset) =
+PPRec.getSourceManager().getDecomposedLoc(RegionLoc);
 
-if (RegionFID != FID) {
-  if (isParsedOnceInclude(FE)) {
-const llvm::sys::fs::UniqueID &ID = FE->getUniqueID();
-return PPRegion(ID, 0, FE->getModificationTime());
-  }
-  return PPRegion();
-}
+if (RegionFID != FID)
+  return Bail();
 
 const llvm::sys::fs::Un

[PATCH] D66627: [clang-tidy] new check: bugprone-pthread-return

2019-08-26 Thread Jian Cai via Phabricator via cfe-commits
jcai19 marked an inline comment as done.
jcai19 added a comment.

In D66627#1644775 , @gribozavr wrote:

> Thanks for the contribution! In abstract, I think it is a good checker, 
> however, the implementation largely duplicates 
> `clang-tidy/bugprone/PosixReturnCheck.cpp` -- do you think you could factor 
> out the common parts? I see at least two ways:
>
> - Factor out a library, use it in both checkers.
> - Put everything into one checker, if necessary, add configuration options to 
> turn on/off POSIX and PThread parts. However, I don't even think 
> configuration options would be necessary -- it is unlikely that someone would 
> want one but not the other -- or is there a use case?


That's a good suggestion. I will try to combine it with POSIX check. Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66627



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


r369932 - Fix use of invalidated iterator introduced by r369680.

2019-08-26 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Mon Aug 26 10:31:06 2019
New Revision: 369932

URL: http://llvm.org/viewvc/llvm-project?rev=369932&view=rev
Log:
Fix use of invalidated iterator introduced by r369680.

Modified:
cfe/trunk/lib/Basic/FileManager.cpp

Modified: cfe/trunk/lib/Basic/FileManager.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/FileManager.cpp?rev=369932&r1=369931&r2=369932&view=diff
==
--- cfe/trunk/lib/Basic/FileManager.cpp (original)
+++ cfe/trunk/lib/Basic/FileManager.cpp Mon Aug 26 10:31:06 2019
@@ -263,15 +263,15 @@ FileManager::getFileRef(StringRef Filena
   // If the name returned by getStatValue is different than Filename, re-intern
   // the name.
   if (Status.getName() != Filename) {
-auto &NamedFileEnt =
+auto &NewNamedFileEnt =
 *SeenFileEntries.insert({Status.getName(), &UFE}).first;
-assert((*NamedFileEnt.second).get() == &UFE &&
+assert((*NewNamedFileEnt.second).get() == &UFE &&
"filename from getStatValue() refers to wrong file");
-InterndFileName = NamedFileEnt.first().data();
+InterndFileName = NewNamedFileEnt.first().data();
 // In addition to re-interning the name, construct a redirecting seen file
 // entry, that will point to the name the filesystem actually wants to use.
 StringRef *Redirect = new (CanonicalNameStorage) 
StringRef(InterndFileName);
-SeenFileInsertResult.first->second = Redirect;
+NamedFileEnt.second = Redirect;
   }
 
   if (UFE.isValid()) { // Already have an entry with this inode, return it.


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


[clang-tools-extra] r369934 - [clangd] Release notes

2019-08-26 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Mon Aug 26 10:47:44 2019
New Revision: 369934

URL: http://llvm.org/viewvc/llvm-project?rev=369934&view=rev
Log:
[clangd] Release notes

Modified:
clang-tools-extra/trunk/docs/ReleaseNotes.rst

Modified: clang-tools-extra/trunk/docs/ReleaseNotes.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/ReleaseNotes.rst?rev=369934&r1=369933&r2=369934&view=diff
==
--- clang-tools-extra/trunk/docs/ReleaseNotes.rst (original)
+++ clang-tools-extra/trunk/docs/ReleaseNotes.rst Mon Aug 26 10:47:44 2019
@@ -47,7 +47,98 @@ Major New Features
 Improvements to clangd
 --
 
-The improvements are...
+- Background indexing is on by default
+
+  When using clangd, it will build an index of your code base (all files listed
+  in your compile database). This index enables go-to-definition,
+  find-references, and even code completion to find symbols across your 
project.
+
+  This feature can consume a lot of CPU. It can be disabled using the
+  ``--background-index=false`` flag, and respects ``-j`` to use fewer threads.
+  The index is written to ``.clangd/index`` in the project root.
+
+- Contextual code actions
+
+  Extract variable, expand ``auto``, expand macro, convert string to raw 
string.
+  More to come in the future!
+
+- Clang-tidy warnings are available
+
+  These will be produced for projects that have a ``.clang-tidy`` file in their
+  source tree, as described in the :doc:`clang-tidy documentation 
`.
+
+- Improved diagnostics
+
+  Errors from headers are now shown (on the #including line).
+  The message now indicates if fixes are available.
+  Navigation between errors and associated notes is improved (for editors that
+  support ``Diagnostic.relatedInformation``).
+
+- Suggested includes
+
+  When a class or other name is not found, clangd may suggest to fix this by
+  adding the corresponding ``#include`` directive.
+
+- Semantic highlighting
+
+  clangd can push syntax information to the editor, allowing it to highlight
+  e.g. member variables differently from locals. (requires editor support)
+
+  This implements the proposed protocol from
+  https://github.com/microsoft/vscode-languageserver-node/pull/367
+
+- Type hierachy
+
+  Navigation to base/derived types is possible in editors that support the
+  proposed protocol from
+  https://github.com/microsoft/vscode-languageserver-node/pull/426
+
+- Improvements to include insertion
+
+  Only headers with ``#include``-guards will be inserted, and the feature can
+  be disabled with the ``--header-insertion=never`` flag.
+
+  Standard library headers should now be inserted more accurately, particularly
+  for C++ other than libstdc++, and for the C standard library.
+
+- Code completion
+
+  Overloads are bundled into a single completion item by default. (for editors
+  that support signature-help).
+
+  Redundant const/non-const overloads are no longer shown.
+
+  Before clangd is warmed up (during preamble build), limited identifier- and
+  index-based code completion is available.
+
+- Format-on-type
+
+  A new implementation of format-on-type is triggered by hitting enter: it
+  attempts to reformat the previous line and reindent the new line.
+  (Requires editor support).
+
+- Toolchain header detection
+
+  Projects that use an embedded gcc toolchain may only work when used with the
+  corresponding standard library. clangd can now query the toolchain to find
+  these headers.
+  The compilation database must correctly specify this toolchain, and the
+  ``--query-driver=/path/to/toolchain/bin/*`` flag must be passed to clangd.
+
+- Miscellaneous improvements
+
+  Hover now produces richer Markdown-formatted text (for supported editors).
+
+  Rename is safer and more helpful, though is still within one file only.
+
+  Files without extensions (e.g. C++ standard library) are handled better.
+
+  clangd can understand offsets in UTF-8 or UTF-32 through command-line flags 
or
+  protocol extensions. (Useful with editors/platforms that don't speak UTF-16).
+
+  Editors that support edits near the cursor in code-completion can set the
+  ``textDocument.completion.editsNearCursor`` capability to ``true``, and 
clangd
+  will provide completions that correct ``.`` to ``->``, and vice-versa.
 
 Improvements to clang-doc
 -


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


Re: r369932 - Fix use of invalidated iterator introduced by r369680.

2019-08-26 Thread Alex L via cfe-commits
Thanks for the fix!

On Mon, 26 Aug 2019 at 10:29, Richard Smith via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: rsmith
> Date: Mon Aug 26 10:31:06 2019
> New Revision: 369932
>
> URL: http://llvm.org/viewvc/llvm-project?rev=369932&view=rev
> Log:
> Fix use of invalidated iterator introduced by r369680.
>
> Modified:
> cfe/trunk/lib/Basic/FileManager.cpp
>
> Modified: cfe/trunk/lib/Basic/FileManager.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/FileManager.cpp?rev=369932&r1=369931&r2=369932&view=diff
>
> ==
> --- cfe/trunk/lib/Basic/FileManager.cpp (original)
> +++ cfe/trunk/lib/Basic/FileManager.cpp Mon Aug 26 10:31:06 2019
> @@ -263,15 +263,15 @@ FileManager::getFileRef(StringRef Filena
>// If the name returned by getStatValue is different than Filename,
> re-intern
>// the name.
>if (Status.getName() != Filename) {
> -auto &NamedFileEnt =
> +auto &NewNamedFileEnt =
>  *SeenFileEntries.insert({Status.getName(), &UFE}).first;
> -assert((*NamedFileEnt.second).get() == &UFE &&
> +assert((*NewNamedFileEnt.second).get() == &UFE &&
> "filename from getStatValue() refers to wrong file");
> -InterndFileName = NamedFileEnt.first().data();
> +InterndFileName = NewNamedFileEnt.first().data();
>  // In addition to re-interning the name, construct a redirecting seen
> file
>  // entry, that will point to the name the filesystem actually wants
> to use.
>  StringRef *Redirect = new (CanonicalNameStorage)
> StringRef(InterndFileName);
> -SeenFileInsertResult.first->second = Redirect;
> +NamedFileEnt.second = Redirect;
>}
>
>if (UFE.isValid()) { // Already have an entry with this inode, return
> it.
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r369938 - [driver] add a new option `-gen-cdb-fragment-path` to emit

2019-08-26 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Mon Aug 26 10:59:41 2019
New Revision: 369938

URL: http://llvm.org/viewvc/llvm-project?rev=369938&view=rev
Log:
[driver] add a new option `-gen-cdb-fragment-path` to emit
a fragment of a compilation database for each compilation

This patch adds a new option called -gen-cdb-fragment-path to the driver,
which can be used to specify a directory path to which clang can emit a fragment
of a CDB for each compilation it needs to invoke.

This option emits the same CDB contents as -MJ, and will be ignored if -MJ is 
specified.

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

Added:
cfe/trunk/test/Driver/gen-cdb-fragment.c
Modified:
cfe/trunk/include/clang/Driver/Options.td
cfe/trunk/lib/Driver/ToolChains/Clang.cpp
cfe/trunk/lib/Driver/ToolChains/Clang.h

Modified: cfe/trunk/include/clang/Driver/Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=369938&r1=369937&r2=369938&view=diff
==
--- cfe/trunk/include/clang/Driver/Options.td (original)
+++ cfe/trunk/include/clang/Driver/Options.td Mon Aug 26 10:59:41 2019
@@ -280,6 +280,8 @@ def arcmt_migrate_emit_arc_errors : Flag
   Flags<[CC1Option]>;
 def gen_reproducer: Flag<["-"], "gen-reproducer">, InternalDebugOpt,
   HelpText<"Auto-generates preprocessed source files and a reproduction 
script">;
+def gen_cdb_fragment_path: Separate<["-"], "gen-cdb-fragment-path">, 
InternalDebugOpt,
+  HelpText<"Emit a compilation database fragment to the specified directory">;
 
 def _migrate : Flag<["--"], "migrate">, Flags<[DriverOption]>,
   HelpText<"Run the migrator">;

Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=369938&r1=369937&r2=369938&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Mon Aug 26 10:59:41 2019
@@ -2013,13 +2013,14 @@ void Clang::DumpCompilationDatabase(Comp
 CompilationDatabase = std::move(File);
   }
   auto &CDB = *CompilationDatabase;
-  SmallString<128> Buf;
-  if (llvm::sys::fs::current_path(Buf))
-Buf = ".";
-  CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
+  auto CWD = D.getVFS().getCurrentWorkingDirectory();
+  if (!CWD)
+CWD = ".";
+  CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
   CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
   CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
   CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
+  SmallString<128> Buf;
   Buf = "-x";
   Buf += types::getTypeName(Input.getType());
   CDB << ", \"" << escape(Buf) << "\"";
@@ -2037,6 +2038,8 @@ void Clang::DumpCompilationDatabase(Comp
 // Skip writing dependency output and the compilation database itself.
 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
   continue;
+if (O.getID() == options::OPT_gen_cdb_fragment_path)
+  continue;
 // Skip inputs.
 if (O.getKind() == Option::InputClass)
   continue;
@@ -2051,6 +2054,40 @@ void Clang::DumpCompilationDatabase(Comp
   CDB << ", \"" << escape(Buf) << "\"]},\n";
 }
 
+void Clang::DumpCompilationDatabaseFragmentToDir(
+StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
+const InputInfo &Input, const llvm::opt::ArgList &Args) const {
+  // If this is a dry run, do not create the compilation database file.
+  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
+return;
+
+  if (CompilationDatabase)
+DumpCompilationDatabase(C, "", Target, Output, Input, Args);
+
+  SmallString<256> Path = Dir;
+  const auto &Driver = C.getDriver();
+  Driver.getVFS().makeAbsolute(Path);
+  auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
+  if (Err) {
+Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
+return;
+  }
+
+  llvm::sys::path::append(
+  Path,
+  Twine(llvm::sys::path::filename(Input.getFilename())) + "..json");
+  int FD;
+  SmallString<256> TempPath;
+  Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath);
+  if (Err) {
+Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
+return;
+  }
+  CompilationDatabase =
+  std::make_unique(FD, /*shouldClose=*/true);
+  DumpCompilationDatabase(C, "", Target, Output, Input, Args);
+}
+
 static void CollectArgsForIntegratedAssembler(Compilation &C,
   const ArgList &Args,
   ArgStringList &CmdArgs,
@@ -3495,6 +3532,11 @@ void Clang::ConstructJob(Compilation &C,
   if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
 Args.ClaimAllArg

[PATCH] D66695: msan, codegen, instcombine: Keep more lifetime markers used for msan

2019-08-26 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis accepted this revision.
eugenis added a comment.
This revision is now accepted and ready to land.

LGTM




Comment at: llvm/test/Transforms/InstCombine/lifetime-sanitizer.ll:37-50
+define void @msan() sanitize_memory {
+entry:
+  ; CHECK-LABEL: @msan(
+  %text = alloca i8, align 1
+
+  call void @llvm.lifetime.start.p0i8(i64 1, i8* %text)
+  call void @llvm.lifetime.end.p0i8(i64 1, i8* %text)

lebedev.ri wrote:
> Would be good to have end-to-end test (`-O0`/`-O1`/`-O2`/`-O3`) in 
> PhaseOrdering.
Do you mean exact same test, but with -O0/../-O3 instead of -instcombine?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66695



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


  1   2   3   >