[PATCH] D52296: [Clang] - Add -gsingle-file-split-dwarf option.

2018-10-02 Thread George Rimar via Phabricator via cfe-commits
grimar added a comment.

Ping.


https://reviews.llvm.org/D52296



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


[PATCH] D52419: [clangd] Cache FS stat() calls when building preamble.

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

Sorry for dropping this.




Comment at: clangd/ClangdUnit.h:58
   IncludeStructure Includes;
+  std::unique_ptr StatCache;
 };

This deserves a comment, even if it's a bit repetitive.
```// Cache of FS operations performed when building the preamble.
// When reusing a preamble, this cache can be consumed to save IO.```


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52419



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


[PATCH] D50179: [AArch64][ARM] Context sensitive meaning of option "crypto"

2018-10-02 Thread Sjoerd Meijer via Phabricator via cfe-commits
SjoerdMeijer added a comment.

@efriedma : apologies for the ping, but does this look reasonable?


https://reviews.llvm.org/D50179



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


[PATCH] D52722: [analyzer] Move StdCLibraryFunctions to apiModeling

2018-10-02 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy added a subscriber: martong.
donat.nagy added a comment.

I don't have commit rights, please commit for me @NoQ or @martong


Repository:
  rC Clang

https://reviews.llvm.org/D52722



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


[PATCH] D52554: [WIP] [clangd] Tests for special methods code-completion

2018-10-02 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

The assertions themselves all look good to me.

I don't think these should be new tests, they have substantial overlap with 
TestAfterDotCompletion and should be incorporated there or those tests split up 
to reduce the duplication.
(It's hard to avoid overlap/redundancy between tests, and to do so while 
covering all cases in a systematic way, but it's important for maintenance: one 
of the reasons it's hard to find the overlapping test here is there are so 
many!)




Comment at: clangd/CodeCompleteTests.cpp:2043
 
+TEST(CompletionTestNoExplicitMembers, Struct) {
+  clangd::CodeCompleteOptions Opts;

(Should this be ImplicitMembers?)



Comment at: clangd/CodeCompleteTests.cpp:2043
 
+TEST(CompletionTestNoExplicitMembers, Struct) {
+  clangd::CodeCompleteOptions Opts;

sammccall wrote:
> (Should this be ImplicitMembers?)
nit: these cases should probably be moved up with the other code completion 
ones, and called something like `TEST(CompletionTest, NoExplicitMembers)` or so 
for consistency.

It's OK to have related tests in one test case.

In fact, this large set of closely-related cases seems like a good place for 
Go-style table-driven tests.



Comment at: clangd/CodeCompleteTests.cpp:2045
+  clangd::CodeCompleteOptions Opts;
+  Opts.Limit = 1;
+  auto ResultsDot = completions(R"cpp(

(not clear why the limit is needed?)



Comment at: clangd/CodeCompleteTests.cpp:2054
+
+  EXPECT_TRUE(ResultsDot.Completions.empty());
+

EXPECT_THAT(ResultsDot.Completions, IsEmpty())

(when the assertion fails, the failure message will print the contents of the 
container)



Comment at: clangd/CodeCompleteTests.cpp:2139
+
+TEST(CompletionTestMethodDeclared, Struct) {
+  clangd::CodeCompleteOptions Opts;

doesn't this test a strict superset of what CompletionTestNoTestMembers tests?
i.e. this also asserts that the implicit members are not included.

ISTM we could combine many of these tests (and that in fact many of them are 
covered by TestAfterDotCompletion.



Comment at: clangd/CodeCompleteTests.cpp:2150
+
+  ASSERT_TRUE(ResultsDot.Completions.size() == 1);
+  EXPECT_TRUE(ResultsDot.Completions.front().Name == "foomethod");

EXPECT_THAT(ResultsDot.Completions, ElementsAre(Named("foomethod")));

(As above, this is equivalent to the two assertions here but gives useful 
failure messages)



Comment at: clangd/CodeCompleteTests.cpp:2338
+
+TEST(CompletionTestSpecialMethodsDeclared, 
ExplicitStructTemplateSpecialization) {
+  clangd::CodeCompleteOptions Opts;

(I think we could get away with a representative set of cases, rather than 
testing the intersection of every feature. e.g. test an explicitly declared 
operator= on a struct, but combining that with an explicitly specialized struct 
template seems unneccesary)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52554



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


[PATCH] D52549: [VFS] Add a VFS wrapper which avoids opening nonexistent files by reading dirs.

2018-10-02 Thread Sam McCall via Phabricator via cfe-commits
sammccall planned changes to this revision.
sammccall marked an inline comment as done.
sammccall added a comment.

Hmm, after fixing the stat issue, this still doesn't seem to make a big 
difference on real FSes.
Putting this on hold for now.
We do have VFSes where I think this might be a win, but I'll let them try it 
out out-of-tree.


Repository:
  rC Clang

https://reviews.llvm.org/D52549



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


[PATCH] D52549: [VFS] Add a VFS wrapper which avoids opening nonexistent files by reading dirs.

2018-10-02 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 167888.
sammccall added a comment.

latest snapshot


Repository:
  rC Clang

https://reviews.llvm.org/D52549

Files:
  include/clang/Basic/VirtualFileSystem.h
  lib/Basic/AvoidStatsVFS.cpp
  lib/Basic/CMakeLists.txt
  lib/Basic/VirtualFileSystem.cpp
  unittests/Basic/VirtualFileSystemTest.cpp

Index: unittests/Basic/VirtualFileSystemTest.cpp
===
--- unittests/Basic/VirtualFileSystemTest.cpp
+++ unittests/Basic/VirtualFileSystemTest.cpp
@@ -1616,3 +1616,139 @@
 
   EXPECT_EQ(3, NumDiagnostics);
 }
+
+class AvoidStatsVFSTest : public ::testing::Test {
+ protected:
+  struct Counts {
+unsigned Status = 0;
+unsigned OpenFile = 0;
+unsigned ListDir = 0;
+  };
+  Counts Outer, Inner;
+  IntrusiveRefCntPtr MemFS;
+
+  IntrusiveRefCntPtr reset() {
+Outer = {};
+Inner = {};
+MemFS = new vfs::InMemoryFileSystem();
+return new CountingFS(
+Outer, vfs::avoidStats(new CountingFS(Inner, MemFS)).release());
+  }
+
+  void touch(const Twine &Path) {
+MemFS->addFile(Path, 0, MemoryBuffer::getMemBuffer(""));
+  }
+
+ private:
+   class CountingFS : public vfs::ProxyFileSystem {
+ Counts &C;
+
+   public:
+ CountingFS(Counts &C, IntrusiveRefCntPtr Base)
+ : ProxyFileSystem(Base), C(C) {}
+
+ llvm::ErrorOr>
+ openFileForRead(const Twine &Path) override {
+   ++C.OpenFile;
+   return ProxyFileSystem::openFileForRead(Path);
+ }
+
+ vfs::directory_iterator dir_begin(const Twine &Dir,
+   std::error_code &EC) override {
+   ++C.ListDir;
+   return ProxyFileSystem::dir_begin(Dir, EC);
+ }
+
+ llvm::ErrorOr status(const Twine &Path) override {
+   ++C.Status;
+   return ProxyFileSystem::status(Path);
+ }
+   };
+};
+
+TEST_F(AvoidStatsVFSTest, MissingFileNoStat) {
+  auto FS = reset();
+  touch("/foo/a");
+  touch("/foo/c");
+  touch("/foo/f");
+
+  EXPECT_FALSE(FS->status("/foo/a").getError()); // Just stat, /foo wanted once.
+  EXPECT_TRUE(FS->status("/foo/b").getError()); // List /foo, b known missing
+  EXPECT_FALSE(FS->status("/foo/c").getError()); // c exists, must stat
+  EXPECT_TRUE(FS->status("/foo/d").getError()); // d known missing
+  EXPECT_TRUE(FS->openFileForRead("/foo/e").getError()); // e known missing
+  EXPECT_FALSE(FS->openFileForRead("/foo/f").getError()); // f exists, must open
+
+  EXPECT_EQ(Outer.Status, 4u);
+  EXPECT_EQ(Outer.OpenFile, 2u);
+  EXPECT_EQ(Outer.ListDir, 0u);
+  EXPECT_EQ(Inner.Status, 2u);
+  EXPECT_EQ(Inner.OpenFile, 1u);
+  EXPECT_EQ(Inner.ListDir, 1u);
+}
+
+TEST_F(AvoidStatsVFSTest, ParentDirsMissing) {
+  auto FS = reset();
+  touch("/a/b/z");
+
+  EXPECT_TRUE(FS->status("/a/b/1").getError()); // Just stat.
+  EXPECT_TRUE(FS->status("/a/b/2").getError()); // List /a/b
+  EXPECT_TRUE(FS->status("/a/b/3").getError()); // Known missing
+  EXPECT_TRUE(FS->status("/a/b/c/d").getError()); // Known missing
+  EXPECT_TRUE(FS->status("/a/b/z/d").getError()); // Parent is a file
+  EXPECT_EQ(Outer.Status, 5u);
+  EXPECT_EQ(Outer.ListDir, 0u);
+  EXPECT_EQ(Inner.Status, 1u);
+  EXPECT_EQ(Inner.ListDir, 1u);
+}
+
+TEST_F(AvoidStatsVFSTest, HugeDir) {
+  auto FS = reset();
+  for (int I = 0; I < 1; ++I)
+touch("/big/" + Twine(I));
+
+  EXPECT_FALSE(FS->status("/big/1").getError());// Just stat.
+  EXPECT_FALSE(FS->status("/big/9998").getError()); // Try to list, fail, stat.
+  EXPECT_FALSE(FS->status("/big/").getError()); // stat, don't list
+  EXPECT_TRUE(FS->status("/big/10001").getError());
+  EXPECT_TRUE(FS->status("/big/x/10001").getError());
+  EXPECT_TRUE(FS->status("/big/1/10001").getError()); // missing parent in cache
+
+  EXPECT_EQ(Outer.Status, 6u);
+  EXPECT_EQ(Outer.ListDir, 0u);
+  EXPECT_EQ(Inner.Status, 5u);
+  EXPECT_EQ(Inner.ListDir, 1u);
+}
+
+TEST_F(AvoidStatsVFSTest, Duplicate) {
+  // Stat + stat on a missing file is one operation.
+  auto FS = reset();
+  EXPECT_TRUE(FS->status("/x").getError()); // Just stat.
+  EXPECT_TRUE(FS->status("/x").getError()); // No need to stat or list again.
+  EXPECT_EQ(Inner.Status, 1u);
+  EXPECT_EQ(Inner.ListDir, 0u);
+
+  // Same with open + open.
+  FS = reset();
+  EXPECT_TRUE(FS->openFileForRead("/x").getError());
+  EXPECT_TRUE(FS->openFileForRead("/x").getError());
+  EXPECT_EQ(Inner.OpenFile, 1u);
+  EXPECT_EQ(Inner.ListDir, 0u);
+
+  // And stat + open.
+  FS = reset();
+  EXPECT_TRUE(FS->status("/x").getError());
+  EXPECT_TRUE(FS->openFileForRead("/x").getError());
+  EXPECT_EQ(Inner.Status, 1u);
+  EXPECT_EQ(Inner.OpenFile, 0u);
+  EXPECT_EQ(Inner.ListDir, 0u);
+
+  // But open + stat is two: as far as open() knows, it might be a dir.
+  // We list the directory (second attempt) and see that it's not.
+  FS = reset();
+  EXPECT_TRUE(FS->openFileForRead("/x").getError());
+  EXPECT_TRUE(FS->status("/x").getError());
+  EXPECT_EQ(Inner.OpenFile, 1u);
+  EXPECT_EQ(Inner.Statu

Re: r343285 - [cxx2a] P0641R2: (Some) type mismatches on defaulted functions only

2018-10-02 Thread Stephan Bergmann via cfe-commits

On 28/09/2018 03:16, Richard Smith via cfe-commits wrote:

Author: rsmith
Date: Thu Sep 27 18:16:43 2018
New Revision: 343285

URL: http://llvm.org/viewvc/llvm-project?rev=343285&view=rev
Log:
[cxx2a] P0641R2: (Some) type mismatches on defaulted functions only
render the function deleted instead of rendering the program ill-formed.

This change also adds an enabled-by-default warning for the case where
an explicitly-defaulted special member function of a non-template class
is implicitly deleted by the type checking rules. (This fires either due
to this language change or due to pre-C++20 reasons for the member being
implicitly deleted). I've tested this on a large codebase and found only
bugs (where the program means something that's clearly different from
what the programmer intended), so this is enabled by default, but we
should revisit this if there are problems with this being enabled by
default.


Two questions on the new -Wdefaulted-function-deleted:

1  Do you have examples of actual bugs found by that?  I'm running it on 
the LibreOffice code base now and it feels like lots of just noise.  For 
example, I recently added explicitly defaulted decls of the four 
copy/move functions to lots of classes with a virtual dtor (where the 
dtor needs to be user-declared e.g. because it doesn't override any 
virtual base class dtor or because it shall not be defined inline), to 
silence GCC's new -Wdeprecated-copy.  If such a class then for example 
has a const non-static data member, Clang's -Wdefaulted-function-deleted 
now kicks in for the assignment ops.  I'm not sure whether it's better 
to have those functions explicitly deleted (which then needs revisiting 
when some details of the class change), or just explicitly defaulted and 
the compiler figure out whether its deleted or not (but which now causes 
Clang to bark), or simply not user-declared at all (but which now causes 
GCC to bark).


2  With


$ cat test.cc
struct S1 { S1 & operator =(S1 const &) = delete; };
struct S2 {
S1 m;
S2(S2 const &);
};
struct S3: S2 {
S3 & operator =(S3 const &) = default;
S3 & operator =(S3 &&) = default;
};

$ clang++ -fsyntax-only test.cc
test.cc:7:10: warning: explicitly defaulted copy assignment operator is 
implicitly deleted [-Wdefaulted-function-deleted]
S3 & operator =(S3 const &) = default;
 ^
test.cc:6:12: note: copy assignment operator of 'S3' is implicitly deleted 
because base class 'S2' has a deleted copy assignment operator
struct S3: S2 {
   ^
test.cc:3:8: note: copy assignment operator of 'S2' is implicitly deleted 
because field 'm' has a deleted copy assignment operator
S1 m;
   ^
test.cc:1:18: note: 'operator=' has been explicitly marked deleted here
struct S1 { S1 & operator =(S1 const &) = delete; };
 ^
test.cc:8:10: warning: explicitly defaulted move assignment operator is 
implicitly deleted [-Wdefaulted-function-deleted]
S3 & operator =(S3 &&) = default;
 ^
test.cc:6:12: note: move assignment operator of 'S3' is implicitly deleted 
because base class 'S2' has a deleted move assignment operator
struct S3: S2 {
   ^
test.cc:3:8: note: copy assignment operator of 'S2' is implicitly deleted 
because field 'm' has a deleted copy assignment operator
S1 m;
   ^
test.cc:1:18: note: 'operator=' has been explicitly marked deleted here
struct S1 { S1 & operator =(S1 const &) = delete; };
 ^
2 warnings generated.


the final two notes for the second warning are somewhat confusing I 
think, as there's a mismatch from the preceding note's "'S2' has a 
deleted move assignment operator" to the second-last note's "copy 
assignment operator of 'S2' is implicitly deleted".  Not sure though 
whether this is an issue specific to this new 
-Wdefaulted-function-deleted, or a general issue with generic code 
producing such "deleted because" notes.

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


[PATCH] D52647: [CodeComplete] Re-fix accessibilty of protected members from base class.

2018-10-02 Thread Eric Liu via Phabricator via cfe-commits
ioeric added a comment.
Herald added a subscriber: arphaman.

ping


Repository:
  rC Clang

https://reviews.llvm.org/D52647



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


[PATCH] D52742: [analyzer][WIP] Add macro expansions to the plist output

2018-10-02 Thread Whisperity via Phabricator via cfe-commits
whisperity added a subscriber: gamesh411.
whisperity added a comment.

Your code looks good, just minor comments going on inline.
Trying to think of more cases to test for, in case someone generously misuses 
FLMs, as seen here in an example if you scroll down a bit: 
https://gcc.gnu.org/onlinedocs/cpp/Macro-Arguments.html#Macro-Arguments
Maybe one or two tests cases for this should be added, but I believe all 
corners are covered other than this.

(The whole thing, however, is generally disgusting. I'd've expected the 
`Preprocessor` to readily contain //a lot of stuff// that's going on here.)




Comment at: include/clang/StaticAnalyzer/Core/AnalyzerOptions.h:689
 
+  /// Returns with true if macros related to the bugpath should be expanded and
+  /// included in the plist output.

Returns ~~with ~~ true



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:261
+  std::string Expansion;
+  ExpansionInfo(std::string N, std::string E) : MacroName(N), Expansion(E) {}
+};

move move move like in your other self-defined type below



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:292
+
+  // Output the location.
+  FullSourceLoc L = P.getLocation().asLocation();

the location of what?



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:298
+
+  // Output the ranges (if any).
+  ArrayRef Ranges = P.getRanges();

the ranges of what?



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:668
+/// need to expanded further when it is nested inside another macro.
+class MacroArgsInfo : public std::map {
+public:

You have two records named "MacroArgsInfo" and "MacroNameAndArgsInfo", this is 
confusing. A different name should be for this class here... maybe the later 
used `MacroArgMap` is good, and then the struct's field should be renamed 
`ArgMap` or just `Args`.



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:680
+   llvm::Optional M)
+: Name(N), MI(MI), MacroArgMap(M) {}
+};

move string argument into local member (See 
https://www.bfilipek.com/2018/08/init-string-member.html, it's fascinating and 
me and @gamesh411  just found this again yesterday night.)



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:711-712
+static ExpansionInfo getExpandedMacroImpl(SourceLocation MacroLoc,
+  const Preprocessor &PP,
+  MacroArgsInfo *PrevArgMap) {
+

Indentation of these lines is wrong.



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:723
+
+  // If this macro function-like.
+  if (MacroArgMap) {

"this is a" or "macro is function-like"



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:725
+  if (MacroArgMap) {
+// If this macro is nested inside another one, let's manually expand it's
+// arguments from the "super" macro.

its



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:726
+// If this macro is nested inside another one, let's manually expand it's
+// arguments from the "super" macro.
+if (PrevArgMap)

What's a "\"super\" macro"? Maybe "outer" (or "outermost") is the word you 
wanted to use here?



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:737
+
+  for (auto It = MI->tokens_begin(), E = MI->tokens_end(); It != E;) {
+Token T = *It;

Unnecessary `;` at the end?



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:756
+  while ((++It)->isNot(tok::r_paren)) {
+assert(It->isNot(tok::eof));
+  }

`&& "Ill-formed input: macro args were never closed!"`



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:765
+  if (MacroArgMap && MacroArgMap->count(II)) {
+for (Token ExpandedArgT : MacroArgMap->at(II)) {
+  ExpansionOS << PP.getSpelling(ExpandedArgT) + ' ';

`Token&` so copies are explicitly not created?



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:796
+  std::pair LocInfo = SM.getDecomposedLoc(ExpanLoc);
+  const char *MacroNameBuf = LocInfo.second + BufferInfo.data();
+

Okay, this looks nasty. I get that pointer offsetting is commutative, but... 
this is nasty.

Also, what's the difference between using `.data()` and `.begin()`? `Lexer`'s 
this overload takes three `const char*` params. Maybe this extra variable here 
is useless and you could just pass `BufferInfo.data() + LocInfo.second` to the 
constructor below.



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:796
+  std::pair LocInfo = SM.getDecomposedLoc(ExpanLoc);
+  const char *MacroNameBuf = LocInfo.secon

[PATCH] D52773: clang-cl: Add /showFilenames option (PR31957)

2018-10-02 Thread Hans Wennborg via Phabricator via cfe-commits
hans created this revision.
hans added reviewers: rnk, thakis, zturner, steveire.

Add a /showFilenames option for users who want clang to echo the currently 
compiled filename. MSVC does this echoing by default, and it's useful for 
showing progress in build systems that doesn't otherwise provide any progress 
report, such as MSBuild.


https://reviews.llvm.org/D52773

Files:
  include/clang/Driver/CC1Options.td
  include/clang/Driver/CLCompatOptions.td
  lib/Driver/ToolChains/Clang.cpp
  lib/Frontend/CompilerInvocation.cpp
  test/CodeGen/echo-main-filename.c
  test/Driver/cl-options.c


Index: test/Driver/cl-options.c
===
--- test/Driver/cl-options.c
+++ test/Driver/cl-options.c
@@ -294,6 +294,9 @@
 // RUN: %clang_cl /d1PP -### -- %s 2>&1 | FileCheck -check-prefix=d1PP %s
 // d1PP: -dD
 
+// RUN: %clang_cl /showFilenames -### -- %s 2>&1 | FileCheck 
-check-prefix=showFilenames %s
+// showFilenames: -echo-main-file-name
+
 // We forward any unrecognized -W diagnostic options to cc1.
 // RUN: %clang_cl -Wunused-pragmas -### -- %s 2>&1 | FileCheck 
-check-prefix=WJoined %s
 // WJoined: "-cc1"
Index: test/CodeGen/echo-main-filename.c
===
--- /dev/null
+++ test/CodeGen/echo-main-filename.c
@@ -0,0 +1,3 @@
+// RUN: %clang_cc1 -main-file-name foobar -echo-main-file-name %s -emit-llvm 
-o - | FileCheck %s
+
+// CHECK: foobar
Index: lib/Frontend/CompilerInvocation.cpp
===
--- lib/Frontend/CompilerInvocation.cpp
+++ lib/Frontend/CompilerInvocation.cpp
@@ -789,6 +789,9 @@
   Opts.PreferVectorWidth = Args.getLastArgValue(OPT_mprefer_vector_width_EQ);
 
   Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
+  if (Args.hasArg(OPT_echo_main_file_name))
+llvm::outs() << Opts.MainFileName << "\n";
+
   Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier);
 
   Opts.ControlFlowGuard = Args.hasArg(OPT_cfguard);
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -3530,6 +3530,8 @@
   // -save-temps.
   CmdArgs.push_back("-main-file-name");
   CmdArgs.push_back(getBaseInputName(Args, Input));
+  if (Arg *A = Args.getLastArg(options::OPT_echo_main_file_name))
+A->render(Args, CmdArgs);
 
   // Some flags which affect the language (via preprocessor
   // defines).
Index: include/clang/Driver/CLCompatOptions.td
===
--- include/clang/Driver/CLCompatOptions.td
+++ include/clang/Driver/CLCompatOptions.td
@@ -158,6 +158,9 @@
 def _SLASH_showIncludes : CLFlag<"showIncludes">,
   HelpText<"Print info about included files to stderr">,
   Alias;
+def _SLASH_showFilenames : CLFlag<"showFilenames">,
+  HelpText<"Print the name of each compiled file">,
+  Alias;
 def _SLASH_source_charset : CLCompileJoined<"source-charset:">,
   HelpText<"Source encoding, supports only UTF-8">, Alias;
 def _SLASH_execution_charset : CLCompileJoined<"execution-charset:">,
Index: include/clang/Driver/CC1Options.td
===
--- include/clang/Driver/CC1Options.td
+++ include/clang/Driver/CC1Options.td
@@ -636,6 +636,8 @@
 
 }
 
+def echo_main_file_name : Flag<["-"], "echo-main-file-name">,
+  HelpText<"Echo the main file name">;
 def fblocks_runtime_optional : Flag<["-"], "fblocks-runtime-optional">,
   HelpText<"Weakly link in the blocks runtime">;
 def fexternc_nounwind : Flag<["-"], "fexternc-nounwind">,


Index: test/Driver/cl-options.c
===
--- test/Driver/cl-options.c
+++ test/Driver/cl-options.c
@@ -294,6 +294,9 @@
 // RUN: %clang_cl /d1PP -### -- %s 2>&1 | FileCheck -check-prefix=d1PP %s
 // d1PP: -dD
 
+// RUN: %clang_cl /showFilenames -### -- %s 2>&1 | FileCheck -check-prefix=showFilenames %s
+// showFilenames: -echo-main-file-name
+
 // We forward any unrecognized -W diagnostic options to cc1.
 // RUN: %clang_cl -Wunused-pragmas -### -- %s 2>&1 | FileCheck -check-prefix=WJoined %s
 // WJoined: "-cc1"
Index: test/CodeGen/echo-main-filename.c
===
--- /dev/null
+++ test/CodeGen/echo-main-filename.c
@@ -0,0 +1,3 @@
+// RUN: %clang_cc1 -main-file-name foobar -echo-main-file-name %s -emit-llvm -o - | FileCheck %s
+
+// CHECK: foobar
Index: lib/Frontend/CompilerInvocation.cpp
===
--- lib/Frontend/CompilerInvocation.cpp
+++ lib/Frontend/CompilerInvocation.cpp
@@ -789,6 +789,9 @@
   Opts.PreferVectorWidth = Args.getLastArgValue(OPT_mprefer_vector_width_EQ);
 
   Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
+  if (Args.hasArg(OPT_echo_main_file_name))
+llvm::outs() << Opts.MainFileName <

[PATCH] D52715: [clangd] Dex iterator printer shows query structure, not iterator state.

2018-10-02 Thread Eric Liu via Phabricator via cfe-commits
ioeric accepted this revision.
ioeric added inline comments.
This revision is now accepted and ready to land.



Comment at: unittests/clangd/DexTests.cpp:239
+  auto Tree = createLimit(createAnd(move(I1), move(I2)), 10);
+  EXPECT_EQ(llvm::to_string(*Tree), "(LIMIT 10 (& [1 3 5] T=L2))");
 }

nit: it's not obvious in this test case that `[1 3 5]` and `T=L2` are both 
posting lists.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52715



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


[clang-tools-extra] r343564 - [clang-tidy] NFC use CHECK-NOTES in tests for cppcoreguidelines-owning-memory

2018-10-02 Thread Jonas Toth via cfe-commits
Author: jonastoth
Date: Tue Oct  2 02:38:20 2018
New Revision: 343564

URL: http://llvm.org/viewvc/llvm-project?rev=343564&view=rev
Log:
[clang-tidy] NFC use CHECK-NOTES in tests for cppcoreguidelines-owning-memory

Reviewers: alexfh, aaron.ballman, hokein

Reviewed By: alexfh

Subscribers: nemanjai, xazax.hun, kbarton, cfe-commits

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

Modified:

clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-containers.cpp
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory.cpp

Modified: 
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-containers.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-containers.cpp?rev=343564&r1=343563&r2=343564&view=diff
==
--- 
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-containers.cpp
 (original)
+++ 
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-containers.cpp
 Tue Oct  2 02:38:20 2018
@@ -37,22 +37,23 @@ int main() {
   // Rangebased looping in resource vector.
   for (auto *Element : OwnerStdVector) {
 Element = new int(42);
-// CHECK-MESSAGES: [[@LINE-1]]:5: warning: assigning newly created 
'gsl::owner<>' to non-owner 'int *'
+// CHECK-NOTES: [[@LINE-1]]:5: warning: assigning newly created 
'gsl::owner<>' to non-owner 'int *'
   }
   for (auto *Element : OwnerStdVector) {
 delete Element;
-// CHECK-MESSAGES: [[@LINE-1]]:5: warning: deleting a pointer through a 
type that is not marked 'gsl::owner<>'; consider using a smart pointer instead
-// CHECK-MESSAGES: [[@LINE-3]]:8: note: variable declared here
+// CHECK-NOTES: [[@LINE-1]]:5: warning: deleting a pointer through a type 
that is not marked 'gsl::owner<>'; consider using a smart pointer instead
+// CHECK-NOTES: [[@LINE-3]]:8: note: variable declared here
   }
 
   // Indexbased looping in resource vector.
   for (int i = 0; i < 100; ++i) {
 OwnerStdVector[i] = new int(42);
-// CHECK-MESSAGES: [[@LINE-1]]:5: warning: assigning newly created 
'gsl::owner<>' to non-owner 'int *'
+// CHECK-NOTES: [[@LINE-1]]:5: warning: assigning newly created 
'gsl::owner<>' to non-owner 'int *'
   }
   for (int i = 0; i < 100; ++i) {
 delete OwnerStdVector[i];
-// CHECK-MESSAGES: [[@LINE-1]]:5: warning: deleting a pointer through a 
type that is not marked 'gsl::owner<>'; consider using a smart pointer instead
+// CHECK-NOTES: [[@LINE-1]]:5: warning: deleting a pointer through a type 
that is not marked 'gsl::owner<>'; consider using a smart pointer instead
+// CHECK-NOTES: [[@LINE-21]]:3: note: variable declared here
 // A note gets emitted here pointing to the return value of the operator[] 
from the
 // vector implementation. Maybe this is considered misleading.
   }

Modified: 
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory.cpp?rev=343564&r1=343563&r2=343564&view=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory.cpp 
(original)
+++ clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory.cpp 
Tue Oct  2 02:38:20 2018
@@ -36,17 +36,17 @@ gsl::owner returns_owner2() { ret
 int *returns_no_owner1() { return nullptr; }
 int *returns_no_owner2() {
   return new int(42);
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: returning a newly created 
resource of type 'int *' or 'gsl::owner<>' from a function whose return type is 
not 'gsl::owner<>'
+  // CHECK-NOTES: [[@LINE-1]]:3: warning: returning a newly created resource 
of type 'int *' or 'gsl::owner<>' from a function whose return type is not 
'gsl::owner<>'
 }
 int *returns_no_owner3() {
   int *should_be_owner = new int(42);
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non-owner 'int *' 
with a newly created 'gsl::owner<>'
+  // CHECK-NOTES: [[@LINE-1]]:3: warning: initializing non-owner 'int *' with 
a newly created 'gsl::owner<>'
   return should_be_owner;
 }
 int *returns_no_owner4() {
   gsl::owner owner = new int(42);
   return owner;
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: returning a newly created 
resource of type 'int *' or 'gsl::owner<>' from a function whose return type is 
not 'gsl::owner<>'
+  // CHECK-NOTES: [[@LINE-1]]:3: warning: returning a newly created resource 
of type 'int *' or 'gsl::owner<>' from a function whose return type is not 
'gsl::owner<>'
 }
 
 unique_ptr returns_no_owner5() {
@@ -71,11 +71,11 @@ void test_assignment_and_initialization(
   int stack_int2;
 
   gsl::owner owned_int1 = &stack_int1; // BAD
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: expected initialization with 
value of type 'gsl::

r343566 - [AArch64][v8.5A] Test clang option for the Memory Tagging Extension

2018-10-02 Thread Oliver Stannard via cfe-commits
Author: olista01
Date: Tue Oct  2 02:38:59 2018
New Revision: 343566

URL: http://llvm.org/viewvc/llvm-project?rev=343566&view=rev
Log:
[AArch64][v8.5A] Test clang option for the Memory Tagging Extension

The implementation of this is in TargetParser, so we only need to add a
test for it in clang.

Patch by Pablo Barrio!

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


Added:
cfe/trunk/test/Driver/aarch64-mte.c

Added: cfe/trunk/test/Driver/aarch64-mte.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/aarch64-mte.c?rev=343566&view=auto
==
--- cfe/trunk/test/Driver/aarch64-mte.c (added)
+++ cfe/trunk/test/Driver/aarch64-mte.c Tue Oct  2 02:38:59 2018
@@ -0,0 +1,13 @@
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.4a+memtag %s 
2>&1 | FileCheck %s
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.5a+memtag %s 
2>&1 | FileCheck %s
+// CHECK: "-target-feature" "+mte"
+
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.4a+nomemtag %s 
2>&1 | FileCheck %s --check-prefix=NOMTE
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.5a+nomemtag %s 
2>&1 | FileCheck %s --check-prefix=NOMTE
+// NOMTE: "-target-feature" "-mte"
+
+// RUN: %clang -### -target aarch64-none-none-eabi %s 2>&1 | 
FileCheck %s --check-prefix=ABSENTMTE
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.4a %s 2>&1 | 
FileCheck %s --check-prefix=ABSENTMTE
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.5a %s 2>&1 | 
FileCheck %s --check-prefix=ABSENTMTE
+// ABSENTMTE-NOT: "-target-feature" "+mte"
+// ABSENTMTE-NOT: "-target-feature" "-mte"


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


[clang-tools-extra] r343565 - [clang-tidy] NFC use CHECK-NOTES in test for cppgoreguidelines-avoid-goto

2018-10-02 Thread Jonas Toth via cfe-commits
Author: jonastoth
Date: Tue Oct  2 02:38:26 2018
New Revision: 343565

URL: http://llvm.org/viewvc/llvm-project?rev=343565&view=rev
Log:
[clang-tidy] NFC use CHECK-NOTES in test for cppgoreguidelines-avoid-goto

Reviewers: alexfh, aaron.ballman, hokein

Reviewed By: alexfh

Subscribers: nemanjai, xazax.hun, kbarton, cfe-commits

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

Modified:
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-avoid-goto.cpp

Modified: 
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-avoid-goto.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-avoid-goto.cpp?rev=343565&r1=343564&r2=343565&view=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-avoid-goto.cpp 
(original)
+++ clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-avoid-goto.cpp 
Tue Oct  2 02:38:26 2018
@@ -5,8 +5,8 @@ void noop() {}
 int main() {
   noop();
   goto jump_to_me;
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: avoid using 'goto' for flow 
control
-  // CHECK-MESSAGES: [[@LINE+3]]:1: note: label defined here
+  // CHECK-NOTES: [[@LINE-1]]:3: warning: avoid using 'goto' for flow control
+  // CHECK-NOTES: [[@LINE+3]]:1: note: label defined here
   noop();
 
 jump_to_me:;
@@ -14,14 +14,14 @@ jump_to_me:;
 jump_backwards:;
   noop();
   goto jump_backwards;
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: avoid using 'goto' for flow 
control
-  // CHECK-MESSAGES: [[@LINE-4]]:1: note: label defined here
+  // CHECK-NOTES: [[@LINE-1]]:3: warning: avoid using 'goto' for flow control
+  // CHECK-NOTES: [[@LINE-4]]:1: note: label defined here
 
   goto jump_in_line;
   ;
 jump_in_line:;
-  // CHECK-MESSAGES: [[@LINE-3]]:3: warning: avoid using 'goto' for flow 
control
-  // CHECK-MESSAGES: [[@LINE-2]]:1: note: label defined here
+  // CHECK-NOTES: [[@LINE-3]]:3: warning: avoid using 'goto' for flow control
+  // CHECK-NOTES: [[@LINE-2]]:1: note: label defined here
 
   // Test the GNU extension 
https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html
 some_label:;
@@ -132,8 +132,8 @@ before_the_loop:
 for (int j = 0; j < 10; ++j) {
   if (i * j > 80)
 goto before_the_loop;
-  // CHECK-MESSAGES: [[@LINE-1]]:9: warning: avoid using 'goto' for flow 
control
-  // CHECK-MESSAGES: [[@LINE-8]]:1: note: label defined here
+  // CHECK-NOTES: [[@LINE-1]]:9: warning: avoid using 'goto' for flow 
control
+  // CHECK-NOTES: [[@LINE-8]]:1: note: label defined here
 }
   }
 }


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


[PATCH] D52493: [AArch64][v8.5A] Test clang option for the Memory Tagging Extension

2018-10-02 Thread Oliver Stannard via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC343566: [AArch64][v8.5A] Test clang option for the Memory 
Tagging Extension (authored by olista01, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D52493?vs=166910&id=167900#toc

Repository:
  rC Clang

https://reviews.llvm.org/D52493

Files:
  test/Driver/aarch64-mte.c


Index: test/Driver/aarch64-mte.c
===
--- test/Driver/aarch64-mte.c
+++ test/Driver/aarch64-mte.c
@@ -0,0 +1,13 @@
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.4a+memtag %s 
2>&1 | FileCheck %s
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.5a+memtag %s 
2>&1 | FileCheck %s
+// CHECK: "-target-feature" "+mte"
+
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.4a+nomemtag %s 
2>&1 | FileCheck %s --check-prefix=NOMTE
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.5a+nomemtag %s 
2>&1 | FileCheck %s --check-prefix=NOMTE
+// NOMTE: "-target-feature" "-mte"
+
+// RUN: %clang -### -target aarch64-none-none-eabi %s 2>&1 | 
FileCheck %s --check-prefix=ABSENTMTE
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.4a %s 2>&1 | 
FileCheck %s --check-prefix=ABSENTMTE
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.5a %s 2>&1 | 
FileCheck %s --check-prefix=ABSENTMTE
+// ABSENTMTE-NOT: "-target-feature" "+mte"
+// ABSENTMTE-NOT: "-target-feature" "-mte"


Index: test/Driver/aarch64-mte.c
===
--- test/Driver/aarch64-mte.c
+++ test/Driver/aarch64-mte.c
@@ -0,0 +1,13 @@
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.4a+memtag %s 2>&1 | FileCheck %s
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.5a+memtag %s 2>&1 | FileCheck %s
+// CHECK: "-target-feature" "+mte"
+
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.4a+nomemtag %s 2>&1 | FileCheck %s --check-prefix=NOMTE
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.5a+nomemtag %s 2>&1 | FileCheck %s --check-prefix=NOMTE
+// NOMTE: "-target-feature" "-mte"
+
+// RUN: %clang -### -target aarch64-none-none-eabi %s 2>&1 | FileCheck %s --check-prefix=ABSENTMTE
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.4a %s 2>&1 | FileCheck %s --check-prefix=ABSENTMTE
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.5a %s 2>&1 | FileCheck %s --check-prefix=ABSENTMTE
+// ABSENTMTE-NOT: "-target-feature" "+mte"
+// ABSENTMTE-NOT: "-target-feature" "-mte"
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52687: [clang-tidy] NFC use CHECK-NOTES in tests for cppcoreguidelines-owning-memory

2018-10-02 Thread Jonas Toth via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL343564: [clang-tidy] NFC use CHECK-NOTES in tests for 
cppcoreguidelines-owning-memory (authored by JonasToth, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D52687

Files:
  
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-containers.cpp
  clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory.cpp

Index: clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-containers.cpp
===
--- clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-containers.cpp
+++ clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-containers.cpp
@@ -37,22 +37,23 @@
   // Rangebased looping in resource vector.
   for (auto *Element : OwnerStdVector) {
 Element = new int(42);
-// CHECK-MESSAGES: [[@LINE-1]]:5: warning: assigning newly created 'gsl::owner<>' to non-owner 'int *'
+// CHECK-NOTES: [[@LINE-1]]:5: warning: assigning newly created 'gsl::owner<>' to non-owner 'int *'
   }
   for (auto *Element : OwnerStdVector) {
 delete Element;
-// CHECK-MESSAGES: [[@LINE-1]]:5: warning: deleting a pointer through a type that is not marked 'gsl::owner<>'; consider using a smart pointer instead
-// CHECK-MESSAGES: [[@LINE-3]]:8: note: variable declared here
+// CHECK-NOTES: [[@LINE-1]]:5: warning: deleting a pointer through a type that is not marked 'gsl::owner<>'; consider using a smart pointer instead
+// CHECK-NOTES: [[@LINE-3]]:8: note: variable declared here
   }
 
   // Indexbased looping in resource vector.
   for (int i = 0; i < 100; ++i) {
 OwnerStdVector[i] = new int(42);
-// CHECK-MESSAGES: [[@LINE-1]]:5: warning: assigning newly created 'gsl::owner<>' to non-owner 'int *'
+// CHECK-NOTES: [[@LINE-1]]:5: warning: assigning newly created 'gsl::owner<>' to non-owner 'int *'
   }
   for (int i = 0; i < 100; ++i) {
 delete OwnerStdVector[i];
-// CHECK-MESSAGES: [[@LINE-1]]:5: warning: deleting a pointer through a type that is not marked 'gsl::owner<>'; consider using a smart pointer instead
+// CHECK-NOTES: [[@LINE-1]]:5: warning: deleting a pointer through a type that is not marked 'gsl::owner<>'; consider using a smart pointer instead
+// CHECK-NOTES: [[@LINE-21]]:3: note: variable declared here
 // A note gets emitted here pointing to the return value of the operator[] from the
 // vector implementation. Maybe this is considered misleading.
   }
Index: clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory.cpp
===
--- clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory.cpp
+++ clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory.cpp
@@ -36,17 +36,17 @@
 int *returns_no_owner1() { return nullptr; }
 int *returns_no_owner2() {
   return new int(42);
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: returning a newly created resource of type 'int *' or 'gsl::owner<>' from a function whose return type is not 'gsl::owner<>'
+  // CHECK-NOTES: [[@LINE-1]]:3: warning: returning a newly created resource of type 'int *' or 'gsl::owner<>' from a function whose return type is not 'gsl::owner<>'
 }
 int *returns_no_owner3() {
   int *should_be_owner = new int(42);
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non-owner 'int *' with a newly created 'gsl::owner<>'
+  // CHECK-NOTES: [[@LINE-1]]:3: warning: initializing non-owner 'int *' with a newly created 'gsl::owner<>'
   return should_be_owner;
 }
 int *returns_no_owner4() {
   gsl::owner owner = new int(42);
   return owner;
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: returning a newly created resource of type 'int *' or 'gsl::owner<>' from a function whose return type is not 'gsl::owner<>'
+  // CHECK-NOTES: [[@LINE-1]]:3: warning: returning a newly created resource of type 'int *' or 'gsl::owner<>' from a function whose return type is not 'gsl::owner<>'
 }
 
 unique_ptr returns_no_owner5() {
@@ -71,11 +71,11 @@
   int stack_int2;
 
   gsl::owner owned_int1 = &stack_int1; // BAD
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: expected initialization with value of type 'gsl::owner<>'; got 'int *'
+  // CHECK-NOTES: [[@LINE-1]]:3: warning: expected initialization with value of type 'gsl::owner<>'; got 'int *'
 
   gsl::owner owned_int2;
   owned_int2 = &stack_int2; // BAD since no owner, bad since uninitialized
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: expected assignment source to be of type 'gsl::owner<>'; got 'int *'
+  // CHECK-NOTES: [[@LINE-1]]:3: warning: expected assignment source to be of type 'gsl::owner<>'; got 'int *'
 
   gsl::owner owned_int3 = new int(42); // Good
   owned_int3 = nullptr;   // Good
@@ -92,41 +92,41 @@
   owned_int6 = owned_int3; // BAD

[PATCH] D52686: [clang-tidy] NFC use CHECK-NOTES in test for cppgoreguidelines-avoid-goto

2018-10-02 Thread Jonas Toth via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL343565: [clang-tidy] NFC use CHECK-NOTES in test for 
cppgoreguidelines-avoid-goto (authored by JonasToth, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D52686

Files:
  clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-avoid-goto.cpp


Index: clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-avoid-goto.cpp
===
--- clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-avoid-goto.cpp
+++ clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-avoid-goto.cpp
@@ -5,23 +5,23 @@
 int main() {
   noop();
   goto jump_to_me;
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: avoid using 'goto' for flow 
control
-  // CHECK-MESSAGES: [[@LINE+3]]:1: note: label defined here
+  // CHECK-NOTES: [[@LINE-1]]:3: warning: avoid using 'goto' for flow control
+  // CHECK-NOTES: [[@LINE+3]]:1: note: label defined here
   noop();
 
 jump_to_me:;
 
 jump_backwards:;
   noop();
   goto jump_backwards;
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: avoid using 'goto' for flow 
control
-  // CHECK-MESSAGES: [[@LINE-4]]:1: note: label defined here
+  // CHECK-NOTES: [[@LINE-1]]:3: warning: avoid using 'goto' for flow control
+  // CHECK-NOTES: [[@LINE-4]]:1: note: label defined here
 
   goto jump_in_line;
   ;
 jump_in_line:;
-  // CHECK-MESSAGES: [[@LINE-3]]:3: warning: avoid using 'goto' for flow 
control
-  // CHECK-MESSAGES: [[@LINE-2]]:1: note: label defined here
+  // CHECK-NOTES: [[@LINE-3]]:3: warning: avoid using 'goto' for flow control
+  // CHECK-NOTES: [[@LINE-2]]:1: note: label defined here
 
   // Test the GNU extension 
https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html
 some_label:;
@@ -132,8 +132,8 @@
 for (int j = 0; j < 10; ++j) {
   if (i * j > 80)
 goto before_the_loop;
-  // CHECK-MESSAGES: [[@LINE-1]]:9: warning: avoid using 'goto' for flow 
control
-  // CHECK-MESSAGES: [[@LINE-8]]:1: note: label defined here
+  // CHECK-NOTES: [[@LINE-1]]:9: warning: avoid using 'goto' for flow 
control
+  // CHECK-NOTES: [[@LINE-8]]:1: note: label defined here
 }
   }
 }


Index: clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-avoid-goto.cpp
===
--- clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-avoid-goto.cpp
+++ clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-avoid-goto.cpp
@@ -5,23 +5,23 @@
 int main() {
   noop();
   goto jump_to_me;
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: avoid using 'goto' for flow control
-  // CHECK-MESSAGES: [[@LINE+3]]:1: note: label defined here
+  // CHECK-NOTES: [[@LINE-1]]:3: warning: avoid using 'goto' for flow control
+  // CHECK-NOTES: [[@LINE+3]]:1: note: label defined here
   noop();
 
 jump_to_me:;
 
 jump_backwards:;
   noop();
   goto jump_backwards;
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: avoid using 'goto' for flow control
-  // CHECK-MESSAGES: [[@LINE-4]]:1: note: label defined here
+  // CHECK-NOTES: [[@LINE-1]]:3: warning: avoid using 'goto' for flow control
+  // CHECK-NOTES: [[@LINE-4]]:1: note: label defined here
 
   goto jump_in_line;
   ;
 jump_in_line:;
-  // CHECK-MESSAGES: [[@LINE-3]]:3: warning: avoid using 'goto' for flow control
-  // CHECK-MESSAGES: [[@LINE-2]]:1: note: label defined here
+  // CHECK-NOTES: [[@LINE-3]]:3: warning: avoid using 'goto' for flow control
+  // CHECK-NOTES: [[@LINE-2]]:1: note: label defined here
 
   // Test the GNU extension https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html
 some_label:;
@@ -132,8 +132,8 @@
 for (int j = 0; j < 10; ++j) {
   if (i * j > 80)
 goto before_the_loop;
-  // CHECK-MESSAGES: [[@LINE-1]]:9: warning: avoid using 'goto' for flow control
-  // CHECK-MESSAGES: [[@LINE-8]]:1: note: label defined here
+  // CHECK-NOTES: [[@LINE-1]]:9: warning: avoid using 'goto' for flow control
+  // CHECK-NOTES: [[@LINE-8]]:1: note: label defined here
 }
   }
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r343568 - [clang] Implement Override Suggestions in Sema.

2018-10-02 Thread Kadir Cetinkaya via cfe-commits
Author: kadircet
Date: Tue Oct  2 02:42:31 2018
New Revision: 343568

URL: http://llvm.org/viewvc/llvm-project?rev=343568&view=rev
Log:
[clang] Implement Override Suggestions in Sema.

Summary:
In clangd we had a new type of completion suggestions for cpp
class/struct/unions that will show override signatures for virtual methods in
base classes. This patch implements it in sema because it is hard to deduce more
info about completion token outside of Sema and handle itchy cases.

See the patch D50898 for more info on the functionality.

In addition to above patch this one also converts the suggestion into a
CK_Pattern with whole insertion text as the name of the suggestion and factors
out CodeCompletionString generation for declerations so that it can be re-used
by others.

Reviewers: ioeric, ilya-biryukov

Reviewed By: ioeric

Subscribers: cfe-commits

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

Added:
cfe/trunk/test/CodeCompletion/overrides.cpp
Modified:
cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h
cfe/trunk/lib/Sema/SemaCodeComplete.cpp

Modified: cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h?rev=343568&r1=343567&r2=343568&view=diff
==
--- cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h (original)
+++ cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h Tue Oct  2 02:42:31 2018
@@ -946,6 +946,16 @@ public:
  CodeCompletionAllocator &Allocator,
  CodeCompletionTUInfo &CCTUInfo);
 
+  CodeCompletionString *createCodeCompletionStringForDecl(
+  Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
+  bool IncludeBriefComments, const CodeCompletionContext &CCContext,
+  PrintingPolicy &Policy);
+
+  CodeCompletionString *createCodeCompletionStringForOverride(
+  Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
+  bool IncludeBriefComments, const CodeCompletionContext &CCContext,
+  PrintingPolicy &Policy);
+
   /// Retrieve the name that should be used to order a result.
   ///
   /// If the name needs to be constructed as a string, that string will be

Modified: cfe/trunk/lib/Sema/SemaCodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaCodeComplete.cpp?rev=343568&r1=343567&r2=343568&view=diff
==
--- cfe/trunk/lib/Sema/SemaCodeComplete.cpp (original)
+++ cfe/trunk/lib/Sema/SemaCodeComplete.cpp Tue Oct  2 02:42:31 2018
@@ -1598,6 +1598,74 @@ static void AddStaticAssertResult(CodeCo
   Results.AddResult(CodeCompletionResult(Builder.TakeString()));
 }
 
+namespace {
+void printOverrideString(llvm::raw_ostream &OS, CodeCompletionString *CCS) {
+  for (const auto &C : *CCS) {
+if (C.Kind == CodeCompletionString::CK_Optional)
+  printOverrideString(OS, C.Optional);
+else
+  OS << C.Text;
+// Add a space after return type.
+if (C.Kind == CodeCompletionString::CK_ResultType)
+  OS << ' ';
+  }
+}
+} // namespace
+
+static void AddOverrideResults(ResultBuilder &Results,
+   const CodeCompletionContext &CCContext,
+   CodeCompletionBuilder &Builder) {
+  Sema &S = Results.getSema();
+  const auto *CR = llvm::dyn_cast(S.CurContext);
+  // If not inside a class/struct/union return empty.
+  if (!CR)
+return;
+  // First store overrides within current class.
+  // These are stored by name to make querying fast in the later step.
+  llvm::StringMap> Overrides;
+  for (auto *Method : CR->methods()) {
+if (!Method->isVirtual() || !Method->getIdentifier())
+  continue;
+Overrides[Method->getName()].push_back(Method);
+  }
+
+  for (const auto &Base : CR->bases()) {
+const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl();
+if (!BR)
+  continue;
+for (auto *Method : BR->methods()) {
+  if (!Method->isVirtual() || !Method->getIdentifier())
+continue;
+  const auto it = Overrides.find(Method->getName());
+  bool IsOverriden = false;
+  if (it != Overrides.end()) {
+for (auto *MD : it->second) {
+  // If the method in current body is not an overload of this virtual
+  // function, then it overrides this one.
+  if (!S.IsOverload(MD, Method, false)) {
+IsOverriden = true;
+break;
+  }
+}
+  }
+  if (!IsOverriden) {
+// Generates a new CodeCompletionResult by taking this function and
+// converting it into an override declaration with only one chunk in 
the
+// final CodeCompletionString as a TypedTextChunk.
+std::string OverrideSignature;
+llvm::raw_string_ostream OS(OverrideSignature);
+CodeCompletionResult CCR(Method, 0);

[clang-tools-extra] r343567 - [clangd] Remove override result handling logic from clangd

2018-10-02 Thread Kadir Cetinkaya via cfe-commits
Author: kadircet
Date: Tue Oct  2 02:42:17 2018
New Revision: 343567

URL: http://llvm.org/viewvc/llvm-project?rev=343567&view=rev
Log:
[clangd] Remove override result handling logic from clangd

Summary:
Since we plan to move handling of override suggestions to Sema with
D52225 this patch just makes sure clangd-side has no logic related to that
anymore and updates tests.

Reviewers: ioeric, ilya-biryukov

Reviewed By: ioeric

Subscribers: MaskRay, jkorous, arphaman, cfe-commits

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

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

Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=343567&r1=343566&r2=343567&view=diff
==
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Tue Oct  2 02:42:17 2018
@@ -199,55 +199,6 @@ static llvm::Expected toHead
   return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
 }
 
-// First traverses all method definitions inside current class/struct/union
-// definition. Than traverses base classes to find virtual methods that haven't
-// been overriden within current context.
-// FIXME(kadircet): Currently we cannot see declarations below completion 
point.
-// It is because Sema gets run only upto completion point. Need to find a
-// solution to run it for the whole class/struct/union definition.
-static std::vector
-getNonOverridenMethodCompletionResults(const DeclContext *DC, Sema *S) {
-  const auto *CR = llvm::dyn_cast(DC);
-  // If not inside a class/struct/union return empty.
-  if (!CR)
-return {};
-  // First store overrides within current class.
-  // These are stored by name to make querying fast in the later step.
-  llvm::StringMap> Overrides;
-  for (auto *Method : CR->methods()) {
-if (!Method->isVirtual() || !Method->getIdentifier())
-  continue;
-Overrides[Method->getName()].push_back(Method);
-  }
-
-  std::vector Results;
-  for (const auto &Base : CR->bases()) {
-const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl();
-if (!BR)
-  continue;
-for (auto *Method : BR->methods()) {
-  if (!Method->isVirtual() || !Method->getIdentifier())
-continue;
-  const auto it = Overrides.find(Method->getName());
-  bool IsOverriden = false;
-  if (it != Overrides.end()) {
-for (auto *MD : it->second) {
-  // If the method in current body is not an overload of this virtual
-  // function, then it overrides this one.
-  if (!S->IsOverload(MD, Method, false)) {
-IsOverriden = true;
-break;
-  }
-}
-  }
-  if (!IsOverriden)
-Results.emplace_back(Method, 0);
-}
-  }
-
-  return Results;
-}
-
 /// A code completion result, in clang-native form.
 /// It may be promoted to a CompletionItem if it's among the top-ranked 
results.
 struct CompletionCandidate {
@@ -257,9 +208,6 @@ struct CompletionCandidate {
   const Symbol *IndexResult = nullptr;
   llvm::SmallVector RankedIncludeHeaders;
 
-  // States whether this item is an override suggestion.
-  bool IsOverride = false;
-
   // Returns a token identifying the overload set this is part of.
   // 0 indicates it's not part of any overload set.
   size_t overloadSet() const {
@@ -447,8 +395,6 @@ struct CodeCompletionBuilder {
 Completion.Documentation = getDocComment(ASTCtx, *C.SemaResult,
  /*CommentsFromHeader=*/false);
 }
-if (C.IsOverride)
-  S.OverrideSuffix = true;
   }
 
   CodeCompletion build() {
@@ -456,12 +402,6 @@ struct CodeCompletionBuilder {
 Completion.Signature = summarizeSignature();
 Completion.SnippetSuffix = summarizeSnippet();
 Completion.BundleSize = Bundled.size();
-if (summarizeOverride()) {
-  Completion.Name = Completion.ReturnType + ' ' +
-std::move(Completion.Name) +
-std::move(Completion.Signature) + " override";
-  Completion.Signature.clear();
-}
 return std::move(Completion);
   }
 
@@ -470,7 +410,6 @@ private:
 std::string SnippetSuffix;
 std::string Signature;
 std::string ReturnType;
-bool OverrideSuffix;
   };
 
   // If all BundledEntrys have the same value for a property, return it.
@@ -548,12 +487,6 @@ private:
 return "(…)";
   }
 
-  bool summarizeOverride() const {
-if (auto *OverrideSuffix = onlyValue<&BundledEntry::OverrideSuffix>())
-  return *OverrideSuffix;
-return false;
-  }
-
   ASTContext &ASTCtx;
   CodeCompletion Completion;
   SmallVector Bundled;
@@ -1418,11 +1351,8 @@ private:
 ? queryIndex()
 : SymbolSlab();
 trace::Span Tracer("Populate CodeCompleteResult");
-// Merge S

[PATCH] D52226: [clangd] Remove override result handling logic from clangd

2018-10-02 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE343567: [clangd] Remove override result handling logic 
from clangd (authored by kadircet, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D52226?vs=167075&id=167901#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52226

Files:
  clangd/CodeComplete.cpp

Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -199,55 +199,6 @@
   return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
 }
 
-// First traverses all method definitions inside current class/struct/union
-// definition. Than traverses base classes to find virtual methods that haven't
-// been overriden within current context.
-// FIXME(kadircet): Currently we cannot see declarations below completion point.
-// It is because Sema gets run only upto completion point. Need to find a
-// solution to run it for the whole class/struct/union definition.
-static std::vector
-getNonOverridenMethodCompletionResults(const DeclContext *DC, Sema *S) {
-  const auto *CR = llvm::dyn_cast(DC);
-  // If not inside a class/struct/union return empty.
-  if (!CR)
-return {};
-  // First store overrides within current class.
-  // These are stored by name to make querying fast in the later step.
-  llvm::StringMap> Overrides;
-  for (auto *Method : CR->methods()) {
-if (!Method->isVirtual() || !Method->getIdentifier())
-  continue;
-Overrides[Method->getName()].push_back(Method);
-  }
-
-  std::vector Results;
-  for (const auto &Base : CR->bases()) {
-const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl();
-if (!BR)
-  continue;
-for (auto *Method : BR->methods()) {
-  if (!Method->isVirtual() || !Method->getIdentifier())
-continue;
-  const auto it = Overrides.find(Method->getName());
-  bool IsOverriden = false;
-  if (it != Overrides.end()) {
-for (auto *MD : it->second) {
-  // If the method in current body is not an overload of this virtual
-  // function, then it overrides this one.
-  if (!S->IsOverload(MD, Method, false)) {
-IsOverriden = true;
-break;
-  }
-}
-  }
-  if (!IsOverriden)
-Results.emplace_back(Method, 0);
-}
-  }
-
-  return Results;
-}
-
 /// A code completion result, in clang-native form.
 /// It may be promoted to a CompletionItem if it's among the top-ranked results.
 struct CompletionCandidate {
@@ -257,9 +208,6 @@
   const Symbol *IndexResult = nullptr;
   llvm::SmallVector RankedIncludeHeaders;
 
-  // States whether this item is an override suggestion.
-  bool IsOverride = false;
-
   // Returns a token identifying the overload set this is part of.
   // 0 indicates it's not part of any overload set.
   size_t overloadSet() const {
@@ -447,30 +395,21 @@
 Completion.Documentation = getDocComment(ASTCtx, *C.SemaResult,
  /*CommentsFromHeader=*/false);
 }
-if (C.IsOverride)
-  S.OverrideSuffix = true;
   }
 
   CodeCompletion build() {
 Completion.ReturnType = summarizeReturnType();
 Completion.Signature = summarizeSignature();
 Completion.SnippetSuffix = summarizeSnippet();
 Completion.BundleSize = Bundled.size();
-if (summarizeOverride()) {
-  Completion.Name = Completion.ReturnType + ' ' +
-std::move(Completion.Name) +
-std::move(Completion.Signature) + " override";
-  Completion.Signature.clear();
-}
 return std::move(Completion);
   }
 
 private:
   struct BundledEntry {
 std::string SnippetSuffix;
 std::string Signature;
 std::string ReturnType;
-bool OverrideSuffix;
   };
 
   // If all BundledEntrys have the same value for a property, return it.
@@ -548,12 +487,6 @@
 return "(…)";
   }
 
-  bool summarizeOverride() const {
-if (auto *OverrideSuffix = onlyValue<&BundledEntry::OverrideSuffix>())
-  return *OverrideSuffix;
-return false;
-  }
-
   ASTContext &ASTCtx;
   CodeCompletion Completion;
   SmallVector Bundled;
@@ -1418,11 +1351,8 @@
 ? queryIndex()
 : SymbolSlab();
 trace::Span Tracer("Populate CodeCompleteResult");
-// Merge Sema, Index and Override results, score them, and pick the
-// winners.
-const auto Overrides = getNonOverridenMethodCompletionResults(
-Recorder->CCSema->CurContext, Recorder->CCSema);
-auto Top = mergeResults(Recorder->Results, IndexResults, Overrides);
+// Merge Sema and Index results, score them, and pick the winners.
+auto Top = mergeResults(Recorder->Results, IndexResults);
 CodeCompleteResult Output;
 
 // Convert the results to final form, assembling the expensive strings.
@@ -1474,26 +1404,22 @@
 return std::move(R

[PATCH] D52225: [clang] Implement Override Suggestions in Sema.

2018-10-02 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC343568: [clang] Implement Override Suggestions in Sema. 
(authored by kadircet, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D52225?vs=167717&id=167902#toc

Repository:
  rC Clang

https://reviews.llvm.org/D52225

Files:
  include/clang/Sema/CodeCompleteConsumer.h
  lib/Sema/SemaCodeComplete.cpp
  test/CodeCompletion/overrides.cpp

Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -1598,6 +1598,74 @@
   Results.AddResult(CodeCompletionResult(Builder.TakeString()));
 }
 
+namespace {
+void printOverrideString(llvm::raw_ostream &OS, CodeCompletionString *CCS) {
+  for (const auto &C : *CCS) {
+if (C.Kind == CodeCompletionString::CK_Optional)
+  printOverrideString(OS, C.Optional);
+else
+  OS << C.Text;
+// Add a space after return type.
+if (C.Kind == CodeCompletionString::CK_ResultType)
+  OS << ' ';
+  }
+}
+} // namespace
+
+static void AddOverrideResults(ResultBuilder &Results,
+   const CodeCompletionContext &CCContext,
+   CodeCompletionBuilder &Builder) {
+  Sema &S = Results.getSema();
+  const auto *CR = llvm::dyn_cast(S.CurContext);
+  // If not inside a class/struct/union return empty.
+  if (!CR)
+return;
+  // First store overrides within current class.
+  // These are stored by name to make querying fast in the later step.
+  llvm::StringMap> Overrides;
+  for (auto *Method : CR->methods()) {
+if (!Method->isVirtual() || !Method->getIdentifier())
+  continue;
+Overrides[Method->getName()].push_back(Method);
+  }
+
+  for (const auto &Base : CR->bases()) {
+const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl();
+if (!BR)
+  continue;
+for (auto *Method : BR->methods()) {
+  if (!Method->isVirtual() || !Method->getIdentifier())
+continue;
+  const auto it = Overrides.find(Method->getName());
+  bool IsOverriden = false;
+  if (it != Overrides.end()) {
+for (auto *MD : it->second) {
+  // If the method in current body is not an overload of this virtual
+  // function, then it overrides this one.
+  if (!S.IsOverload(MD, Method, false)) {
+IsOverriden = true;
+break;
+  }
+}
+  }
+  if (!IsOverriden) {
+// Generates a new CodeCompletionResult by taking this function and
+// converting it into an override declaration with only one chunk in the
+// final CodeCompletionString as a TypedTextChunk.
+std::string OverrideSignature;
+llvm::raw_string_ostream OS(OverrideSignature);
+CodeCompletionResult CCR(Method, 0);
+PrintingPolicy Policy =
+getCompletionPrintingPolicy(S.getASTContext(), S.getPreprocessor());
+auto *CCS = CCR.createCodeCompletionStringForOverride(
+S.getPreprocessor(), S.getASTContext(), Builder,
+/*IncludeBriefComments=*/false, CCContext, Policy);
+Results.AddResult(CodeCompletionResult(CCS, Method, CCP_CodePattern));
+  }
+}
+  }
+}
+
 /// Add language constructs that show up for "ordinary" names.
 static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
Scope *S,
@@ -1706,6 +1774,12 @@
 if (IsNotInheritanceScope && Results.includeCodePatterns())
   Builder.AddChunk(CodeCompletionString::CK_Colon);
 Results.AddResult(Result(Builder.TakeString()));
+
+// FIXME: This adds override results only if we are at the first word of
+// the declaration/definition. Also call this from other sides to have
+// more use-cases.
+AddOverrideResults(Results, CodeCompletionContext::CCC_ClassStructUnion,
+   Builder);
   }
 }
 LLVM_FALLTHROUGH;
@@ -2834,6 +2908,30 @@
 return Result.TakeString();
   }
   assert(Kind == RK_Declaration && "Missed a result kind?");
+  return createCodeCompletionStringForDecl(PP, Ctx, Result, IncludeBriefComments,
+CCContext, Policy);
+}
+
+CodeCompletionString *
+CodeCompletionResult::createCodeCompletionStringForOverride(
+Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
+bool IncludeBriefComments, const CodeCompletionContext &CCContext,
+PrintingPolicy &Policy) {
+  std::string OverrideSignature;
+  llvm::raw_string_ostream OS(OverrideSignature);
+  auto *CCS = createCodeCompletionStringForDecl(PP, Ctx, Result,
+/*IncludeBriefComments=*/false,
+CCContext, Policy);
+  printOverrideString(OS, CCS);
+  OS << " override";
+  Result.AddTypedTextChunk(Result.getAllocator().CopyString(OS.str()));
+ 

[PATCH] D52727: [clang-tidy] White List Option for performance-unnecessary-value-param, performance-unnecessary-copy-initialization and performance-for-range-copy

2018-10-02 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added inline comments.



Comment at: clang-tidy/performance/ForRangeCopyCheck.cpp:49
+  // Skip whitelisted types
+  const auto VarType = Var->getType();
+  if (std::find_if(WhiteListTypes.begin(), WhiteListTypes.end(),

lebedev.ri wrote:
> I'm not sure what is `auto` here, please spell `QualType`.
And please elide `const`, as it is a value and values are not made `const` in 
llvm code (consistency for now)



Comment at: clang-tidy/performance/ForRangeCopyCheck.cpp:50
+  const auto VarType = Var->getType();
+  if (std::find_if(WhiteListTypes.begin(), WhiteListTypes.end(),
+   [&](llvm::StringRef WhiteListType) {

lebedev.ri wrote:
> `llvm::any_of()`
This configuration should be used in the matchers. Please see 
`cppcoreguidelines-no-malloc` for an example on how to do it in the matchers. 
Having it there usually improves performance and is clearer.



Comment at: clang-tidy/performance/UnnecessaryValueParamCheck.cpp:110
+
+  const bool IsConstQualified = 
ParamType.getCanonicalType().isConstQualified();
 

please remove the `const`



Comment at: docs/clang-tidy/checks/performance-for-range-copy.rst:31
+
+   A semicolon-separated list of names of whitelist types. Regular expressions
+   are allowed. Default is empty.

Please give an example for regular expressions. There are many slightly 
different variations of them and not everyone might be familiar. I think one 
wildcard expression is enough.

The sentences miss some fill words i think. `whitelisted types`, `The default 
is empty`.



Comment at: 
docs/clang-tidy/checks/performance-unnecessary-copy-initialization.rst:44
+
+   A semicolon-separated list of names of whitelist types. Regular expressions
+   are allowed. Default is empty.

Same as other doc, same below



Comment at: test/clang-tidy/performance-for-range-copy.cpp:1
-// RUN: %check_clang_tidy %s performance-for-range-copy %t -- -- -std=c++11 
-fno-delayed-template-parsing
+// RUN: %check_clang_tidy %s performance-for-range-copy %t -- 
-config="{CheckOptions: [{key: performance-for-range-copy.WhiteListTypes, 
value: '[Pp]ointer$|[Pp]tr$|[Rr]ef(erence)?$'}]}" -- -std=c++11 
-fno-delayed-template-parsing
 

I would prefer 2 test files. One with default configuration and one with the 
special whitelisting, same for the other checks


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52727



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


[PATCH] D52774: [Preprocessor] Fix an assertion failure trigged in clangd #include completion.

2018-10-02 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added subscribers: kadircet, arphaman, jkorous, MaskRay, ioeric, 
ilya-biryukov.

- Fix an assertion, the Filename should fallback to the written name in

the code if the correct typo heuristic fails.

- Fix an inconsistent issue of NormalizedPath and Filename, NormalizedPath 
should

always correspond to the Filename. Previously, NormalizedPath was the old one 
if we find a
file after typo correction.

I checked the Filename usage after the typo correct code, it seems expected.
The "check-clang" test is passed, so I believe this change doesn't introduce
any unexpected functional change.

The test is added in extra repo. I tried to add the test to clang's code
completion test, it doesn't reporduce the crash like clangd.


Repository:
  rC Clang

https://reviews.llvm.org/D52774

Files:
  lib/Lex/PPDirectives.cpp


Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -1833,13 +1833,18 @@
   // the path.
   ModuleMap::KnownHeader SuggestedModule;
   SourceLocation FilenameLoc = FilenameTok.getLocation();
-  SmallString<128> NormalizedPath;
-  if (LangOpts.MSVCCompat) {
-NormalizedPath = Filename.str();
+  auto NormalizePathForMSVCCompat = [this](llvm::StringRef FilePath) {
+SmallString<128> NormalizedPath;
+if (!LangOpts.MSVCCompat)
+  return NormalizedPath;
+NormalizedPath = FilePath;
 #ifndef _WIN32
 llvm::sys::path::native(NormalizedPath);
 #endif
-  }
+return NormalizedPath;
+  };
+  SmallString<128> NormalizedPath = NormalizePathForMSVCCompat(Filename);
+
   const FileEntry *File = LookupFile(
   FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename,
   isAngled, LookupFrom, LookupFromFile, CurDir,
@@ -1887,7 +1892,6 @@
 
   // Check for likely typos due to leading or trailing non-isAlphanumeric
   // characters
-  StringRef OriginalFilename = Filename;
   if (!File) {
 // A heuristic to correct a typo file name by removing leading and
 // trailing non-isAlphanumeric characters.
@@ -1898,27 +1902,35 @@
   }
   return Filename;
 };
-Filename = CorrectTypoFilename(Filename);
+StringRef TypoCorrectionName = CorrectTypoFilename(Filename);
+auto NormalizedTypoCorrectionName =
+NormalizePathForMSVCCompat(TypoCorrectionName);
 File = LookupFile(
 FilenameLoc,
-LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
-LookupFrom, LookupFromFile, CurDir,
+LangOpts.MSVCCompat ? NormalizedTypoCorrectionName.c_str()
+: TypoCorrectionName,
+isAngled, LookupFrom, LookupFromFile, CurDir,
 Callbacks ? &SearchPath : nullptr,
 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped);
 if (File) {
   SourceRange Range(FilenameTok.getLocation(), CharEnd);
-  auto Hint = isAngled ? FixItHint::CreateReplacement(
- Range, "<" + Filename.str() + ">")
-   : FixItHint::CreateReplacement(
- Range, "\"" + Filename.str() + "\"");
+  auto Hint = isAngled
+  ? FixItHint::CreateReplacement(
+Range, "<" + TypoCorrectionName.str() + ">")
+  : FixItHint::CreateReplacement(
+Range, "\"" + TypoCorrectionName.str() + "\"");
   Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
-  << OriginalFilename << Filename << Hint;
+  << Filename << TypoCorrectionName << Hint;
+  // We found the file, so set the Filename and NormalizedPath to the
+  // name after typo correction.
+  Filename = TypoCorrectionName;
+  NormalizedPath = NormalizedTypoCorrectionName;
 }
   }
 
   // If the file is still not found, just go with the vanilla diagnostic
   if (!File)
-Diag(FilenameTok, diag::err_pp_file_not_found) << OriginalFilename
+Diag(FilenameTok, diag::err_pp_file_not_found) << Filename
<< FilenameRange;
 }
   }


Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -1833,13 +1833,18 @@
   // the path.
   ModuleMap::KnownHeader SuggestedModule;
   SourceLocation FilenameLoc = FilenameTok.getLocation();
-  SmallString<128> NormalizedPath;
-  if (LangOpts.MSVCCompat) {
-NormalizedPath = Filename.str();
+  auto NormalizePathForMSVCCompat = [this](llvm::StringRef FilePath) {
+SmallString<128> NormalizedPath;
+if (!LangOpts.MSVCCompat)
+  return NormalizedPath;
+Normaliz

[PATCH] D52775: [clangd] Add a #include completion test that triggers an assertion.

2018-10-02 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added subscribers: kadircet, arphaman, jkorous, MaskRay, ioeric, 
ilya-biryukov.

Test for https://reviews.llvm.org/D52774.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52775

Files:
  unittests/clangd/CodeCompleteTests.cpp


Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -2093,6 +2093,15 @@
 Has("bar.h\"", CompletionItemKind::File)));
 }
 
+TEST(CompletionTest, NoCrashAtNonAlphaIncludeHeader) {
+  auto Results = completions(
+  R"cpp(
+#include "./^"
+  )cpp"
+  );
+  EXPECT_TRUE(Results.Completions.empty());
+}
+
 TEST(CompletionTest, NoAllScopesCompletionWhenQualified) {
   clangd::CodeCompleteOptions Opts = {};
   Opts.AllScopes = true;


Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -2093,6 +2093,15 @@
 Has("bar.h\"", CompletionItemKind::File)));
 }
 
+TEST(CompletionTest, NoCrashAtNonAlphaIncludeHeader) {
+  auto Results = completions(
+  R"cpp(
+#include "./^"
+  )cpp"
+  );
+  EXPECT_TRUE(Results.Completions.empty());
+}
+
 TEST(CompletionTest, NoAllScopesCompletionWhenQualified) {
   clangd::CodeCompleteOptions Opts = {};
   Opts.AllScopes = true;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r343285 - [cxx2a] P0641R2: (Some) type mismatches on defaulted functions only

2018-10-02 Thread Hans Wennborg via cfe-commits
I'm confused about what implicitly deleted means. In this code for example:

struct S {
  S(const S&) = default;
  S& operator=(const S&) = default;
  const int x;
};

void f(S &s) {
  S t = s;
}

Clang will warn that operator= is implicitly deleted.

But it seems the code still works fine, whereas if operator= were
actually deleted it would not compile. So what does implicitly deleted
mean then?


On Fri, Sep 28, 2018 at 3:16 AM, Richard Smith via cfe-commits
 wrote:
> Author: rsmith
> Date: Thu Sep 27 18:16:43 2018
> New Revision: 343285
>
> URL: http://llvm.org/viewvc/llvm-project?rev=343285&view=rev
> Log:
> [cxx2a] P0641R2: (Some) type mismatches on defaulted functions only
> render the function deleted instead of rendering the program ill-formed.
>
> This change also adds an enabled-by-default warning for the case where
> an explicitly-defaulted special member function of a non-template class
> is implicitly deleted by the type checking rules. (This fires either due
> to this language change or due to pre-C++20 reasons for the member being
> implicitly deleted). I've tested this on a large codebase and found only
> bugs (where the program means something that's clearly different from
> what the programmer intended), so this is enabled by default, but we
> should revisit this if there are problems with this being enabled by
> default.
>
> Modified:
> cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
> cfe/trunk/lib/Sema/SemaDeclCXX.cpp
> cfe/trunk/test/CXX/class.derived/class.abstract/p16.cpp
> cfe/trunk/test/CXX/dcl.decl/dcl.fct.def/dcl.fct.def.default/p1.cpp
> cfe/trunk/test/CXX/drs/dr6xx.cpp
> cfe/trunk/test/CXX/special/class.copy/p12-0x.cpp
> cfe/trunk/test/CXX/special/class.copy/p23-cxx11.cpp
> cfe/trunk/test/CXX/special/class.ctor/p5-0x.cpp
> cfe/trunk/test/CXX/special/class.dtor/p5-0x.cpp
> cfe/trunk/test/SemaCUDA/implicit-member-target.cu
> cfe/trunk/test/SemaCXX/cxx0x-deleted-default-ctor.cpp
> cfe/trunk/test/SemaCXX/cxx17-compat.cpp
> cfe/trunk/test/SemaCXX/dr1301.cpp
> cfe/trunk/test/SemaCXX/microsoft-dtor-lookup-cxx11.cpp
> cfe/trunk/test/SemaTemplate/exception-spec-crash.cpp
> cfe/trunk/www/cxx_status.html
>
> Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=343285&r1=343284&r2=343285&view=diff
> ==
> --- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
> +++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Thu Sep 27 18:16:43 
> 2018
> @@ -7760,9 +7760,19 @@ def err_incorrect_defaulted_exception_sp
>  def err_incorrect_defaulted_constexpr : Error<
>"defaulted definition of %sub{select_special_member_kind}0 "
>"is not constexpr">;
> +def warn_defaulted_method_deleted : Warning<
> +  "explicitly defaulted %sub{select_special_member_kind}0 is implicitly "
> +  "deleted">, InGroup>;
>  def err_out_of_line_default_deletes : Error<
>"defaulting this %sub{select_special_member_kind}0 "
>"would delete it after its first declaration">;
> +def note_deleted_type_mismatch : Note<
> +  "function is implicitly deleted because its declared type does not match "
> +  "the type of an implicit %sub{select_special_member_kind}0">;
> +def warn_cxx17_compat_defaulted_method_type_mismatch : Warning<
> +  "explicitly defaulting this %sub{select_special_member_kind}0 with a type "
> +  "different from the implicit type is incompatible with C++ standards 
> before "
> +  "C++2a">, InGroup, DefaultIgnore;
>  def warn_vbase_moved_multiple_times : Warning<
>"defaulted move assignment operator of %0 will move assign virtual base "
>"class %1 multiple times">, InGroup>;
>
> Modified: cfe/trunk/lib/Sema/SemaDeclCXX.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclCXX.cpp?rev=343285&r1=343284&r2=343285&view=diff
> ==
> --- cfe/trunk/lib/Sema/SemaDeclCXX.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaDeclCXX.cpp Thu Sep 27 18:16:43 2018
> @@ -6451,20 +6451,29 @@ void Sema::CheckExplicitlyDefaultedSpeci
>//copy operation can take a non-const reference) as an implicit
>//declaration, and
>// -- not have default arguments.
> +  // C++2a changes the second bullet to instead delete the function if it's
> +  // defaulted on its first declaration, unless it's "an assignment operator,
> +  // and its return type differs or its parameter type is not a reference".
> +  bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
> +  bool ShouldDeleteForTypeMismatch = false;
>unsigned ExpectedParams = 1;
>if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
>  ExpectedParams = 0;
>if (MD->getNumParams() != ExpectedParams) {
> -// This also checks for default arguments: a cop

[PATCH] D52774: [Preprocessor] Fix an assertion failure trigged in clangd #include completion.

2018-10-02 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

For reference, the crash stack is like:

  ClangdTests: ../include/llvm/ADT/StringSet.h:39: std::pair 
llvm::StringSet::insert(llvm::StringRef) [AllocatorTy = 
llvm::MallocAllocator]: Assertion `!Key.empty()' failed.
  #0 0x0061e5ff llvm::sys::PrintStackTrace(llvm::raw_ostream&) 
/llvm-upstream/build/../lib/Support/Unix/Signals.inc:490:13
  #1 0x0061c942 llvm::sys::RunSignalHandlers() 
llvm-upstream/build/../lib/Support/Signals.cpp:68:18
  #2 0x0061e942 SignalHandler(int) 
llvm-upstream/build/../lib/Support/Unix/Signals.inc:353:1
  #3 0x7f1c964fb0c0 __restore_rt 
(/lib/x86_64-linux-gnu/libpthread.so.0+0x110c0)
  #4 0x7f1c9508cfcf gsignal (/lib/x86_64-linux-gnu/libc.so.6+0x32fcf)
  #5 0x7f1c9508e3fa abort (/lib/x86_64-linux-gnu/libc.so.6+0x343fa)
  #6 0x7f1c95085e37 (/lib/x86_64-linux-gnu/libc.so.6+0x2be37)
  #7 0x7f1c95085ee2 (/lib/x86_64-linux-gnu/libc.so.6+0x2bee2)
  #8 0x00a19f75 
(llvm-upstream/build/tools/clang/tools/extra/unittests/clangd/./ClangdTests+0xa19f75)
  #9 0x00a1b72d (anonymous 
namespace)::DepCollectorPPCallbacks::InclusionDirective(clang::SourceLocation, 
clang::Token const&, llvm::StringRef, bool, clang::CharSourceRange, 
clang::FileEntry const*, llvm::StringRef, llvm::StringRef, clang::Module 
const*, clang::SrcMgr::CharacteristicKind) 
llvm-upstream/build/../tools/clang/lib/Frontend/DependencyFile.cpp:0:20
  #10 0x00ab958c 
clang::PPChainedCallbacks::InclusionDirective(clang::SourceLocation, 
clang::Token const&, llvm::StringRef, bool, clang::CharSourceRange, 
clang::FileEntry const*, llvm::StringRef, llvm::StringRef, clang::Module 
const*, clang::SrcMgr::CharacteristicKind) 
llvm-upstream/build/../tools/clang/include/clang/Lex/PPCallbacks.h:389:3
  #11 0x00ab958c 
clang::PPChainedCallbacks::InclusionDirective(clang::SourceLocation, 
clang::Token const&, llvm::StringRef, bool, clang::CharSourceRange, 
clang::FileEntry const*, llvm::StringRef, llvm::StringRef, clang::Module 
const*, clang::SrcMgr::CharacteristicKind) 
llvm-upstream/build/../tools/clang/include/clang/Lex/PPCallbacks.h:389:3
  #12 0x00abf696 
clang::Preprocessor::HandleIncludeDirective(clang::SourceLocation, 
clang::Token&, clang::DirectoryLookup const*, clang::FileEntry const*, bool) 
llvm-upstream/build/../tools/clang/lib/Lex/PPDirectives.cpp:2043:16
  #13 0x00ac2589 clang::Preprocessor::HandleDirective(clang::Token&) 
llvm-upstream/build/../tools/clang/lib/Lex/PPDirectives.cpp:1021:14
  #14 0x00a97ac9 clang::Lexer::LexTokenInternal(clang::Token&, bool) 
llvm-upstream/build/../tools/clang/lib/Lex/Lexer.cpp:3934:7
  #15 0x00a957ad clang::Lexer::Lex(clang::Token&) 
llvm-upstream/build/../tools/clang/lib/Lex/Lexer.cpp:3155:3
  #16 0x00af4954 clang::Preprocessor::Lex(clang::Token&) 
llvm-upstream/build/../tools/clang/lib/Lex/Preprocessor.cpp:895:12
  #17 0x012da277 clang::Parser::ConsumeToken() 
llvm-upstream/build/../tools/clang/include/clang/Parse/Parser.h:416:12
  #18 0x012dc8d9 clang::Parser::Initialize() 
llvm-upstream/build/../tools/clang/lib/Parse/Parser.cpp:520:1


Repository:
  rC Clang

https://reviews.llvm.org/D52774



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


Re: r343285 - [cxx2a] P0641R2: (Some) type mismatches on defaulted functions only

2018-10-02 Thread Hans Wennborg via cfe-commits
On Tue, Oct 2, 2018 at 12:02 PM, Hans Wennborg  wrote:
> I'm confused about what implicitly deleted means. In this code for example:
>
> struct S {
>   S(const S&) = default;
>   S& operator=(const S&) = default;
>   const int x;
> };
>
> void f(S &s) {
>   S t = s;
> }
>
> Clang will warn that operator= is implicitly deleted.
>
> But it seems the code still works fine, whereas if operator= were
> actually deleted it would not compile. So what does implicitly deleted
> mean then?

Oh, I see, my example is wrong. The assignment operator really is
deleted and it uses the copy constructor instead.

>
>
> On Fri, Sep 28, 2018 at 3:16 AM, Richard Smith via cfe-commits
>  wrote:
>> Author: rsmith
>> Date: Thu Sep 27 18:16:43 2018
>> New Revision: 343285
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=343285&view=rev
>> Log:
>> [cxx2a] P0641R2: (Some) type mismatches on defaulted functions only
>> render the function deleted instead of rendering the program ill-formed.
>>
>> This change also adds an enabled-by-default warning for the case where
>> an explicitly-defaulted special member function of a non-template class
>> is implicitly deleted by the type checking rules. (This fires either due
>> to this language change or due to pre-C++20 reasons for the member being
>> implicitly deleted). I've tested this on a large codebase and found only
>> bugs (where the program means something that's clearly different from
>> what the programmer intended), so this is enabled by default, but we
>> should revisit this if there are problems with this being enabled by
>> default.
>>
>> Modified:
>> cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
>> cfe/trunk/lib/Sema/SemaDeclCXX.cpp
>> cfe/trunk/test/CXX/class.derived/class.abstract/p16.cpp
>> cfe/trunk/test/CXX/dcl.decl/dcl.fct.def/dcl.fct.def.default/p1.cpp
>> cfe/trunk/test/CXX/drs/dr6xx.cpp
>> cfe/trunk/test/CXX/special/class.copy/p12-0x.cpp
>> cfe/trunk/test/CXX/special/class.copy/p23-cxx11.cpp
>> cfe/trunk/test/CXX/special/class.ctor/p5-0x.cpp
>> cfe/trunk/test/CXX/special/class.dtor/p5-0x.cpp
>> cfe/trunk/test/SemaCUDA/implicit-member-target.cu
>> cfe/trunk/test/SemaCXX/cxx0x-deleted-default-ctor.cpp
>> cfe/trunk/test/SemaCXX/cxx17-compat.cpp
>> cfe/trunk/test/SemaCXX/dr1301.cpp
>> cfe/trunk/test/SemaCXX/microsoft-dtor-lookup-cxx11.cpp
>> cfe/trunk/test/SemaTemplate/exception-spec-crash.cpp
>> cfe/trunk/www/cxx_status.html
>>
>> Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=343285&r1=343284&r2=343285&view=diff
>> ==
>> --- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
>> +++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Thu Sep 27 18:16:43 
>> 2018
>> @@ -7760,9 +7760,19 @@ def err_incorrect_defaulted_exception_sp
>>  def err_incorrect_defaulted_constexpr : Error<
>>"defaulted definition of %sub{select_special_member_kind}0 "
>>"is not constexpr">;
>> +def warn_defaulted_method_deleted : Warning<
>> +  "explicitly defaulted %sub{select_special_member_kind}0 is implicitly "
>> +  "deleted">, InGroup>;
>>  def err_out_of_line_default_deletes : Error<
>>"defaulting this %sub{select_special_member_kind}0 "
>>"would delete it after its first declaration">;
>> +def note_deleted_type_mismatch : Note<
>> +  "function is implicitly deleted because its declared type does not match "
>> +  "the type of an implicit %sub{select_special_member_kind}0">;
>> +def warn_cxx17_compat_defaulted_method_type_mismatch : Warning<
>> +  "explicitly defaulting this %sub{select_special_member_kind}0 with a type 
>> "
>> +  "different from the implicit type is incompatible with C++ standards 
>> before "
>> +  "C++2a">, InGroup, DefaultIgnore;
>>  def warn_vbase_moved_multiple_times : Warning<
>>"defaulted move assignment operator of %0 will move assign virtual base "
>>"class %1 multiple times">, InGroup>;
>>
>> Modified: cfe/trunk/lib/Sema/SemaDeclCXX.cpp
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclCXX.cpp?rev=343285&r1=343284&r2=343285&view=diff
>> ==
>> --- cfe/trunk/lib/Sema/SemaDeclCXX.cpp (original)
>> +++ cfe/trunk/lib/Sema/SemaDeclCXX.cpp Thu Sep 27 18:16:43 2018
>> @@ -6451,20 +6451,29 @@ void Sema::CheckExplicitlyDefaultedSpeci
>>//copy operation can take a non-const reference) as an implicit
>>//declaration, and
>>// -- not have default arguments.
>> +  // C++2a changes the second bullet to instead delete the function if it's
>> +  // defaulted on its first declaration, unless it's "an assignment 
>> operator,
>> +  // and its return type differs or its parameter type is not a reference".
>> +  bool DeleteOnTypeMismatch = getLangOpts().

[PATCH] D52647: [CodeComplete] Re-fix accessibilty of protected members from base class.

2018-10-02 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:
  rC Clang

https://reviews.llvm.org/D52647



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


[PATCH] D52711: [clangd] Dex: add Corpus factory for iterators, rename, fold constant. NFC

2018-10-02 Thread Eric Liu via Phabricator via cfe-commits
ioeric accepted this revision.
ioeric added inline comments.
This revision is now accepted and ready to land.



Comment at: clangd/index/dex/Iterator.h:131
+struct Corpus {
+  DocID Size;
+

Maybe make this a constant and initialize it via a constructor?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52711



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


[PATCH] D52774: [Preprocessor] Fix an assertion failure trigged in clangd #include completion.

2018-10-02 Thread Kristina Brooks via Phabricator via cfe-commits
kristina added a reviewer: kristina.
kristina added a comment.

Could you add a regression test please? Thank you.


Repository:
  rC Clang

https://reviews.llvm.org/D52774



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


[PATCH] D52730: [analyzer] ConversionChecker: handle floating point

2018-10-02 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus added inline comments.



Comment at: lib/StaticAnalyzer/Checkers/ConversionChecker.cpp:175
+
+  if (RepresentsUntilExp >= sizeof(unsigned long long)*8) {
 return false;

NoQ wrote:
> Szelethus wrote:
> > Szelethus wrote:
> > > How about `AC.getSizeType(AC.UnsignedLongLongTy))`?
> > I'm actually not too sure about this. @whisperity?
> Yeah, i suspect it's a host machine check (to prevent our own overflow on 
> line 189) rather than a target machine check.
Oh right, thanks for clarifying that.
I looked it up, and the number of bits in a `char` can be acquired from 
`CHAR_BITS`, maybe use that instead of hard coding 8? 
https://en.cppreference.com/w/c/types/limits


Repository:
  rC Clang

https://reviews.llvm.org/D52730



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


r343574 - Revert untintentionally commited changes

2018-10-02 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Tue Oct  2 03:28:54 2018
New Revision: 343574

URL: http://llvm.org/viewvc/llvm-project?rev=343574&view=rev
Log:
Revert untintentionally commited changes

Modified:

cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h?rev=343574&r1=343573&r2=343574&view=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h 
(original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h 
Tue Oct  2 03:28:54 2018
@@ -79,9 +79,9 @@ class FieldNode {
 protected:
   const FieldRegion *FR;
 
-  // TODO: This destructor shouldn't be virtual, but breaks buildbots with
-  // -Werror -Wnon-virtual-dtor.
-  virtual ~FieldNode() = default;
+  /// FieldNodes are never meant to be created on the heap, see
+  /// FindUninitializedFields::addFieldToUninits().
+  /* non-virtual */ ~FieldNode() = default;
 
 public:
   FieldNode(const FieldRegion *FR) : FR(FR) {}


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


r343573 - [Lex] TokenConcatenation now takes const Preprocessor

2018-10-02 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Tue Oct  2 03:28:50 2018
New Revision: 343573

URL: http://llvm.org/viewvc/llvm-project?rev=343573&view=rev
Log:
[Lex] TokenConcatenation now takes const Preprocessor

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

Modified:

cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h?rev=343573&r1=343572&r2=343573&view=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h 
(original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h 
Tue Oct  2 03:28:50 2018
@@ -79,9 +79,9 @@ class FieldNode {
 protected:
   const FieldRegion *FR;
 
-  /// FieldNodes are never meant to be created on the heap, see
-  /// FindUninitializedFields::addFieldToUninits().
-  /* non-virtual */ ~FieldNode() = default;
+  // TODO: This destructor shouldn't be virtual, but breaks buildbots with
+  // -Werror -Wnon-virtual-dtor.
+  virtual ~FieldNode() = default;
 
 public:
   FieldNode(const FieldRegion *FR) : FR(FR) {}


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


r343575 - [CodeComplete] Re-fix accessibilty of protected members from base class.

2018-10-02 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Tue Oct  2 03:29:00 2018
New Revision: 343575

URL: http://llvm.org/viewvc/llvm-project?rev=343575&view=rev
Log:
[CodeComplete] Re-fix accessibilty of protected members from base class.

Summary:
The initial fix (r337453) had bug and was partially reverted (r338255).
This simplies the original fix by explicitly passing the naming class to the
completion consumer.

Reviewers: ilya-biryukov

Subscribers: cfe-commits

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

Modified:
cfe/trunk/lib/Sema/SemaCodeComplete.cpp
cfe/trunk/lib/Sema/SemaLookup.cpp
cfe/trunk/test/Index/complete-access-checks.cpp

Modified: cfe/trunk/lib/Sema/SemaCodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaCodeComplete.cpp?rev=343575&r1=343574&r2=343575&view=diff
==
--- cfe/trunk/lib/Sema/SemaCodeComplete.cpp (original)
+++ cfe/trunk/lib/Sema/SemaCodeComplete.cpp Tue Oct  2 03:29:00 2018
@@ -10,6 +10,7 @@
 //  This file defines the code-completion semantic actions.
 //
 
//===--===//
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/ExprCXX.h"
@@ -1295,18 +1296,29 @@ namespace {
 ResultBuilder &Results;
 DeclContext *CurContext;
 std::vector FixIts;
+// This is set to the record where the search starts, if this is a record
+// member completion.
+RecordDecl *MemberCompletionRecord = nullptr;
 
   public:
 CodeCompletionDeclConsumer(
 ResultBuilder &Results, DeclContext *CurContext,
-std::vector FixIts = std::vector())
-: Results(Results), CurContext(CurContext), FixIts(std::move(FixIts)) 
{}
+std::vector FixIts = std::vector(),
+RecordDecl *MemberCompletionRecord = nullptr)
+: Results(Results), CurContext(CurContext), FixIts(std::move(FixIts)),
+  MemberCompletionRecord(MemberCompletionRecord) {}
 
 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
bool InBaseClass) override {
   bool Accessible = true;
-  if (Ctx)
-Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
+  if (Ctx) {
+// Set the actual accessing context (i.e. naming class) to the record
+// context where the search starts. When `InBaseClass` is true, `Ctx`
+// will be the base class, which is not the actual naming class.
+DeclContext *AccessingCtx =
+MemberCompletionRecord ? MemberCompletionRecord : Ctx;
+Accessible = Results.getSema().IsSimplyAccessible(ND, AccessingCtx);
+  }
   ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
false, Accessible, FixIts);
   Results.AddResult(Result, CurContext, Hiding, InBaseClass);
@@ -4101,7 +4113,8 @@ static void AddRecordMembersCompletionRe
   std::vector FixIts;
   if (AccessOpFixIt)
   FixIts.emplace_back(AccessOpFixIt.getValue());
-  CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext, 
std::move(FixIts));
+  CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext,
+  std::move(FixIts), RD);
   SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer,
  SemaRef.CodeCompleter->includeGlobals(),
  /*IncludeDependentBases=*/true,

Modified: cfe/trunk/lib/Sema/SemaLookup.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaLookup.cpp?rev=343575&r1=343574&r2=343575&view=diff
==
--- cfe/trunk/lib/Sema/SemaLookup.cpp (original)
+++ cfe/trunk/lib/Sema/SemaLookup.cpp Tue Oct  2 03:29:00 2018
@@ -3619,8 +3619,9 @@ static void LookupVisibleDecls(DeclConte
 
   // Find results in this base class (and its bases).
   ShadowContextRAII Shadow(Visited);
-  LookupVisibleDecls(RD, Result, QualifiedNameLookup, true, Consumer,
- Visited, IncludeDependentBases, LoadExternal);
+  LookupVisibleDecls(RD, Result, QualifiedNameLookup, /*InBaseClass=*/true,
+ Consumer, Visited, IncludeDependentBases,
+ LoadExternal);
 }
   }
 

Modified: cfe/trunk/test/Index/complete-access-checks.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/complete-access-checks.cpp?rev=343575&r1=343574&r2=343575&view=diff
==
--- cfe/trunk/test/Index/complete-access-checks.cpp (original)
+++ cfe/trunk/test/Index/complete-access-checks.cpp Tue Oct  2 03:29:00 2018
@@ -36,10 +36,10 @@ void Y::doSomething() {
 
 // CHECK-SUPER-ACCESS: CXXMethod:{ResultType void}{TypedText 
doSomething}{LeftParen (}{RightParen )} (34)
 // CHECK-SUPER-ACCESS: CXXMethod

Re: r343573 - [Lex] TokenConcatenation now takes const Preprocessor

2018-10-02 Thread Eric Liu via cfe-commits
Sorry, I messed up my svn rebase somehow and committed and reverted this
again (r343574) when landing r343575.

On Tue, Oct 2, 2018 at 12:30 PM Eric Liu via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: ioeric
> Date: Tue Oct  2 03:28:50 2018
> New Revision: 343573
>
> URL: http://llvm.org/viewvc/llvm-project?rev=343573&view=rev
> Log:
> [Lex] TokenConcatenation now takes const Preprocessor
>
> Differential Revision: https://reviews.llvm.org/D52502
>
> Modified:
>
> cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h
>
> Modified:
> cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h?rev=343573&r1=343572&r2=343573&view=diff
>
> ==
> ---
> cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h
> (original)
> +++
> cfe/trunk/lib/StaticAnalyzer/Checkers/UninitializedObject/UninitializedObject.h
> Tue Oct  2 03:28:50 2018
> @@ -79,9 +79,9 @@ class FieldNode {
>  protected:
>const FieldRegion *FR;
>
> -  /// FieldNodes are never meant to be created on the heap, see
> -  /// FindUninitializedFields::addFieldToUninits().
> -  /* non-virtual */ ~FieldNode() = default;
> +  // TODO: This destructor shouldn't be virtual, but breaks buildbots with
> +  // -Werror -Wnon-virtual-dtor.
> +  virtual ~FieldNode() = default;
>
>  public:
>FieldNode(const FieldRegion *FR) : FR(FR) {}
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52647: [CodeComplete] Re-fix accessibilty of protected members from base class.

2018-10-02 Thread Eric Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL343575: [CodeComplete] Re-fix accessibilty of protected 
members from base class. (authored by ioeric, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D52647

Files:
  cfe/trunk/lib/Sema/SemaCodeComplete.cpp
  cfe/trunk/lib/Sema/SemaLookup.cpp
  cfe/trunk/test/Index/complete-access-checks.cpp


Index: cfe/trunk/test/Index/complete-access-checks.cpp
===
--- cfe/trunk/test/Index/complete-access-checks.cpp
+++ cfe/trunk/test/Index/complete-access-checks.cpp
@@ -36,10 +36,10 @@
 
 // CHECK-SUPER-ACCESS: CXXMethod:{ResultType void}{TypedText 
doSomething}{LeftParen (}{RightParen )} (34)
 // CHECK-SUPER-ACCESS: CXXMethod:{ResultType void}{Informative X::}{TypedText 
func1}{LeftParen (}{RightParen )} (36)
-// CHECK-SUPER-ACCESS: CXXMethod:{ResultType void}{Informative X::}{TypedText 
func2}{LeftParen (}{RightParen )} (36)
+// CHECK-SUPER-ACCESS: CXXMethod:{ResultType void}{Informative X::}{TypedText 
func2}{LeftParen (}{RightParen )} (36){{$}}
 // CHECK-SUPER-ACCESS: CXXMethod:{ResultType void}{Informative X::}{TypedText 
func3}{LeftParen (}{RightParen )} (36) (inaccessible)
 // CHECK-SUPER-ACCESS: FieldDecl:{ResultType int}{Informative X::}{TypedText 
member1} (37)
-// CHECK-SUPER-ACCESS: FieldDecl:{ResultType int}{Informative X::}{TypedText 
member2} (37)
+// CHECK-SUPER-ACCESS: FieldDecl:{ResultType int}{Informative X::}{TypedText 
member2} (37){{$}}
 // CHECK-SUPER-ACCESS: FieldDecl:{ResultType int}{Informative X::}{TypedText 
member3} (37) (inaccessible)
 // CHECK-SUPER-ACCESS: CXXMethod:{ResultType Y &}{TypedText 
operator=}{LeftParen (}{Placeholder const Y &}{RightParen )} (79)
 // CHECK-SUPER-ACCESS: CXXMethod:{ResultType X &}{Text X::}{TypedText 
operator=}{LeftParen (}{Placeholder const X &}{RightParen )} (81)
Index: cfe/trunk/lib/Sema/SemaCodeComplete.cpp
===
--- cfe/trunk/lib/Sema/SemaCodeComplete.cpp
+++ cfe/trunk/lib/Sema/SemaCodeComplete.cpp
@@ -10,6 +10,7 @@
 //  This file defines the code-completion semantic actions.
 //
 
//===--===//
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/ExprCXX.h"
@@ -1295,18 +1296,29 @@
 ResultBuilder &Results;
 DeclContext *CurContext;
 std::vector FixIts;
+// This is set to the record where the search starts, if this is a record
+// member completion.
+RecordDecl *MemberCompletionRecord = nullptr;
 
   public:
 CodeCompletionDeclConsumer(
 ResultBuilder &Results, DeclContext *CurContext,
-std::vector FixIts = std::vector())
-: Results(Results), CurContext(CurContext), FixIts(std::move(FixIts)) 
{}
+std::vector FixIts = std::vector(),
+RecordDecl *MemberCompletionRecord = nullptr)
+: Results(Results), CurContext(CurContext), FixIts(std::move(FixIts)),
+  MemberCompletionRecord(MemberCompletionRecord) {}
 
 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
bool InBaseClass) override {
   bool Accessible = true;
-  if (Ctx)
-Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
+  if (Ctx) {
+// Set the actual accessing context (i.e. naming class) to the record
+// context where the search starts. When `InBaseClass` is true, `Ctx`
+// will be the base class, which is not the actual naming class.
+DeclContext *AccessingCtx =
+MemberCompletionRecord ? MemberCompletionRecord : Ctx;
+Accessible = Results.getSema().IsSimplyAccessible(ND, AccessingCtx);
+  }
   ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
false, Accessible, FixIts);
   Results.AddResult(Result, CurContext, Hiding, InBaseClass);
@@ -4101,7 +4113,8 @@
   std::vector FixIts;
   if (AccessOpFixIt)
   FixIts.emplace_back(AccessOpFixIt.getValue());
-  CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext, 
std::move(FixIts));
+  CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext,
+  std::move(FixIts), RD);
   SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer,
  SemaRef.CodeCompleter->includeGlobals(),
  /*IncludeDependentBases=*/true,
Index: cfe/trunk/lib/Sema/SemaLookup.cpp
===
--- cfe/trunk/lib/Sema/SemaLookup.cpp
+++ cfe/trunk/lib/Sema/SemaLookup.cpp
@@ -3619,8 +3619,9 @@
 
   // Find results in this base class (and its bases).
   ShadowContextRAII Shadow(Visited);
-  LookupVisibleDecls(RD, Result, QualifiedNameLookup, true, C

[PATCH] D52419: [clangd] Cache FS stat() calls when building preamble.

2018-10-02 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 167913.
ioeric added a comment.

- add comment for StatCache in PreambleData


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52419

Files:
  clangd/CMakeLists.txt
  clangd/ClangdServer.cpp
  clangd/ClangdUnit.cpp
  clangd/ClangdUnit.h
  clangd/CodeComplete.cpp
  clangd/CodeComplete.h
  clangd/FS.cpp
  clangd/FS.h
  clangd/index/Index.h
  clangd/index/MemIndex.cpp
  clangd/index/Merge.cpp
  clangd/index/dex/Dex.cpp
  clangd/tool/ClangdMain.cpp
  unittests/clangd/CMakeLists.txt
  unittests/clangd/ClangdTests.cpp
  unittests/clangd/CodeCompleteTests.cpp
  unittests/clangd/DexTests.cpp
  unittests/clangd/FSTests.cpp
  unittests/clangd/TestFS.cpp

Index: unittests/clangd/TestFS.cpp
===
--- unittests/clangd/TestFS.cpp
+++ unittests/clangd/TestFS.cpp
@@ -23,6 +23,7 @@
 llvm::StringMap const &Timestamps) {
   IntrusiveRefCntPtr MemFS(
   new vfs::InMemoryFileSystem);
+  MemFS->setCurrentWorkingDirectory(testRoot());
   for (auto &FileAndContents : Files) {
 StringRef File = FileAndContents.first();
 MemFS->addFile(
Index: unittests/clangd/FSTests.cpp
===
--- /dev/null
+++ unittests/clangd/FSTests.cpp
@@ -0,0 +1,46 @@
+//===-- FSTests.cpp - File system related tests -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "FS.h"
+#include "TestFS.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+TEST(FSTests, PreambleStatusCache) {
+  llvm::StringMap Files;
+  Files["x"] = "";
+  Files["y"] = "";
+  auto FS = buildTestFS(Files);
+  FS->setCurrentWorkingDirectory(testRoot());
+
+  PreambleFileStatusCache StatCache;
+  auto ProduceFS = StatCache.getProducingFS(FS);
+  EXPECT_TRUE(ProduceFS->openFileForRead("x"));
+  EXPECT_TRUE(ProduceFS->status("y"));
+
+  EXPECT_TRUE(StatCache.lookup(testPath("x")).hasValue());
+  EXPECT_TRUE(StatCache.lookup(testPath("y")).hasValue());
+
+  vfs::Status S("fake", llvm::sys::fs::UniqueID(0, 0),
+std::chrono::system_clock::now(), 0, 0, 1024,
+llvm::sys::fs::file_type::regular_file, llvm::sys::fs::all_all);
+  StatCache.update(*FS, S);
+  auto ConsumeFS = StatCache.getConsumingFS(FS);
+  auto Cached = ConsumeFS->status(testPath("fake"));
+  EXPECT_TRUE(Cached);
+  EXPECT_EQ(Cached->getName(), S.getName());
+}
+
+} // namespace
+} // namespace clangd
+} // namespace clang
Index: unittests/clangd/DexTests.cpp
===
--- unittests/clangd/DexTests.cpp
+++ unittests/clangd/DexTests.cpp
@@ -523,6 +523,17 @@
   EXPECT_THAT(match(*I, Req), UnorderedElementsAre("a::y1"));
 }
 
+TEST(DexTest, WildcardScope) {
+  auto I =
+  Dex::build(generateSymbols({"a::y1", "a::b::y2", "c::y3"}), URISchemes);
+  FuzzyFindRequest Req;
+  Req.Query = "y";
+  Req.Scopes = {"a::"};
+  Req.AnyScope = true;
+  EXPECT_THAT(match(*I, Req),
+  UnorderedElementsAre("a::y1", "a::b::y2", "c::y3"));
+}
+
 TEST(DexTest, IgnoreCases) {
   auto I = Dex::build(generateSymbols({"ns::ABC", "ns::abc"}), URISchemes);
   FuzzyFindRequest Req;
Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -2093,6 +2093,57 @@
 Has("bar.h\"", CompletionItemKind::File)));
 }
 
+TEST(CompletionTest, NoAllScopesCompletionWhenQualified) {
+  clangd::CodeCompleteOptions Opts = {};
+  Opts.AllScopes = true;
+
+  auto Results = completions(
+  R"cpp(
+void f() { na::Clangd^ }
+  )cpp",
+  {cls("na::ClangdA"), cls("nx::ClangdX"), cls("Clangd3")}, Opts);
+  EXPECT_THAT(Results.Completions,
+  UnorderedElementsAre(
+  AllOf(Qualifier(""), Scope("na::"), Named("ClangdA";
+}
+
+TEST(CompletionTest, AllScopesCompletion) {
+  clangd::CodeCompleteOptions Opts = {};
+  Opts.AllScopes = true;
+
+  auto Results = completions(
+  R"cpp(
+namespace na {
+void f() { Clangd^ }
+}
+  )cpp",
+  {cls("nx::Clangd1"), cls("ny::Clangd2"), cls("Clangd3"),
+   cls("na::nb::Clangd4")},
+  Opts);
+  EXPECT_THAT(
+  Results.Completions,
+  UnorderedElementsAre(AllOf(Qualifier("nx::"), Named("Clangd1")),
+   AllOf(Qualifier("ny::"), Named("Clangd2")),
+   AllOf(Qualifier(""), Scope(""), Named("Clangd3")),
+   AllOf(Qualifier("nb::"), Named("Clangd4";
+}
+
+TEST(CompletionTest, NoQualifierIfShadowed) {
+  clangd::CodeCompleteOptions Opt

[PATCH] D52419: [clangd] Cache FS stat() calls when building preamble.

2018-10-02 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 167914.
ioeric added a comment.

- Rebase


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52419

Files:
  clangd/CMakeLists.txt
  clangd/ClangdServer.cpp
  clangd/ClangdUnit.cpp
  clangd/ClangdUnit.h
  clangd/CodeComplete.cpp
  clangd/CodeComplete.h
  clangd/FS.cpp
  clangd/FS.h
  unittests/clangd/CMakeLists.txt
  unittests/clangd/ClangdTests.cpp
  unittests/clangd/FSTests.cpp
  unittests/clangd/TestFS.cpp

Index: unittests/clangd/TestFS.cpp
===
--- unittests/clangd/TestFS.cpp
+++ unittests/clangd/TestFS.cpp
@@ -23,6 +23,7 @@
 llvm::StringMap const &Timestamps) {
   IntrusiveRefCntPtr MemFS(
   new vfs::InMemoryFileSystem);
+  MemFS->setCurrentWorkingDirectory(testRoot());
   for (auto &FileAndContents : Files) {
 StringRef File = FileAndContents.first();
 MemFS->addFile(
Index: unittests/clangd/FSTests.cpp
===
--- /dev/null
+++ unittests/clangd/FSTests.cpp
@@ -0,0 +1,46 @@
+//===-- FSTests.cpp - File system related tests -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "FS.h"
+#include "TestFS.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+TEST(FSTests, PreambleStatusCache) {
+  llvm::StringMap Files;
+  Files["x"] = "";
+  Files["y"] = "";
+  auto FS = buildTestFS(Files);
+  FS->setCurrentWorkingDirectory(testRoot());
+
+  PreambleFileStatusCache StatCache;
+  auto ProduceFS = StatCache.getProducingFS(FS);
+  EXPECT_TRUE(ProduceFS->openFileForRead("x"));
+  EXPECT_TRUE(ProduceFS->status("y"));
+
+  EXPECT_TRUE(StatCache.lookup(testPath("x")).hasValue());
+  EXPECT_TRUE(StatCache.lookup(testPath("y")).hasValue());
+
+  vfs::Status S("fake", llvm::sys::fs::UniqueID(0, 0),
+std::chrono::system_clock::now(), 0, 0, 1024,
+llvm::sys::fs::file_type::regular_file, llvm::sys::fs::all_all);
+  StatCache.update(*FS, S);
+  auto ConsumeFS = StatCache.getConsumingFS(FS);
+  auto Cached = ConsumeFS->status(testPath("fake"));
+  EXPECT_TRUE(Cached);
+  EXPECT_EQ(Cached->getName(), S.getName());
+}
+
+} // namespace
+} // namespace clangd
+} // namespace clang
Index: unittests/clangd/ClangdTests.cpp
===
--- unittests/clangd/ClangdTests.cpp
+++ unittests/clangd/ClangdTests.cpp
@@ -963,6 +963,71 @@
Field(&CodeCompletion::Name, "baz")));
 }
 
+// Check that running code completion doesn't stat() a bunch of files from the
+// preamble again. (They should be using the preamble's stat-cache)
+TEST(ClangdTests, PreambleVFSStatCache) {
+  class ListenStatsFSProvider : public FileSystemProvider {
+  public:
+ListenStatsFSProvider(llvm::StringMap &CountStats)
+: CountStats(CountStats) {}
+
+IntrusiveRefCntPtr getFileSystem() override {
+  class ListenStatVFS : public vfs::ProxyFileSystem {
+  public:
+ListenStatVFS(IntrusiveRefCntPtr FS,
+  llvm::StringMap &CountStats)
+: ProxyFileSystem(std::move(FS)), CountStats(CountStats) {}
+
+llvm::ErrorOr>
+openFileForRead(const Twine &Path) override {
+  ++CountStats[llvm::sys::path::filename(Path.str())];
+  return ProxyFileSystem::openFileForRead(Path);
+}
+llvm::ErrorOr status(const Twine &Path) override {
+  ++CountStats[llvm::sys::path::filename(Path.str())];
+  return ProxyFileSystem::status(Path);
+}
+
+  private:
+llvm::StringMap &CountStats;
+  };
+
+  return IntrusiveRefCntPtr(
+  new ListenStatVFS(buildTestFS(Files), CountStats));
+}
+
+// If relative paths are used, they are resolved with testPath().
+llvm::StringMap Files;
+llvm::StringMap &CountStats;
+  };
+
+  llvm::StringMap CountStats;
+  ListenStatsFSProvider FS(CountStats);
+  ErrorCheckingDiagConsumer DiagConsumer;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
+
+  auto SourcePath = testPath("foo.cpp");
+  auto HeaderPath = testPath("foo.h");
+  FS.Files[HeaderPath] = "struct TestSym {};";
+  Annotations Code(R"cpp(
+#include "foo.h"
+
+int main() {
+  TestSy^
+})cpp");
+
+  runAddDocument(Server, SourcePath, Code.code());
+
+  EXPECT_EQ(CountStats["foo.h"], 1u);
+  auto Completions = cantFail(runCodeComplete(Server, SourcePath, Code.point(),
+  clangd::CodeCompleteOptions()))
+ .Completions;
+  EXPECT_EQ(CountStats["foo.h"], 1u);
+  EXPECT

[PATCH] D52419: [clangd] Cache FS stat() calls when building preamble.

2018-10-02 Thread Eric Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE343576: [clangd] Cache FS stat() calls when building 
preamble. (authored by ioeric, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D52419?vs=167914&id=167915#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52419

Files:
  clangd/CMakeLists.txt
  clangd/ClangdServer.cpp
  clangd/ClangdUnit.cpp
  clangd/ClangdUnit.h
  clangd/CodeComplete.cpp
  clangd/CodeComplete.h
  clangd/FS.cpp
  clangd/FS.h
  unittests/clangd/CMakeLists.txt
  unittests/clangd/ClangdTests.cpp
  unittests/clangd/FSTests.cpp
  unittests/clangd/TestFS.cpp

Index: unittests/clangd/ClangdTests.cpp
===
--- unittests/clangd/ClangdTests.cpp
+++ unittests/clangd/ClangdTests.cpp
@@ -963,6 +963,71 @@
Field(&CodeCompletion::Name, "baz")));
 }
 
+// Check that running code completion doesn't stat() a bunch of files from the
+// preamble again. (They should be using the preamble's stat-cache)
+TEST(ClangdTests, PreambleVFSStatCache) {
+  class ListenStatsFSProvider : public FileSystemProvider {
+  public:
+ListenStatsFSProvider(llvm::StringMap &CountStats)
+: CountStats(CountStats) {}
+
+IntrusiveRefCntPtr getFileSystem() override {
+  class ListenStatVFS : public vfs::ProxyFileSystem {
+  public:
+ListenStatVFS(IntrusiveRefCntPtr FS,
+  llvm::StringMap &CountStats)
+: ProxyFileSystem(std::move(FS)), CountStats(CountStats) {}
+
+llvm::ErrorOr>
+openFileForRead(const Twine &Path) override {
+  ++CountStats[llvm::sys::path::filename(Path.str())];
+  return ProxyFileSystem::openFileForRead(Path);
+}
+llvm::ErrorOr status(const Twine &Path) override {
+  ++CountStats[llvm::sys::path::filename(Path.str())];
+  return ProxyFileSystem::status(Path);
+}
+
+  private:
+llvm::StringMap &CountStats;
+  };
+
+  return IntrusiveRefCntPtr(
+  new ListenStatVFS(buildTestFS(Files), CountStats));
+}
+
+// If relative paths are used, they are resolved with testPath().
+llvm::StringMap Files;
+llvm::StringMap &CountStats;
+  };
+
+  llvm::StringMap CountStats;
+  ListenStatsFSProvider FS(CountStats);
+  ErrorCheckingDiagConsumer DiagConsumer;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
+
+  auto SourcePath = testPath("foo.cpp");
+  auto HeaderPath = testPath("foo.h");
+  FS.Files[HeaderPath] = "struct TestSym {};";
+  Annotations Code(R"cpp(
+#include "foo.h"
+
+int main() {
+  TestSy^
+})cpp");
+
+  runAddDocument(Server, SourcePath, Code.code());
+
+  EXPECT_EQ(CountStats["foo.h"], 1u);
+  auto Completions = cantFail(runCodeComplete(Server, SourcePath, Code.point(),
+  clangd::CodeCompleteOptions()))
+ .Completions;
+  EXPECT_EQ(CountStats["foo.h"], 1u);
+  EXPECT_THAT(Completions,
+  ElementsAre(Field(&CodeCompletion::Name, "TestSym")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: unittests/clangd/TestFS.cpp
===
--- unittests/clangd/TestFS.cpp
+++ unittests/clangd/TestFS.cpp
@@ -23,6 +23,7 @@
 llvm::StringMap const &Timestamps) {
   IntrusiveRefCntPtr MemFS(
   new vfs::InMemoryFileSystem);
+  MemFS->setCurrentWorkingDirectory(testRoot());
   for (auto &FileAndContents : Files) {
 StringRef File = FileAndContents.first();
 MemFS->addFile(
Index: unittests/clangd/FSTests.cpp
===
--- unittests/clangd/FSTests.cpp
+++ unittests/clangd/FSTests.cpp
@@ -0,0 +1,46 @@
+//===-- FSTests.cpp - File system related tests -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "FS.h"
+#include "TestFS.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+TEST(FSTests, PreambleStatusCache) {
+  llvm::StringMap Files;
+  Files["x"] = "";
+  Files["y"] = "";
+  auto FS = buildTestFS(Files);
+  FS->setCurrentWorkingDirectory(testRoot());
+
+  PreambleFileStatusCache StatCache;
+  auto ProduceFS = StatCache.getProducingFS(FS);
+  EXPECT_TRUE(ProduceFS->openFileForRead("x"));
+  EXPECT_TRUE(ProduceFS->status("y"));
+
+  EXPECT_TRUE(StatCache.lookup(testPath("x")).hasValue());
+  EXPECT_TRUE(StatCache.lookup(testPath("y")).hasValue());
+
+  vfs::Status S("fake", llvm::sys::fs::UniqueID(0, 0),
+std::chrono::system_clo

[clang-tools-extra] r343576 - [clangd] Cache FS stat() calls when building preamble.

2018-10-02 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Tue Oct  2 03:43:55 2018
New Revision: 343576

URL: http://llvm.org/viewvc/llvm-project?rev=343576&view=rev
Log:
[clangd] Cache FS stat() calls when building preamble.

Summary:
The file stats can be reused when preamble is reused (e.g. code
completion). It's safe to assume that cached status is not outdated as we
assume preamble files to remain unchanged.

On real file system, this made code completion ~20% faster on a measured file
(with big preamble). The preamble build time doesn't change much.

Reviewers: sammccall, ilya-biryukov

Reviewed By: sammccall

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

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

Added:
clang-tools-extra/trunk/clangd/FS.cpp
clang-tools-extra/trunk/clangd/FS.h
clang-tools-extra/trunk/unittests/clangd/FSTests.cpp
Modified:
clang-tools-extra/trunk/clangd/CMakeLists.txt
clang-tools-extra/trunk/clangd/ClangdServer.cpp
clang-tools-extra/trunk/clangd/ClangdUnit.cpp
clang-tools-extra/trunk/clangd/ClangdUnit.h
clang-tools-extra/trunk/clangd/CodeComplete.cpp
clang-tools-extra/trunk/clangd/CodeComplete.h
clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt
clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp
clang-tools-extra/trunk/unittests/clangd/TestFS.cpp

Modified: clang-tools-extra/trunk/clangd/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CMakeLists.txt?rev=343576&r1=343575&r2=343576&view=diff
==
--- clang-tools-extra/trunk/clangd/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clangd/CMakeLists.txt Tue Oct  2 03:43:55 2018
@@ -21,6 +21,7 @@ add_clang_library(clangDaemon
   DraftStore.cpp
   FindSymbols.cpp
   FileDistance.cpp
+  FS.cpp
   FuzzyMatch.cpp
   GlobalCompilationDatabase.cpp
   Headers.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=343576&r1=343575&r2=343576&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Tue Oct  2 03:43:55 2018
@@ -181,8 +181,6 @@ void ClangdServer::codeComplete(PathRef
 if (isCancelled())
   return CB(llvm::make_error());
 
-auto PreambleData = IP->Preamble;
-
 llvm::Optional SpecFuzzyFind;
 if (CodeCompleteOpts.Index && CodeCompleteOpts.SpeculativeIndexRequest) {
   SpecFuzzyFind.emplace();
@@ -195,10 +193,8 @@ void ClangdServer::codeComplete(PathRef
 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
 // both the old and the new version in case only one of them matches.
 CodeCompleteResult Result = clangd::codeComplete(
-File, IP->Command, PreambleData ? &PreambleData->Preamble : nullptr,
-PreambleData ? PreambleData->Includes : IncludeStructure(),
-IP->Contents, Pos, FS, PCHs, CodeCompleteOpts,
-SpecFuzzyFind ? SpecFuzzyFind.getPointer() : nullptr);
+File, IP->Command, IP->Preamble, IP->Contents, Pos, FS, PCHs,
+CodeCompleteOpts, SpecFuzzyFind ? SpecFuzzyFind.getPointer() : 
nullptr);
 {
   clang::clangd::trace::Span Tracer("Completion results callback");
   CB(std::move(Result));
@@ -231,9 +227,8 @@ void ClangdServer::signatureHelp(PathRef
   return CB(IP.takeError());
 
 auto PreambleData = IP->Preamble;
-CB(clangd::signatureHelp(File, IP->Command,
- PreambleData ? &PreambleData->Preamble : nullptr,
- IP->Contents, Pos, FS, PCHs, Index));
+CB(clangd::signatureHelp(File, IP->Command, PreambleData, IP->Contents, 
Pos,
+ FS, PCHs, Index));
   };
 
   // Unlike code completion, we wait for an up-to-date preamble here.

Modified: clang-tools-extra/trunk/clangd/ClangdUnit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdUnit.cpp?rev=343576&r1=343575&r2=343576&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdUnit.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdUnit.cpp Tue Oct  2 03:43:55 2018
@@ -246,9 +246,10 @@ const IncludeStructure &ParsedAST::getIn
 }
 
 PreambleData::PreambleData(PrecompiledPreamble Preamble,
-   std::vector Diags, IncludeStructure Includes)
+   std::vector Diags, IncludeStructure Includes,
+   std::unique_ptr StatCache)
 : Preamble(std::move(Preamble)), Diags(std::move(Diags)),
-  Includes(std::move(Includes)) {}
+  Includes(std::move(Includes)), StatCache(std::move(StatCache)) {}
 
 ParsedAST::ParsedAST(std::shared_ptr Preamble,
  std::unique_ptr Clang,
@@ -

[PATCH] D52419: [clangd] Cache FS stat() calls when building preamble.

2018-10-02 Thread Eric Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL343576: [clangd] Cache FS stat() calls when building 
preamble. (authored by ioeric, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D52419

Files:
  clang-tools-extra/trunk/clangd/CMakeLists.txt
  clang-tools-extra/trunk/clangd/ClangdServer.cpp
  clang-tools-extra/trunk/clangd/ClangdUnit.cpp
  clang-tools-extra/trunk/clangd/ClangdUnit.h
  clang-tools-extra/trunk/clangd/CodeComplete.cpp
  clang-tools-extra/trunk/clangd/CodeComplete.h
  clang-tools-extra/trunk/clangd/FS.cpp
  clang-tools-extra/trunk/clangd/FS.h
  clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt
  clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp
  clang-tools-extra/trunk/unittests/clangd/FSTests.cpp
  clang-tools-extra/trunk/unittests/clangd/TestFS.cpp

Index: clang-tools-extra/trunk/clangd/FS.cpp
===
--- clang-tools-extra/trunk/clangd/FS.cpp
+++ clang-tools-extra/trunk/clangd/FS.cpp
@@ -0,0 +1,92 @@
+//===--- FS.cpp - File system related utils --*- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "FS.h"
+#include "clang/Basic/VirtualFileSystem.h"
+#include "llvm/ADT/None.h"
+
+namespace clang {
+namespace clangd {
+
+void PreambleFileStatusCache::update(const vfs::FileSystem &FS, vfs::Status S) {
+  SmallString<32> PathStore(S.getName());
+  if (auto Err = FS.makeAbsolute(PathStore))
+return;
+  // Stores the latest status in cache as it can change in a preamble build.
+  StatCache.insert({PathStore, std::move(S)});
+}
+
+llvm::Optional
+PreambleFileStatusCache::lookup(llvm::StringRef File) const {
+  auto I = StatCache.find(File);
+  if (I != StatCache.end())
+return I->getValue();
+  return llvm::None;
+}
+
+IntrusiveRefCntPtr PreambleFileStatusCache::getProducingFS(
+IntrusiveRefCntPtr FS) {
+  // This invalidates old status in cache if files are re-`open()`ed or
+  // re-`stat()`ed in case file status has changed during preamble build.
+  class CollectFS : public vfs::ProxyFileSystem {
+  public:
+CollectFS(IntrusiveRefCntPtr FS,
+  PreambleFileStatusCache &StatCache)
+: ProxyFileSystem(std::move(FS)), StatCache(StatCache) {}
+
+llvm::ErrorOr>
+openFileForRead(const Twine &Path) override {
+  auto File = getUnderlyingFS().openFileForRead(Path);
+  if (!File || !*File)
+return File;
+  // Eagerly stat opened file, as the followup `status` call on the file
+  // doesn't necessarily go through this FS. This puts some extra work on
+  // preamble build, but it should be worth it as preamble can be reused
+  // many times (e.g. code completion) and the repeated status call is
+  // likely to be cached in the underlying file system anyway.
+  if (auto S = File->get()->status())
+StatCache.update(getUnderlyingFS(), std::move(*S));
+  return File;
+}
+
+llvm::ErrorOr status(const Twine &Path) override {
+  auto S = getUnderlyingFS().status(Path);
+  if (S)
+StatCache.update(getUnderlyingFS(), *S);
+  return S;
+}
+
+  private:
+PreambleFileStatusCache &StatCache;
+  };
+  return IntrusiveRefCntPtr(new CollectFS(std::move(FS), *this));
+}
+
+IntrusiveRefCntPtr PreambleFileStatusCache::getConsumingFS(
+IntrusiveRefCntPtr FS) const {
+  class CacheVFS : public vfs::ProxyFileSystem {
+  public:
+CacheVFS(IntrusiveRefCntPtr FS,
+ const PreambleFileStatusCache &StatCache)
+: ProxyFileSystem(std::move(FS)), StatCache(StatCache) {}
+
+llvm::ErrorOr status(const Twine &Path) override {
+  if (auto S = StatCache.lookup(Path.str()))
+return *S;
+  return getUnderlyingFS().status(Path);
+}
+
+  private:
+const PreambleFileStatusCache &StatCache;
+  };
+  return IntrusiveRefCntPtr(new CacheVFS(std::move(FS), *this));
+}
+
+} // namespace clangd
+} // namespace clang
Index: clang-tools-extra/trunk/clangd/FS.h
===
--- clang-tools-extra/trunk/clangd/FS.h
+++ clang-tools-extra/trunk/clangd/FS.h
@@ -0,0 +1,65 @@
+//===--- FS.h - File system related utils *- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_FS_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_FS_H
+
+#include "clang/Basic/VirtualFileSystem.h"
+#include "llvm/ADT/Optional.h"
+
+namespace 

[PATCH] D52691: [clang-tidy] NFC use CHECK-NOTES in tests for performance-move-constructor-init

2018-10-02 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 167917.
JonasToth added a comment.

- adjust regex in check_clang_tidy


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52691

Files:
  test/clang-tidy/check_clang_tidy.py
  test/clang-tidy/performance-move-constructor-init.cpp


Index: test/clang-tidy/performance-move-constructor-init.cpp
===
--- test/clang-tidy/performance-move-constructor-init.cpp
+++ test/clang-tidy/performance-move-constructor-init.cpp
@@ -5,7 +5,7 @@
 
 #include 
 
-// CHECK-FIXES: #include 
+// CHECK FIXES: #include 
 
 template  struct remove_reference  {typedef T type;};
 template  struct remove_reference  {typedef T type;};
@@ -30,9 +30,9 @@
 struct D : B {
   D() : B() {}
   D(const D &RHS) : B(RHS) {}
-  // CHECK-MESSAGES: :[[@LINE+3]]:16: warning: move constructor initializes 
base class by calling a copy constructor [performance-move-constructor-init]
-  // CHECK-MESSAGES: 26:3: note: copy constructor being called
-  // CHECK-MESSAGES: 27:3: note: candidate move constructor here
+  // CHECK-NOTES: :[[@LINE+3]]:16: warning: move constructor initializes base 
class by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
   D(D &&RHS) : B(RHS) {}
 };
 
@@ -75,8 +75,10 @@
 
 struct M {
   B Mem;
-  // CHECK-MESSAGES: :[[@LINE+1]]:16: warning: move constructor initializes 
class member by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: :[[@LINE+1]]:16: warning: move constructor initializes class 
member by calling a copy constructor [performance-move-constructor-init]
   M(M &&RHS) : Mem(RHS.Mem) {}
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
 };
 
 struct N {
@@ -109,7 +111,7 @@
 
 struct Positive {
   Positive(Movable M) : M_(M) {}
-  // CHECK-MESSAGES: [[@LINE-1]]:12: warning: pass by value and use std::move 
[modernize-pass-by-value]
+  // CHECK-NOTES: [[@LINE-1]]:12: warning: pass by value and use std::move 
[modernize-pass-by-value]
   // CHECK-FIXES: Positive(Movable M) : M_(std::move(M)) {}
   Movable M_;
 };
Index: test/clang-tidy/check_clang_tidy.py
===
--- test/clang-tidy/check_clang_tidy.py
+++ test/clang-tidy/check_clang_tidy.py
@@ -169,7 +169,7 @@
   subprocess.check_output(
   ['FileCheck', '-input-file=' + notes_file, input_file_name,
'-check-prefix=' + check_notes_prefix,
-   '-implicit-check-not={{note|warning|error}}:'],
+   '-implicit-check-not=warning|error}}:|note: (?!FIX-IT)}}'],
   stderr=subprocess.STDOUT)
 except subprocess.CalledProcessError as e:
   print('FileCheck failed:\n' + e.output.decode())


Index: test/clang-tidy/performance-move-constructor-init.cpp
===
--- test/clang-tidy/performance-move-constructor-init.cpp
+++ test/clang-tidy/performance-move-constructor-init.cpp
@@ -5,7 +5,7 @@
 
 #include 
 
-// CHECK-FIXES: #include 
+// CHECK FIXES: #include 
 
 template  struct remove_reference  {typedef T type;};
 template  struct remove_reference  {typedef T type;};
@@ -30,9 +30,9 @@
 struct D : B {
   D() : B() {}
   D(const D &RHS) : B(RHS) {}
-  // CHECK-MESSAGES: :[[@LINE+3]]:16: warning: move constructor initializes base class by calling a copy constructor [performance-move-constructor-init]
-  // CHECK-MESSAGES: 26:3: note: copy constructor being called
-  // CHECK-MESSAGES: 27:3: note: candidate move constructor here
+  // CHECK-NOTES: :[[@LINE+3]]:16: warning: move constructor initializes base class by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
   D(D &&RHS) : B(RHS) {}
 };
 
@@ -75,8 +75,10 @@
 
 struct M {
   B Mem;
-  // CHECK-MESSAGES: :[[@LINE+1]]:16: warning: move constructor initializes class member by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: :[[@LINE+1]]:16: warning: move constructor initializes class member by calling a copy constructor [performance-move-constructor-init]
   M(M &&RHS) : Mem(RHS.Mem) {}
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
 };
 
 struct N {
@@ -109,7 +111,7 @@
 
 struct Positive {
   Positive(Movable M) : M_(M) {}
-  // CHECK-MESSAGES: [[@LINE-1]]:12: warning: pass by value and use std::move [modernize-pass-by-value]
+  // CHECK-NOTES: [[@LINE-1]]:12: warning: pass by value and use std::move [modernize-pass-by-value]
   // CHECK-FIXES: Positive(Movable M) : M_(std::move(M)) {}
   Movable M_;
 };
Index: test/clang-tidy/check_clang_tidy.py
===

[PATCH] D52691: [clang-tidy] NFC use CHECK-NOTES in tests for performance-move-constructor-init

2018-10-02 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth marked 2 inline comments as done.
JonasToth added a comment.

check_clang_tidy now ignores `note: FIX-IT`, so only diagnostics directly 
emitted from the check are tested


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52691



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


[PATCH] D52691: [clang-tidy] NFC use CHECK-NOTES in tests for performance-move-constructor-init

2018-10-02 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 167918.
JonasToth added a comment.

- fix spurious change


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52691

Files:
  test/clang-tidy/check_clang_tidy.py
  test/clang-tidy/performance-move-constructor-init.cpp


Index: test/clang-tidy/performance-move-constructor-init.cpp
===
--- test/clang-tidy/performance-move-constructor-init.cpp
+++ test/clang-tidy/performance-move-constructor-init.cpp
@@ -30,9 +30,9 @@
 struct D : B {
   D() : B() {}
   D(const D &RHS) : B(RHS) {}
-  // CHECK-MESSAGES: :[[@LINE+3]]:16: warning: move constructor initializes 
base class by calling a copy constructor [performance-move-constructor-init]
-  // CHECK-MESSAGES: 26:3: note: copy constructor being called
-  // CHECK-MESSAGES: 27:3: note: candidate move constructor here
+  // CHECK-NOTES: :[[@LINE+3]]:16: warning: move constructor initializes base 
class by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
   D(D &&RHS) : B(RHS) {}
 };
 
@@ -75,8 +75,10 @@
 
 struct M {
   B Mem;
-  // CHECK-MESSAGES: :[[@LINE+1]]:16: warning: move constructor initializes 
class member by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: :[[@LINE+1]]:16: warning: move constructor initializes class 
member by calling a copy constructor [performance-move-constructor-init]
   M(M &&RHS) : Mem(RHS.Mem) {}
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
 };
 
 struct N {
@@ -109,7 +111,7 @@
 
 struct Positive {
   Positive(Movable M) : M_(M) {}
-  // CHECK-MESSAGES: [[@LINE-1]]:12: warning: pass by value and use std::move 
[modernize-pass-by-value]
+  // CHECK-NOTES: [[@LINE-1]]:12: warning: pass by value and use std::move 
[modernize-pass-by-value]
   // CHECK-FIXES: Positive(Movable M) : M_(std::move(M)) {}
   Movable M_;
 };
Index: test/clang-tidy/check_clang_tidy.py
===
--- test/clang-tidy/check_clang_tidy.py
+++ test/clang-tidy/check_clang_tidy.py
@@ -169,7 +169,7 @@
   subprocess.check_output(
   ['FileCheck', '-input-file=' + notes_file, input_file_name,
'-check-prefix=' + check_notes_prefix,
-   '-implicit-check-not={{note|warning|error}}:'],
+   '-implicit-check-not=warning|error}}:|note: (?!FIX-IT)}}'],
   stderr=subprocess.STDOUT)
 except subprocess.CalledProcessError as e:
   print('FileCheck failed:\n' + e.output.decode())


Index: test/clang-tidy/performance-move-constructor-init.cpp
===
--- test/clang-tidy/performance-move-constructor-init.cpp
+++ test/clang-tidy/performance-move-constructor-init.cpp
@@ -30,9 +30,9 @@
 struct D : B {
   D() : B() {}
   D(const D &RHS) : B(RHS) {}
-  // CHECK-MESSAGES: :[[@LINE+3]]:16: warning: move constructor initializes base class by calling a copy constructor [performance-move-constructor-init]
-  // CHECK-MESSAGES: 26:3: note: copy constructor being called
-  // CHECK-MESSAGES: 27:3: note: candidate move constructor here
+  // CHECK-NOTES: :[[@LINE+3]]:16: warning: move constructor initializes base class by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
   D(D &&RHS) : B(RHS) {}
 };
 
@@ -75,8 +75,10 @@
 
 struct M {
   B Mem;
-  // CHECK-MESSAGES: :[[@LINE+1]]:16: warning: move constructor initializes class member by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: :[[@LINE+1]]:16: warning: move constructor initializes class member by calling a copy constructor [performance-move-constructor-init]
   M(M &&RHS) : Mem(RHS.Mem) {}
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
 };
 
 struct N {
@@ -109,7 +111,7 @@
 
 struct Positive {
   Positive(Movable M) : M_(M) {}
-  // CHECK-MESSAGES: [[@LINE-1]]:12: warning: pass by value and use std::move [modernize-pass-by-value]
+  // CHECK-NOTES: [[@LINE-1]]:12: warning: pass by value and use std::move [modernize-pass-by-value]
   // CHECK-FIXES: Positive(Movable M) : M_(std::move(M)) {}
   Movable M_;
 };
Index: test/clang-tidy/check_clang_tidy.py
===
--- test/clang-tidy/check_clang_tidy.py
+++ test/clang-tidy/check_clang_tidy.py
@@ -169,7 +169,7 @@
   subprocess.check_output(
   ['FileCheck', '-input-file=' + notes_file, input_file_name,
'-check-prefix=' + check_notes_prefix,
-   '-implicit-check-not={{note|warning|error}}:'],
+   '-implicit-check-not=war

[PATCH] D52691: [clang-tidy] NFC use CHECK-NOTES in tests for performance-move-constructor-init

2018-10-02 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added inline comments.



Comment at: test/clang-tidy/check_clang_tidy.py:172
'-check-prefix=' + check_notes_prefix,
-   '-implicit-check-not={{note|warning|error}}:'],
+   '-implicit-check-not=warning|error}}:|note: (?!FIX-IT)}}'],
   stderr=subprocess.STDOUT)

SGTM, if it works.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52691



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


[PATCH] D52690: [clang-tidy] NFC use CHECK-NOTES in tests for misc-misplaced-const

2018-10-02 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 167919.
JonasToth added a comment.

- use absolute line number for note


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52690

Files:
  test/clang-tidy/misc-misplaced-const.c
  test/clang-tidy/misc-misplaced-const.cpp


Index: test/clang-tidy/misc-misplaced-const.cpp
===
--- test/clang-tidy/misc-misplaced-const.cpp
+++ test/clang-tidy/misc-misplaced-const.cpp
@@ -12,7 +12,8 @@
   if (const cip i = 0)
 ;
 
-  // CHECK-MESSAGES: :[[@LINE+1]]:16: warning: 'i' declared with a 
const-qualified typedef type; results in the type being 'int *const' instead of 
'const int *'
+  // CHECK-NOTES: :[[@LINE+2]]:16: warning: 'i' declared with a 
const-qualified typedef type; results in the type being 'int *const' instead of 
'const int *'
+  // CHECK-NOTES: :4:14: note: typedef declared here
   if (const ip i = 0)
 ;
 }
Index: test/clang-tidy/misc-misplaced-const.c
===
--- test/clang-tidy/misc-misplaced-const.c
+++ test/clang-tidy/misc-misplaced-const.c
@@ -14,28 +14,33 @@
 
   // Not ok
   const ip i3 = 0;
-  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: 'i3' declared with a 
const-qualified typedef type; results in the type being 'int *const' instead of 
'const int *'
+  // CHECK-NOTES: :[[@LINE-1]]:12: warning: 'i3' declared with a 
const-qualified typedef type; results in the type being 'int *const' instead of 
'const int *'
+  // CHECK-NOTES: :4:14: note: typedef declared here
 
   ip const i4 = 0;
-  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: 'i4' declared with a 
const-qualified
+  // CHECK-NOTES: :[[@LINE-1]]:12: warning: 'i4' declared with a 
const-qualified
+  // CHECK-NOTES: :4:14: note: typedef declared here
 
   const volatile ip i5 = 0;
-  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'i5' declared with a 
const-qualified typedef type; results in the type being 'int *const volatile' 
instead of 'const int *volatile'
+  // CHECK-NOTES: :[[@LINE-1]]:21: warning: 'i5' declared with a 
const-qualified typedef type; results in the type being 'int *const volatile' 
instead of 'const int *volatile'
+  // CHECK-NOTES: :4:14: note: typedef declared here
 }
 
 void func2(const plain_i *i1,
const cip i2,
const ip i3,
-   // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'i3' declared with a 
const-qualified
+   // CHECK-NOTES: :[[@LINE-1]]:21: warning: 'i3' declared with a 
const-qualified
+   // CHECK-NOTES: :4:14: note: typedef declared here
const int *i4) {
 }
 
 struct S {
   const int *i0;
   const plain_i *i1;
   const cip i2;
   const ip i3;
-  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: 'i3' declared with a 
const-qualified
+  // CHECK-NOTES: :[[@LINE-1]]:12: warning: 'i3' declared with a 
const-qualified
+  // CHECK-NOTES: :4:14: note: typedef declared here
 };
 
 // Function pointers should not be diagnosed because a function


Index: test/clang-tidy/misc-misplaced-const.cpp
===
--- test/clang-tidy/misc-misplaced-const.cpp
+++ test/clang-tidy/misc-misplaced-const.cpp
@@ -12,7 +12,8 @@
   if (const cip i = 0)
 ;
 
-  // CHECK-MESSAGES: :[[@LINE+1]]:16: warning: 'i' declared with a const-qualified typedef type; results in the type being 'int *const' instead of 'const int *'
+  // CHECK-NOTES: :[[@LINE+2]]:16: warning: 'i' declared with a const-qualified typedef type; results in the type being 'int *const' instead of 'const int *'
+  // CHECK-NOTES: :4:14: note: typedef declared here
   if (const ip i = 0)
 ;
 }
Index: test/clang-tidy/misc-misplaced-const.c
===
--- test/clang-tidy/misc-misplaced-const.c
+++ test/clang-tidy/misc-misplaced-const.c
@@ -14,28 +14,33 @@
 
   // Not ok
   const ip i3 = 0;
-  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: 'i3' declared with a const-qualified typedef type; results in the type being 'int *const' instead of 'const int *'
+  // CHECK-NOTES: :[[@LINE-1]]:12: warning: 'i3' declared with a const-qualified typedef type; results in the type being 'int *const' instead of 'const int *'
+  // CHECK-NOTES: :4:14: note: typedef declared here
 
   ip const i4 = 0;
-  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: 'i4' declared with a const-qualified
+  // CHECK-NOTES: :[[@LINE-1]]:12: warning: 'i4' declared with a const-qualified
+  // CHECK-NOTES: :4:14: note: typedef declared here
 
   const volatile ip i5 = 0;
-  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'i5' declared with a const-qualified typedef type; results in the type being 'int *const volatile' instead of 'const int *volatile'
+  // CHECK-NOTES: :[[@LINE-1]]:21: warning: 'i5' declared with a const-qualified typedef type; results in the type being 'int *const volatile' instead of 'const int *volatile'
+  // CHECK-NOTES: :4:14: note: typedef decla

[PATCH] D52750: [Diagnostics] Check for integer overflow in array size expressions

2018-10-02 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added inline comments.



Comment at: lib/Sema/SemaType.cpp:2231
   }
+
+  if (isa(ArraySize))

@rsmith what about this place for check?


https://reviews.llvm.org/D52750



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


[clang-tools-extra] r343578 - [clang-tidy] Ignore singe bit bitfield -> bool conversion in readability-implicit-bool-conversion

2018-10-02 Thread Alexander Kornienko via cfe-commits
Author: alexfh
Date: Tue Oct  2 04:38:41 2018
New Revision: 343578

URL: http://llvm.org/viewvc/llvm-project?rev=343578&view=rev
Log:
[clang-tidy] Ignore singe bit bitfield -> bool conversion in 
readability-implicit-bool-conversion

Modified:

clang-tools-extra/trunk/clang-tidy/readability/ImplicitBoolConversionCheck.cpp

clang-tools-extra/trunk/docs/clang-tidy/checks/readability-implicit-bool-conversion.rst

clang-tools-extra/trunk/test/clang-tidy/readability-implicit-bool-conversion.cpp

Modified: 
clang-tools-extra/trunk/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/ImplicitBoolConversionCheck.cpp?rev=343578&r1=343577&r2=343578&view=diff
==
--- 
clang-tools-extra/trunk/clang-tidy/readability/ImplicitBoolConversionCheck.cpp 
(original)
+++ 
clang-tools-extra/trunk/clang-tidy/readability/ImplicitBoolConversionCheck.cpp 
Tue Oct  2 04:38:41 2018
@@ -266,6 +266,7 @@ void ImplicitBoolConversionCheck::regist
 
   auto exceptionCases =
   expr(anyOf(allOf(isMacroExpansion(), unless(isNULLMacroExpansion())),
+ 
has(ignoringImplicit(memberExpr(hasDeclaration(fieldDecl(hasBitWidth(1)),
  hasParent(explicitCastExpr(;
   auto implicitCastFromBool = implicitCastExpr(
   anyOf(hasCastKind(CK_IntegralCast), hasCastKind(CK_IntegralToFloating),

Modified: 
clang-tools-extra/trunk/docs/clang-tidy/checks/readability-implicit-bool-conversion.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/checks/readability-implicit-bool-conversion.rst?rev=343578&r1=343577&r2=343578&view=diff
==
--- 
clang-tools-extra/trunk/docs/clang-tidy/checks/readability-implicit-bool-conversion.rst
 (original)
+++ 
clang-tools-extra/trunk/docs/clang-tidy/checks/readability-implicit-bool-conversion.rst
 Tue Oct  2 04:38:41 2018
@@ -66,7 +66,9 @@ example:
 
 In general, the following conversion types are checked:
 
-- integer expression/literal to boolean,
+- integer expression/literal to boolean (conversion from a single bit bitfield
+  to boolean is explicitly allowed, since there's no ambiguity / information
+  loss in this case),
 
 - floating expression/literal to boolean,
 

Modified: 
clang-tools-extra/trunk/test/clang-tidy/readability-implicit-bool-conversion.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/readability-implicit-bool-conversion.cpp?rev=343578&r1=343577&r2=343578&view=diff
==
--- 
clang-tools-extra/trunk/test/clang-tidy/readability-implicit-bool-conversion.cpp
 (original)
+++ 
clang-tools-extra/trunk/test/clang-tidy/readability-implicit-bool-conversion.cpp
 Tue Oct  2 04:38:41 2018
@@ -437,3 +437,24 @@ void useOfUserConversion() {
 }
 
 } // namespace ignoreUserDefinedConversionOperator
+
+namespace ignore_1bit_bitfields {
+
+struct S {
+  int a;
+  int b : 1;
+  int c : 2;
+};
+
+bool f(const S& s) {
+  functionTaking(s.a);
+  // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: implicit conversion 'int' -> 
bool
+  // CHECK-FIXES: functionTaking(s.a != 0);
+  functionTaking(s.b);
+  // CHECK-FIXES: functionTaking(s.b);
+  functionTaking(s.c);
+  // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: implicit conversion 'int' -> 
bool
+  // CHECK-FIXES: functionTaking(s.c != 0);
+}
+
+} // namespace ignore_1bit_bitfields


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


[PATCH] D52738: [AST] Pack the bit-fields of FunctionProtoType into Type.

2018-10-02 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL343579: [AST] Pack the bit-fields of FunctionProtoType into 
Type. (authored by brunoricci, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D52738?vs=16&id=167922#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D52738

Files:
  cfe/trunk/include/clang/AST/Type.h
  cfe/trunk/lib/AST/ASTContext.cpp
  cfe/trunk/lib/AST/Type.cpp

Index: cfe/trunk/include/clang/AST/Type.h
===
--- cfe/trunk/include/clang/AST/Type.h
+++ cfe/trunk/include/clang/AST/Type.h
@@ -1502,6 +1502,9 @@
 unsigned Kind : 8;
   };
 
+  /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
+  /// Only common bits are stored here. Additional uncommon bits are stored
+  /// in a trailing object after FunctionProtoType.
   class FunctionTypeBitfields {
 friend class FunctionProtoType;
 friend class FunctionType;
@@ -1512,18 +1515,36 @@
 /// regparm and the calling convention.
 unsigned ExtInfo : 12;
 
+/// The ref-qualifier associated with a \c FunctionProtoType.
+///
+/// This is a value of type \c RefQualifierKind.
+unsigned RefQualifier : 2;
+
 /// Used only by FunctionProtoType, put here to pack with the
 /// other bitfields.
 /// The qualifiers are part of FunctionProtoType because...
 ///
 /// C++ 8.3.5p4: The return type, the parameter type list and the
 /// cv-qualifier-seq, [...], are part of the function type.
 unsigned TypeQuals : 4;
 
-/// The ref-qualifier associated with a \c FunctionProtoType.
-///
-/// This is a value of type \c RefQualifierKind.
-unsigned RefQualifier : 2;
+/// The number of parameters this function has, not counting '...'.
+/// According to [implimits] 8 bits should be enough here but this is
+/// somewhat easy to exceed with metaprogramming and so we would like to
+/// keep NumParams as wide as reasonably possible.
+unsigned NumParams : 16;
+
+/// The type of exception specification this function has.
+unsigned ExceptionSpecType : 4;
+
+/// Whether this function has extended parameter information.
+unsigned HasExtParameterInfos : 1;
+
+/// Whether the function is variadic.
+unsigned Variadic : 1;
+
+/// Whether this function has a trailing return type.
+unsigned HasTrailingReturn : 1;
   };
 
   class ObjCObjectTypeBitfields {
@@ -3331,6 +3352,92 @@
   QualType ResultType;
 
 public:
+  /// Interesting information about a specific parameter that can't simply
+  /// be reflected in parameter's type. This is only used by FunctionProtoType
+  /// but is in FunctionType to make this class available during the
+  /// specification of the bases of FunctionProtoType.
+  ///
+  /// It makes sense to model language features this way when there's some
+  /// sort of parameter-specific override (such as an attribute) that
+  /// affects how the function is called.  For example, the ARC ns_consumed
+  /// attribute changes whether a parameter is passed at +0 (the default)
+  /// or +1 (ns_consumed).  This must be reflected in the function type,
+  /// but isn't really a change to the parameter type.
+  ///
+  /// One serious disadvantage of modelling language features this way is
+  /// that they generally do not work with language features that attempt
+  /// to destructure types.  For example, template argument deduction will
+  /// not be able to match a parameter declared as
+  ///   T (*)(U)
+  /// against an argument of type
+  ///   void (*)(__attribute__((ns_consumed)) id)
+  /// because the substitution of T=void, U=id into the former will
+  /// not produce the latter.
+  class ExtParameterInfo {
+enum {
+  ABIMask = 0x0F,
+  IsConsumed = 0x10,
+  HasPassObjSize = 0x20,
+  IsNoEscape = 0x40,
+};
+unsigned char Data = 0;
+
+  public:
+ExtParameterInfo() = default;
+
+/// Return the ABI treatment of this parameter.
+ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
+ExtParameterInfo withABI(ParameterABI kind) const {
+  ExtParameterInfo copy = *this;
+  copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
+  return copy;
+}
+
+/// Is this parameter considered "consumed" by Objective-C ARC?
+/// Consumed parameters must have retainable object type.
+bool isConsumed() const { return (Data & IsConsumed); }
+ExtParameterInfo withIsConsumed(bool consumed) const {
+  ExtParameterInfo copy = *this;
+  if (consumed)
+copy.Data |= IsConsumed;
+  else
+copy.Data &= ~IsConsumed;
+  return copy;
+}
+
+bool hasPassObjectSize() const { return Data & HasPassObjSize; }
+ExtParameterInfo withHasPassObjectSize() const {
+  ExtParameterInfo Copy = *this;
+  Copy.Data |= HasPassObjSize;
+  return Copy;
+}
+

r343579 - [AST] Pack the bit-fields of FunctionProtoType into Type.

2018-10-02 Thread Bruno Ricci via cfe-commits
Author: brunoricci
Date: Tue Oct  2 04:46:38 2018
New Revision: 343579

URL: http://llvm.org/viewvc/llvm-project?rev=343579&view=rev
Log:
[AST] Pack the bit-fields of FunctionProtoType into Type.

Move the bit-fields of FunctionProtoType into FunctionTypeBitfields.
This cuts the size of FunctionProtoType by a pointer. Additionally use
llvm::TrailingObjects instead of manually doing the casts + arithmetic.

This patch is bigger then what could be expected for the following reasons:

1. As discussed before in D50631 it would be nice if there was some space left
   in FunctionTypeBitfields for future additions. This patch introduces an
   extra structure FunctionTypeExtraBitfields which is supposed to hold
   uncommon bits and is stored in a trailing object. The number of exception
   types NumExceptions is moved to this struct. As of this patch this trailing
   struct will only be allocated if we have > 0 types in a dynamic exception
   specification.

2. TrailingObjects cannot handle repeated types. Therefore the QualType
   representing an exception type is wrapped in a struct ExceptionType.
   The ExceptionType * is then reinterpret_cast'd to QualType *.

3. TrailingObjects needs the definition of the various trailing classes.
   Therefore ExtParameterInfo, ExceptionType and FunctionTypeExtraBitfields
   are put in FunctionType.

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

Reviewed By: rjmccall


Modified:
cfe/trunk/include/clang/AST/Type.h
cfe/trunk/lib/AST/ASTContext.cpp
cfe/trunk/lib/AST/Type.cpp

Modified: cfe/trunk/include/clang/AST/Type.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Type.h?rev=343579&r1=343578&r2=343579&view=diff
==
--- cfe/trunk/include/clang/AST/Type.h (original)
+++ cfe/trunk/include/clang/AST/Type.h Tue Oct  2 04:46:38 2018
@@ -1502,6 +1502,9 @@ protected:
 unsigned Kind : 8;
   };
 
+  /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
+  /// Only common bits are stored here. Additional uncommon bits are stored
+  /// in a trailing object after FunctionProtoType.
   class FunctionTypeBitfields {
 friend class FunctionProtoType;
 friend class FunctionType;
@@ -1512,6 +1515,11 @@ protected:
 /// regparm and the calling convention.
 unsigned ExtInfo : 12;
 
+/// The ref-qualifier associated with a \c FunctionProtoType.
+///
+/// This is a value of type \c RefQualifierKind.
+unsigned RefQualifier : 2;
+
 /// Used only by FunctionProtoType, put here to pack with the
 /// other bitfields.
 /// The qualifiers are part of FunctionProtoType because...
@@ -1520,10 +1528,23 @@ protected:
 /// cv-qualifier-seq, [...], are part of the function type.
 unsigned TypeQuals : 4;
 
-/// The ref-qualifier associated with a \c FunctionProtoType.
-///
-/// This is a value of type \c RefQualifierKind.
-unsigned RefQualifier : 2;
+/// The number of parameters this function has, not counting '...'.
+/// According to [implimits] 8 bits should be enough here but this is
+/// somewhat easy to exceed with metaprogramming and so we would like to
+/// keep NumParams as wide as reasonably possible.
+unsigned NumParams : 16;
+
+/// The type of exception specification this function has.
+unsigned ExceptionSpecType : 4;
+
+/// Whether this function has extended parameter information.
+unsigned HasExtParameterInfos : 1;
+
+/// Whether the function is variadic.
+unsigned Variadic : 1;
+
+/// Whether this function has a trailing return type.
+unsigned HasTrailingReturn : 1;
   };
 
   class ObjCObjectTypeBitfields {
@@ -3331,6 +3352,92 @@ class FunctionType : public Type {
   QualType ResultType;
 
 public:
+  /// Interesting information about a specific parameter that can't simply
+  /// be reflected in parameter's type. This is only used by FunctionProtoType
+  /// but is in FunctionType to make this class available during the
+  /// specification of the bases of FunctionProtoType.
+  ///
+  /// It makes sense to model language features this way when there's some
+  /// sort of parameter-specific override (such as an attribute) that
+  /// affects how the function is called.  For example, the ARC ns_consumed
+  /// attribute changes whether a parameter is passed at +0 (the default)
+  /// or +1 (ns_consumed).  This must be reflected in the function type,
+  /// but isn't really a change to the parameter type.
+  ///
+  /// One serious disadvantage of modelling language features this way is
+  /// that they generally do not work with language features that attempt
+  /// to destructure types.  For example, template argument deduction will
+  /// not be able to match a parameter declared as
+  ///   T (*)(U)
+  /// against an argument of type
+  ///   void (*)(__attribute__((ns_consumed)) id)
+  /// because the substitution of T=void, U=id into 

[clang-tools-extra] r343580 - [clangd] Dex iterator printer shows query structure, not iterator state.

2018-10-02 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Tue Oct  2 04:51:36 2018
New Revision: 343580

URL: http://llvm.org/viewvc/llvm-project?rev=343580&view=rev
Log:
[clangd] Dex iterator printer shows query structure, not iterator state.

Summary:
This makes it suitable for logging (which immediately found a bug, to
be fixed in the next patch...)

Reviewers: ioeric

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

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

Modified:
clang-tools-extra/trunk/clangd/index/dex/Dex.cpp
clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp
clang-tools-extra/trunk/clangd/index/dex/PostingList.cpp
clang-tools-extra/trunk/clangd/index/dex/PostingList.h
clang-tools-extra/trunk/clangd/index/dex/Token.h
clang-tools-extra/trunk/unittests/clangd/DexTests.cpp

Modified: clang-tools-extra/trunk/clangd/index/dex/Dex.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/dex/Dex.cpp?rev=343580&r1=343579&r2=343580&view=diff
==
--- clang-tools-extra/trunk/clangd/index/dex/Dex.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/dex/Dex.cpp Tue Oct  2 04:51:36 2018
@@ -16,6 +16,7 @@
 #include "index/Index.h"
 #include "index/dex/Iterator.h"
 #include "llvm/ADT/StringSet.h"
+#include "llvm/Support/ScopedPrinter.h"
 #include 
 #include 
 
@@ -85,13 +86,13 @@ std::vector> c
   // ProximityPaths. Boosting factor should depend on the distance to the
   // Proximity Path: the closer processed path is, the higher boosting factor.
   for (const auto &ParentURI : ParentURIs.keys()) {
-const auto It =
-InvertedIndex.find(Token(Token::Kind::ProximityURI, ParentURI));
+Token Tok(Token::Kind::ProximityURI, ParentURI);
+const auto It = InvertedIndex.find(Tok);
 if (It != InvertedIndex.end()) {
   // FIXME(kbobyrev): Append LIMIT on top of every BOOST iterator.
   PathProximitySignals.SymbolURI = ParentURI;
-  BoostingIterators.push_back(
-  createBoost(It->second.iterator(), PathProximitySignals.evaluate()));
+  BoostingIterators.push_back(createBoost(It->second.iterator(&It->first),
+  
PathProximitySignals.evaluate()));
 }
   }
   return BoostingIterators;
@@ -142,7 +143,6 @@ bool Dex::fuzzyFind(const FuzzyFindReque
 llvm::function_ref Callback) const {
   assert(!StringRef(Req.Query).contains("::") &&
  "There must be no :: in query.");
-  // FIXME: attach the query tree to the trace span.
   trace::Span Tracer("Dex fuzzyFind");
   FuzzyMatcher Filter(Req.Query);
   bool More = false;
@@ -156,7 +156,7 @@ bool Dex::fuzzyFind(const FuzzyFindReque
   for (const auto &Trigram : TrigramTokens) {
 const auto It = InvertedIndex.find(Trigram);
 if (It != InvertedIndex.end())
-  TrigramIterators.push_back(It->second.iterator());
+  TrigramIterators.push_back(It->second.iterator(&It->first));
   }
   if (!TrigramIterators.empty())
 TopLevelChildren.push_back(createAnd(move(TrigramIterators)));
@@ -164,9 +164,10 @@ bool Dex::fuzzyFind(const FuzzyFindReque
   // Generate scope tokens for search query.
   std::vector> ScopeIterators;
   for (const auto &Scope : Req.Scopes) {
-const auto It = InvertedIndex.find(Token(Token::Kind::Scope, Scope));
+Token Tok(Token::Kind::Scope, Scope);
+const auto It = InvertedIndex.find(Tok);
 if (It != InvertedIndex.end())
-  ScopeIterators.push_back(It->second.iterator());
+  ScopeIterators.push_back(It->second.iterator(&It->first));
   }
   if (Req.AnyScope)
 ScopeIterators.push_back(createBoost(createTrue(Symbols.size()),
@@ -189,7 +190,8 @@ bool Dex::fuzzyFind(const FuzzyFindReque
 
   if (Req.RestrictForCodeCompletion)
 TopLevelChildren.push_back(
-InvertedIndex.find(RestrictedForCodeCompletion)->second.iterator());
+InvertedIndex.find(RestrictedForCodeCompletion)
+->second.iterator(&RestrictedForCodeCompletion));
 
   // Use TRUE iterator if both trigrams and scopes from the query are not
   // present in the symbol index.
@@ -203,6 +205,8 @@ bool Dex::fuzzyFind(const FuzzyFindReque
   // when the requested number of items is small.
   auto Root = Req.Limit ? createLimit(move(QueryIterator), *Req.Limit * 100)
 : move(QueryIterator);
+  SPAN_ATTACH(Tracer, "query", llvm::to_string(*Root));
+  vlog("Dex query tree: {0}", *Root);
 
   using IDAndScore = std::pair;
   std::vector IDAndScores = consume(*Root);

Modified: clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp?rev=343580&r1=343579&r2=343580&view=diff
==
--- clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp Tue Oc

[PATCH] D52715: [clangd] Dex iterator printer shows query structure, not iterator state.

2018-10-02 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
sammccall marked an inline comment as done.
Closed by commit rCTE343580: [clangd] Dex iterator printer shows query 
structure, not iterator state. (authored by sammccall, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D52715?vs=167694&id=167925#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52715

Files:
  clangd/index/dex/Dex.cpp
  clangd/index/dex/Iterator.cpp
  clangd/index/dex/PostingList.cpp
  clangd/index/dex/PostingList.h
  clangd/index/dex/Token.h
  unittests/clangd/DexTests.cpp

Index: unittests/clangd/DexTests.cpp
===
--- unittests/clangd/DexTests.cpp
+++ unittests/clangd/DexTests.cpp
@@ -226,18 +226,20 @@
 }
 
 TEST(DexIterators, StringRepresentation) {
-  const PostingList L0({4, 7, 8, 20, 42, 100});
-  const PostingList L1({1, 3, 5, 8, 9});
-  const PostingList L2({1, 5, 7, 9});
-  const PostingList L3({0, 5});
-  const PostingList L4({0, 1, 5});
-
-  EXPECT_EQ(llvm::to_string(*(L0.iterator())), "[4 ...]");
-  auto It = L0.iterator();
-  It->advanceTo(19);
-  EXPECT_EQ(llvm::to_string(*It), "[... 20 ...]");
-  It->advanceTo(9000);
-  EXPECT_EQ(llvm::to_string(*It), "[... END]");
+  const PostingList L1({1, 3, 5});
+  const PostingList L2({1, 7, 9});
+
+  // No token given, prints full posting list.
+  auto I1 = L1.iterator();
+  EXPECT_EQ(llvm::to_string(*I1), "[1 3 5]");
+
+  // Token given, uses token's string representation.
+  Token Tok(Token::Kind::Trigram, "L2");
+  auto I2 = L1.iterator(&Tok);
+  EXPECT_EQ(llvm::to_string(*I2), "T=L2");
+
+  auto Tree = createLimit(createAnd(move(I1), move(I2)), 10);
+  EXPECT_EQ(llvm::to_string(*Tree), "(LIMIT 10 (& [1 3 5] T=L2))");
 }
 
 TEST(DexIterators, Limit) {
Index: clangd/index/dex/Iterator.cpp
===
--- clangd/index/dex/Iterator.cpp
+++ clangd/index/dex/Iterator.cpp
@@ -243,8 +243,7 @@
 
 private:
   llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
-OS << "(TRUE {" << Index << "} out of " << Size << ")";
-return OS;
+return OS << "true";
   }
 
   DocID Index = 0;
@@ -273,8 +272,7 @@
 
 private:
   llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
-OS << "(BOOST " << Factor << ' ' << *Child << ')';
-return OS;
+return OS << "(* " << Factor << ' ' << *Child << ')';
   }
 
   std::unique_ptr Child;
@@ -314,8 +312,7 @@
 
 private:
   llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
-OS << "(LIMIT " << Limit << '(' << ItemsLeft << ") " << *Child << ')';
-return OS;
+return OS << "(LIMIT " << Limit << " " << *Child << ')';
   }
 
   std::unique_ptr Child;
Index: clangd/index/dex/Token.h
===
--- clangd/index/dex/Token.h
+++ clangd/index/dex/Token.h
@@ -82,6 +82,20 @@
   Kind TokenKind;
 
   friend llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Token &T) {
+switch (T.TokenKind) {
+case Kind::Trigram:
+  OS << "T=";
+  break;
+case Kind::Scope:
+  OS << "S=";
+  break;
+case Kind::ProximityURI:
+  OS << "U=";
+  break;
+case Kind::Sentinel:
+  OS << "?=";
+  break;
+}
 return OS << T.Data;
   }
 
Index: clangd/index/dex/PostingList.h
===
--- clangd/index/dex/PostingList.h
+++ clangd/index/dex/PostingList.h
@@ -33,8 +33,7 @@
 namespace clang {
 namespace clangd {
 namespace dex {
-
-class Iterator;
+struct Token;
 
 /// NOTE: This is an implementation detail.
 ///
@@ -64,7 +63,8 @@
 
   /// Constructs DocumentIterator over given posting list. DocumentIterator will
   /// go through the chunks and decompress them on-the-fly when necessary.
-  std::unique_ptr iterator() const;
+  /// If given, Tok is only used for the string representation.
+  std::unique_ptr iterator(const Token *Tok = nullptr) const;
 
   /// Returns in-memory size of external storage.
   size_t bytes() const { return Chunks.capacity() * sizeof(Chunk); }
Index: clangd/index/dex/Dex.cpp
===
--- clangd/index/dex/Dex.cpp
+++ clangd/index/dex/Dex.cpp
@@ -16,6 +16,7 @@
 #include "index/Index.h"
 #include "index/dex/Iterator.h"
 #include "llvm/ADT/StringSet.h"
+#include "llvm/Support/ScopedPrinter.h"
 #include 
 #include 
 
@@ -85,13 +86,13 @@
   // ProximityPaths. Boosting factor should depend on the distance to the
   // Proximity Path: the closer processed path is, the higher boosting factor.
   for (const auto &ParentURI : ParentURIs.keys()) {
-const auto It =
-InvertedIndex.find(Token(Token::Kind::ProximityURI, ParentURI));
+Token Tok(Token::Kind::ProximityURI, ParentURI);
+const auto It = InvertedIndex.find(Tok);
 if (It != InvertedIndex.end()) {
   // FIXME(kbobyrev): Append LIMI

[PATCH] D52742: [analyzer][WIP] Add macro expansions to the plist output

2018-10-02 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus updated this revision to Diff 167924.
Szelethus added a comment.

- Fixes according to @whisperity's comments
- New test cases for
  - commas in brackets,
  - commas in braces,
  - macro arguments left empty.

> (The whole thing, however, is generally disgusting. I'd've expected the 
> Preprocessor to readily contain a lot of stuff that's going on here.)

Don't even get me started.


https://reviews.llvm.org/D52742

Files:
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  lib/StaticAnalyzer/Core/BugReporter.cpp
  lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
  test/Analysis/plist-macros-with-expansion.cpp

Index: test/Analysis/plist-macros-with-expansion.cpp
===
--- /dev/null
+++ test/Analysis/plist-macros-with-expansion.cpp
@@ -0,0 +1,212 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+//
+// RUN: %clang_analyze_cc1 -analyzer-checker=core %s  \
+// RUN:   -analyzer-output=plist -o %t.plist \
+// RUN:   -analyzer-config expand-macros=true \
+// RUN:
+// RUN: FileCheck --input-file=%t.plist %s
+
+void print(const void*);
+
+//===--===//
+// Tests for non-function-like macro expansions.
+//===--===//
+
+#define SET_PTR_VAR_TO_NULL \
+  ptr = 0
+
+void nonFunctionLikeMacroTest() {
+  int *ptr;
+  SET_PTR_VAR_TO_NULL;
+  *ptr = 5; // expected-warning{{Dereference of null pointer}}
+}
+
+// CHECK: Expanding macro 'SET_PTR_VAR_TO_NULL' to 'ptr = 0 '
+
+#define NULL 0
+#define SET_PTR_VAR_TO_NULL_WITH_NESTED_MACRO \
+  ptr = NULL
+
+void nonFunctionLikeNestedMacroTest() {
+  int *ptr;
+  SET_PTR_VAR_TO_NULL_WITH_NESTED_MACRO;
+  *ptr = 5; // expected-warning{{Dereference of null pointer}}
+}
+
+// CHECK: Expanding macro 'SET_PTR_VAR_TO_NULL' to 'ptr = 0 '
+
+//===--===//
+// Tests for function-like macro expansions.
+//===--===//
+
+void setToNull(int **vptr) {
+  *vptr = nullptr;
+}
+
+#define TO_NULL(x) \
+  setToNull(x)
+
+void functionLikeMacroTest() {
+  int *ptr;
+  TO_NULL(&ptr);
+  *ptr = 5; // expected-warning{{Dereference of null pointer}}
+}
+
+// CHECK: Expanding macro 'TO_NULL' to 'setToNull ( & a ) '
+
+#define DOES_NOTHING(x) \
+  { \
+int b;  \
+b = 5;  \
+  } \
+  print(x)
+
+#define DEREF(x)   \
+  DOES_NOTHING(x); \
+  *x
+
+void functionLikeNestedMacroTest() {
+  int *a;
+  TO_NULL(&a);
+  DEREF(a) = 5; // expected-warning{{Dereference of null pointer}}
+}
+
+// CHECK: Expanding macro 'TO_NULL' to 'setToNull ( & a ) '
+
+// CHECK: Expanding macro 'DEREF' to '{ int b ; b = 5 ; } print ( a ) ; * a '
+
+//===--===//
+// Tests for macro arguments containing commas and parantheses.
+//
+// As of writing these tests, the algorithm expands macro arguments by lexing
+// the macro's expansion location, and relies on finding tok::comma and
+// tok::l_paren/tok::r_paren.
+//===--===//
+
+// Note that this commas, parantheses in strings aren't parsed as tok::comma or
+// tok::l_paren/tok::r_paren, but why not test them.
+
+#define TO_NULL_AND_PRINT(x, str) \
+  x = 0; \
+  print(str)
+
+void macroArgContainsCommaInStringTest() {
+  int *a;
+  TO_NULL_AND_PRINT(a, "Will this , cause a crash?");
+  *a = 5; // expected-warning{{Dereference of null pointer}}
+}
+
+// CHECK: Expanding macro 'TO_NULL_AND_PRINT' to 'a = 0 ; print ( "Will this , cause a crash?" ) '
+
+void macroArgContainsLParenInStringTest() {
+  int *a;
+  TO_NULL_AND_PRINT(a, "Will this ( cause a crash?");
+  *a = 5; // expected-warning{{Dereference of null pointer}}
+}
+
+// CHECK: Expanding macro 'TO_NULL_AND_PRINT' to 'a = 0 ; print ( "Will this ( cause a crash?" ) '
+
+void macroArgContainsRParenInStringTest() {
+  int *a;
+  TO_NULL_AND_PRINT(a, "Will this ) cause a crash?");
+  *a = 5; // expected-warning{{Dereference of null pointer}}
+}
+
+// CHECK: Expanding macro 'TO_NULL_AND_PRINT' to 'a = 0 ; print ( "Will this ) cause a crash?" ) '
+
+#define CALL_FUNCTION(funcCall)   \
+  funcCall
+
+// Function calls do contain both tok::comma and tok::l_paren/tok::r_paren.
+
+void macroArgContainsLParenRParenTest() {
+  int *a;
+  CALL_FUNCTION(setToNull(&a));
+  *a = 5; // expected-warning{{Dereference of null pointer}}
+}
+
+// CHECK: Expanding macro 'CALL_FUNCTION' to 'setToNull ( & a ) '
+
+void setToNullAndPrint(int **vptr, const char *str) {
+  setToNull(vptr);
+  print(str);
+}
+
+void macroArgContainsCommaLParenRParenTest() {
+  int *a;
+  CALL_FUNCTION(setToNullAndPrint(&a, "Hello!"));
+  *a = 5; // expected-warning{{Derefer

[PATCH] D52742: [analyzer][WIP] Add macro expansions to the plist output

2018-10-02 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus marked 13 inline comments as done.
Szelethus added inline comments.



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:292
+
+  // Output the location.
+  FullSourceLoc L = P.getLocation().asLocation();

whisperity wrote:
> the location of what?
This is fairly obvious from the context, and is used throughout the whole file, 
so I'm leaving this one as is.



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:737
+
+  for (auto It = MI->tokens_begin(), E = MI->tokens_end(); It != E;) {
+Token T = *It;

whisperity wrote:
> Unnecessary `;` at the end?
It is actually necessary ^-^



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:765
+  if (MacroArgMap && MacroArgMap->count(II)) {
+for (Token ExpandedArgT : MacroArgMap->at(II)) {
+  ExpansionOS << PP.getSpelling(ExpandedArgT) + ' ';

whisperity wrote:
> `Token&` so copies are explicitly not created?
I've seen `Token` being copied all over the place in other files, but after 
looking at it's implementation, const ref should be better.



Comment at: test/Analysis/plist-macros-with-expansion.cpp:24
+
+// CHECK: Expanding macro 'SET_PTR_VAR_TO_NULL' to 'ptr 
= 0 '
+

whisperity wrote:
> Why do we use the HTML entity tag `'` instead of `'`? Is the PList 
> output expanded this much?
Yup, unfortunately.


https://reviews.llvm.org/D52742



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


[PATCH] D52773: clang-cl: Add /showFilenames option (PR31957)

2018-10-02 Thread Stephen Kelly via Phabricator via cfe-commits
steveire added inline comments.



Comment at: lib/Frontend/CompilerInvocation.cpp:792
   Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
+  if (Args.hasArg(OPT_echo_main_file_name))
+llvm::outs() << Opts.MainFileName << "\n";

I'll have to keep a patch around anyway for myself locally to remove this 
condition. But maybe someone else will benefit from this.

What do you think about changing CMake to so that this is passed by default 
when using Clang-CL?



https://reviews.llvm.org/D52773



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


[PATCH] D52773: clang-cl: Add /showFilenames option (PR31957)

2018-10-02 Thread Zachary Turner via Phabricator via cfe-commits
zturner added inline comments.



Comment at: lib/Frontend/CompilerInvocation.cpp:792
   Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
+  if (Args.hasArg(OPT_echo_main_file_name))
+llvm::outs() << Opts.MainFileName << "\n";

steveire wrote:
> I'll have to keep a patch around anyway for myself locally to remove this 
> condition. But maybe someone else will benefit from this.
> 
> What do you think about changing CMake to so that this is passed by default 
> when using Clang-CL?
> 
Do you mean llvms cmake?  Or cmake itself?  Which generator are you using?


https://reviews.llvm.org/D52773



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


[PATCH] D52730: [analyzer] ConversionChecker: handle floating point

2018-10-02 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy updated this revision to Diff 167929.
donat.nagy added a comment.

Fix formatting in tests; add a comment.


Repository:
  rC Clang

https://reviews.llvm.org/D52730

Files:
  lib/StaticAnalyzer/Checkers/ConversionChecker.cpp
  test/Analysis/conversion.c

Index: test/Analysis/conversion.c
===
--- test/Analysis/conversion.c
+++ test/Analysis/conversion.c
@@ -137,6 +137,12 @@
   U8 = S + 10;
 }
 
+char dontwarn6(long long x) {
+  long long y = 42;
+  y += x;
+  return y == 42;
+}
+
 
 // false positives..
 
@@ -155,7 +161,7 @@
 # define EOF (-1)
 char reply_string[8192];
 FILE *cin;
-extern int dostuff (void);
+extern int dostuff(void);
 int falsePositive2() {
   int c, n;
   int dig;
@@ -181,3 +187,26 @@
   }
 }
 
+double floating_point(long long a, int b) {
+  if (a > 1LL << 55) {
+double r = a; // expected-warning {{Loss of precision}}
+return r;
+  } else if (b > 1 << 25) {
+float f = b; // expected-warning {{Loss of precision}}
+return f;
+  }
+  return 137;
+}
+
+double floating_point2() {
+  int a = 1 << 24;
+  long long b = 1LL << 53;
+  double d = a; // no-warning
+  double f = b; // no-warning
+  return d - f;
+}
+
+int floating_point_3(unsigned long long a) {
+  double b = a; // no-warning
+  return 42;
+}
Index: lib/StaticAnalyzer/Checkers/ConversionChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/ConversionChecker.cpp
+++ lib/StaticAnalyzer/Checkers/ConversionChecker.cpp
@@ -14,8 +14,10 @@
 // of expressions. A warning is reported when:
 // * a negative value is implicitly converted to an unsigned value in an
 //   assignment, comparison or multiplication.
-// * assignment / initialization when source value is greater than the max
-//   value of target
+// * assignment / initialization when the source value is greater than the max
+//   value of the target integer type
+// * assignment / initialization when the source integer is above the range
+//   where the target floating point type can represent all integers
 //
 // Many compilers and tools have similar checks that are based on semantic
 // analysis. Those checks are sound but have poor precision. ConversionChecker
@@ -29,6 +31,8 @@
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 
+#include 
+
 using namespace clang;
 using namespace ento;
 
@@ -132,19 +136,66 @@
 
   QualType SubType = Cast->IgnoreParenImpCasts()->getType();
 
-  if (!DestType->isIntegerType() || !SubType->isIntegerType())
+  if (!DestType->isRealType() || !SubType->isIntegerType())
 return false;
 
-  if (C.getASTContext().getIntWidth(DestType) >=
-  C.getASTContext().getIntWidth(SubType))
+  const bool isInteger = DestType->isIntegerType();
+
+  const auto &AC = C.getASTContext();
+
+  // We will find the largest RepresentsUntilExp value such that the DestType
+  // can exactly represent all integers 0 <= n < 2^RepresentsUntilExp
+  unsigned RepresentsUntilExp;
+
+  if (isInteger) {
+RepresentsUntilExp = AC.getIntWidth(DestType);
+if (RepresentsUntilExp == 1) {
+  // This is just casting a number to bool, probably not a bug.
+  return false;
+}
+if (DestType->isSignedIntegerType()) {
+  RepresentsUntilExp--;
+}
+  } else {
+unsigned FloatingSize = AC.getTypeSize(DestType);
+switch (FloatingSize) {
+  case 64:
+// double and possibly long double on some systems
+RepresentsUntilExp = 53; break;
+  case 32:
+// float
+RepresentsUntilExp = 24; break;
+  case 16:
+// _Float16
+RepresentsUntilExp = 12; break;
+  default:
+// larger types, which can represent all integers below 2^64
+return false;
+}
+  }
+
+  if (RepresentsUntilExp >= sizeof(unsigned long long)*CHAR_BIT) {
+// Avoid overflow in our later calculations
 return false;
+  }
 
-  unsigned W = C.getASTContext().getIntWidth(DestType);
-  if (W == 1 || W >= 64U)
+  unsigned CorrectedSrcWidth = AC.getIntWidth(SubType);
+  if (SubType->isSignedIntegerType()) {
+CorrectedSrcWidth--;
+  }
+
+  if (RepresentsUntilExp >= CorrectedSrcWidth) {
+// Simple case: the destination can store all values of the source type.
 return false;
+  }
 
-  unsigned long long MaxVal = 1ULL << W;
+  unsigned long long MaxVal = 1ULL << RepresentsUntilExp;
+  if (!isInteger) {
+// if this is a floating point type, it can also represent MaxVal exactly
+MaxVal++;
+  }
   return C.isGreaterOrEqual(Cast->getSubExpr(), MaxVal);
+  // TODO: maybe also check negative values with too large magnitude
 }
 
 bool ConversionChecker::isLossOfSign(const ImplicitCastExpr *Cast,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52730: [analyzer] ConversionChecker: handle floating point

2018-10-02 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy marked 6 inline comments as done.
donat.nagy added inline comments.



Comment at: lib/StaticAnalyzer/Checkers/ConversionChecker.cpp:175
+
+  if (RepresentsUntilExp >= sizeof(unsigned long long)*8) {
 return false;

NoQ wrote:
> Szelethus wrote:
> > Szelethus wrote:
> > > How about `AC.getSizeType(AC.UnsignedLongLongTy))`?
> > I'm actually not too sure about this. @whisperity?
> Yeah, i suspect it's a host machine check (to prevent our own overflow on 
> line 189) rather than a target machine check.
Yes, this is intended to be a host machine check (corresponding to the `W >= 
64U` in the old version). I will add a comment to clarify this.


Repository:
  rC Clang

https://reviews.llvm.org/D52730



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


r343581 - [analyzer] Improvements to the SMT API

2018-10-02 Thread Mikhail R. Gadelha via cfe-commits
Author: mramalho
Date: Tue Oct  2 05:55:48 2018
New Revision: 343581

URL: http://llvm.org/viewvc/llvm-project?rev=343581&view=rev
Log:
[analyzer] Improvements to the SMT API

Summary:
Several improvements in preparation for the new backends.

Refactoring:

- Removed duplicated methods `fromBoolean`, `fromAPSInt`, `fromInt` and 
`fromAPFloat`. The methods `mkBoolean`, `mkBitvector` and `mkFloat` are now 
used instead.
- The names of the functions that convert BVs to FPs were swapped (`mkSBVtoFP`, 
`mkUBVtoFP`, `mkFPtoSBV`, `mkFPtoUBV`).
- Added a couple of comments in function calls.

Crosscheck encoding:

- Changed how constraints are encoded in the refutation manager so it doesn't 
start with (false OR ...). This change introduces one duplicated line (see file 
`BugReporterVisitors.cpp`, the `SMTConv::getRangeExpr is called twice, so I can 
remove this change if the duplication is a problem.

Reviewers: george.karpenkov, NoQ

Reviewed By: george.karpenkov

Subscribers: xazax.hun, szepet, a.sidorin, Szelethus

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

Modified:

cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTSolver.h
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h?rev=343581&r1=343580&r2=343581&view=diff
==
--- 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
 (original)
+++ 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
 Tue Oct  2 05:55:48 2018
@@ -134,9 +134,9 @@ public:
   // A value has been obtained, check if it is the only value
   SMTExprRef NotExp = SMTConv::fromBinOp(
   Solver, Exp, BO_NE,
-  Ty->isBooleanType() ? Solver->fromBoolean(Value.getBoolValue())
-  : Solver->fromAPSInt(Value),
-  false);
+  Ty->isBooleanType() ? Solver->mkBoolean(Value.getBoolValue())
+  : Solver->mkBitvector(Value, 
Value.getBitWidth()),
+  /*isSigned=*/false);
 
   Solver->addConstraint(NotExp);
 

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h?rev=343581&r1=343580&r2=343581&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h Tue Oct 
 2 05:55:48 2018
@@ -246,7 +246,7 @@ public:
   // Logical operators
 case BO_LAnd:
 case BO_LOr:
-  return fromBinOp(Solver, LHS, Op, RHS, false);
+  return fromBinOp(Solver, LHS, Op, RHS, /*isSigned=*/false);
 
 default:;
 }
@@ -294,14 +294,14 @@ public:
 if (FromTy->isIntegralOrEnumerationType() && ToTy->isRealFloatingType()) {
   SMTSortRef Sort = Solver->getFloatSort(ToBitWidth);
   return FromTy->isSignedIntegerOrEnumerationType()
- ? Solver->mkFPtoSBV(Exp, Sort)
- : Solver->mkFPtoUBV(Exp, Sort);
+ ? Solver->mkSBVtoFP(Exp, Sort)
+ : Solver->mkUBVtoFP(Exp, Sort);
 }
 
 if (FromTy->isRealFloatingType() && ToTy->isIntegralOrEnumerationType())
   return ToTy->isSignedIntegerOrEnumerationType()
- ? Solver->mkSBVtoFP(Exp, ToBitWidth)
- : Solver->mkUBVtoFP(Exp, ToBitWidth);
+ ? Solver->mkFPtoSBV(Exp, ToBitWidth)
+ : Solver->mkFPtoUBV(Exp, ToBitWidth);
 
 llvm_unreachable("Unsupported explicit type cast!");
   }
@@ -379,14 +379,14 @@ public:
   getSymExpr(Solver, Ctx, SIE->getLHS(), getRHS());
-  SMTExprRef RHS = Solver->fromAPSInt(NewRInt);
+  SMTExprRef RHS = Solver->mkBitvector(NewRInt, NewRInt.getBitWidth());
   return getBinExpr(Solver, Ctx, LHS, LTy, Op, RHS, RTy, RetTy);
 }
 
 if (const IntSymExpr *ISE = dyn_cast(BSE)) {
   llvm::APSInt NewLInt;
   std::tie(NewLInt, LTy) = fixAPSInt(Ctx, ISE->getLHS());
-  SMTExprRef LHS = Solver->fromAPSInt(NewLInt);
+  SMTExprRef LHS = Solver->mkBitvector(NewLInt, NewLInt.getBitWidth());
   SMTExprRef RHS =
   getSymExpr(Solver, Ctx, ISE->getRHS(), &RTy, hasComparison);
   return getBinExpr(Solver, Ctx, LHS, LTy, Op, RHS, RTy, RetTy);
@@ -466,7 +466,7 @@ public

r343582 - Revert r326937 "[OpenCL] Remove block invoke function from emitted block literal struct"

2018-10-02 Thread Sven van Haastregt via cfe-commits
Author: svenvh
Date: Tue Oct  2 06:02:24 2018
New Revision: 343582

URL: http://llvm.org/viewvc/llvm-project?rev=343582&view=rev
Log:
Revert r326937 "[OpenCL] Remove block invoke function from emitted block 
literal struct"

This reverts r326937 as it broke block argument handling in OpenCL.
See the discussion on https://reviews.llvm.org/D43783 .

The next commit will add a test case that revealed the issue.

Modified:
cfe/trunk/lib/CodeGen/CGBlocks.cpp
cfe/trunk/lib/CodeGen/CGOpenCLRuntime.cpp
cfe/trunk/lib/CodeGen/CGOpenCLRuntime.h
cfe/trunk/test/CodeGenOpenCL/amdgpu-enqueue-kernel.cl
cfe/trunk/test/CodeGenOpenCL/blocks.cl
cfe/trunk/test/CodeGenOpenCL/cl20-device-side-enqueue.cl
cfe/trunk/test/SemaOpenCL/block-array-capturing.cl

Modified: cfe/trunk/lib/CodeGen/CGBlocks.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBlocks.cpp?rev=343582&r1=343581&r2=343582&view=diff
==
--- cfe/trunk/lib/CodeGen/CGBlocks.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBlocks.cpp Tue Oct  2 06:02:24 2018
@@ -446,12 +446,25 @@ static void initializeForBlockHeader(Cod
 
   assert(elementTypes.empty());
   if (CGM.getLangOpts().OpenCL) {
-// The header is basically 'struct { int; int;
+// The header is basically 'struct { int; int; generic void *;
 // custom_fields; }'. Assert that struct is packed.
+auto GenericAS =
+CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic);
+auto GenPtrAlign =
+CharUnits::fromQuantity(CGM.getTarget().getPointerAlign(GenericAS) / 
8);
+auto GenPtrSize =
+CharUnits::fromQuantity(CGM.getTarget().getPointerWidth(GenericAS) / 
8);
+assert(CGM.getIntSize() <= GenPtrSize);
+assert(CGM.getIntAlign() <= GenPtrAlign);
+assert((2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign));
 elementTypes.push_back(CGM.IntTy); /* total size */
 elementTypes.push_back(CGM.IntTy); /* align */
-unsigned Offset = 2 * CGM.getIntSize().getQuantity();
-unsigned BlockAlign = CGM.getIntAlign().getQuantity();
+elementTypes.push_back(
+CGM.getOpenCLRuntime()
+.getGenericVoidPointerType()); /* invoke function */
+unsigned Offset =
+2 * CGM.getIntSize().getQuantity() + GenPtrSize.getQuantity();
+unsigned BlockAlign = GenPtrAlign.getQuantity();
 if (auto *Helper =
 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
   for (auto I : Helper->getCustomFieldTypes()) /* custom fields */ {
@@ -906,12 +919,20 @@ llvm::Value *CodeGenFunction::EmitBlockL
 
 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
   bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
+  auto GenVoidPtrTy =
+  IsOpenCL ? CGM.getOpenCLRuntime().getGenericVoidPointerType() : 
VoidPtrTy;
+  LangAS GenVoidPtrAddr = IsOpenCL ? LangAS::opencl_generic : LangAS::Default;
+  auto GenVoidPtrSize = CharUnits::fromQuantity(
+  CGM.getTarget().getPointerWidth(
+  CGM.getContext().getTargetAddressSpace(GenVoidPtrAddr)) /
+  8);
   // Using the computed layout, generate the actual block function.
   bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
   CodeGenFunction BlockCGF{CGM, true};
   BlockCGF.SanOpts = SanOpts;
   auto *InvokeFn = BlockCGF.GenerateBlockFunction(
   CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
+  auto *blockFn = llvm::ConstantExpr::getPointerCast(InvokeFn, GenVoidPtrTy);
 
   // If there is nothing to capture, we can emit this as a global block.
   if (blockInfo.CanBeGlobal)
@@ -987,12 +1008,11 @@ llvm::Value *CodeGenFunction::EmitBlockL
   llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
   getIntSize(), "block.align");
 }
-if (!IsOpenCL) {
-  addHeaderField(llvm::ConstantExpr::getBitCast(InvokeFn, VoidPtrTy),
- getPointerSize(), "block.invoke");
+addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
+if (!IsOpenCL)
   addHeaderField(descriptor, getPointerSize(), "block.descriptor");
-} else if (auto *Helper =
-   CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
+else if (auto *Helper =
+ CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
   for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
 addHeaderField(
 I.first,
@@ -1196,23 +1216,38 @@ llvm::Type *CodeGenModule::getBlockDescr
 }
 
 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
-  assert(!getLangOpts().OpenCL && "OpenCL does not need this");
-
   if (GenericBlockLiteralType)
 return GenericBlockLiteralType;
 
   llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
 
-  // struct __block_literal_generic {
-  //   void *__isa;
-  //   int __flags;
-  //   int __reserved;
-  //   void (*__invoke)(void *);
-  //   struct __block_descriptor *__de

r343583 - [OpenCL] Add block argument CodeGen test

2018-10-02 Thread Sven van Haastregt via cfe-commits
Author: svenvh
Date: Tue Oct  2 06:02:27 2018
New Revision: 343583

URL: http://llvm.org/viewvc/llvm-project?rev=343583&view=rev
Log:
[OpenCL] Add block argument CodeGen test

r326937 ("[OpenCL] Remove block invoke function from emitted block
literal struct", 2018-03-07) broke block argument handling.  In
particular the commit was causing a crash during code generation, see
the discussion in https://reviews.llvm.org/D43783 .

The offending commit has just been reverted; add a test to avoid
breaking this again in the future.

Modified:
cfe/trunk/test/CodeGenOpenCL/blocks.cl

Modified: cfe/trunk/test/CodeGenOpenCL/blocks.cl
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenOpenCL/blocks.cl?rev=343583&r1=343582&r2=343583&view=diff
==
--- cfe/trunk/test/CodeGenOpenCL/blocks.cl (original)
+++ cfe/trunk/test/CodeGenOpenCL/blocks.cl Tue Oct  2 06:02:27 2018
@@ -78,6 +78,26 @@ void foo(){
 
 // COMMON-NOT: define{{.*}}@__foo_block_invoke_kernel
 
+// Test that we support block arguments.
+// COMMON-LABEL: define {{.*}} @blockArgFunc
+int blockArgFunc(int (^ bl)(void)) {
+  return bl();
+}
+
+// COMMON-LABEL: define {{.*}} @get21
+// COMMON: define {{.*}} @__get21_block_invoke
+// COMMON: ret i32 21
+int get21() {
+  return blockArgFunc(^{return 21;});
+}
+
+// COMMON-LABEL: define {{.*}} @get42
+// COMMON: define {{.*}} @__get42_block_invoke
+// COMMON: ret i32 42
+int get42() {
+  return blockArgFunc(^{return 42;});
+}
+
 // CHECK-DEBUG: !DIDerivedType(tag: DW_TAG_member, name: "__size"
 // CHECK-DEBUG: !DIDerivedType(tag: DW_TAG_member, name: "__align"
 


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


[PATCH] D52778: [Preprocessor] Hide include typo correction behind SpellChecking.

2018-10-02 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.

Similar to Sema typo correction, the Preprocessor typo correction should
also be hidden behind the SpellChecking flag.


Repository:
  rC Clang

https://reviews.llvm.org/D52778

Files:
  lib/Lex/PPDirectives.cpp


Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -1888,31 +1888,33 @@
   // Check for likely typos due to leading or trailing non-isAlphanumeric
   // characters
   StringRef OriginalFilename = Filename;
-  if (!File) {
-// A heuristic to correct a typo file name by removing leading and
-// trailing non-isAlphanumeric characters.
-auto CorrectTypoFilename = [](llvm::StringRef Filename) {
-  Filename = Filename.drop_until(isAlphanumeric);
-  while (!Filename.empty() && !isAlphanumeric(Filename.back())) {
-Filename = Filename.drop_back();
+  if (LangOpts.SpellChecking) {
+if (!File) {
+  // A heuristic to correct a typo file name by removing leading and
+  // trailing non-isAlphanumeric characters.
+  auto CorrectTypoFilename = [](llvm::StringRef Filename) {
+Filename = Filename.drop_until(isAlphanumeric);
+while (!Filename.empty() && !isAlphanumeric(Filename.back())) {
+  Filename = Filename.drop_back();
+}
+return Filename;
+  };
+  Filename = CorrectTypoFilename(Filename);
+  File = LookupFile(
+  FilenameLoc,
+  LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, 
isAngled,
+  LookupFrom, LookupFromFile, CurDir,
+  Callbacks ? &SearchPath : nullptr,
+  Callbacks ? &RelativePath : nullptr, &SuggestedModule, 
&IsMapped);
+  if (File) {
+SourceRange Range(FilenameTok.getLocation(), CharEnd);
+auto Hint = isAngled ? FixItHint::CreateReplacement(
+   Range, "<" + Filename.str() + ">")
+ : FixItHint::CreateReplacement(
+   Range, "\"" + Filename.str() + "\"");
+Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
+<< OriginalFilename << Filename << Hint;
   }
-  return Filename;
-};
-Filename = CorrectTypoFilename(Filename);
-File = LookupFile(
-FilenameLoc,
-LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
-LookupFrom, LookupFromFile, CurDir,
-Callbacks ? &SearchPath : nullptr,
-Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped);
-if (File) {
-  SourceRange Range(FilenameTok.getLocation(), CharEnd);
-  auto Hint = isAngled ? FixItHint::CreateReplacement(
- Range, "<" + Filename.str() + ">")
-   : FixItHint::CreateReplacement(
- Range, "\"" + Filename.str() + "\"");
-  Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
-  << OriginalFilename << Filename << Hint;
 }
   }
 


Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -1888,31 +1888,33 @@
   // Check for likely typos due to leading or trailing non-isAlphanumeric
   // characters
   StringRef OriginalFilename = Filename;
-  if (!File) {
-// A heuristic to correct a typo file name by removing leading and
-// trailing non-isAlphanumeric characters.
-auto CorrectTypoFilename = [](llvm::StringRef Filename) {
-  Filename = Filename.drop_until(isAlphanumeric);
-  while (!Filename.empty() && !isAlphanumeric(Filename.back())) {
-Filename = Filename.drop_back();
+  if (LangOpts.SpellChecking) {
+if (!File) {
+  // A heuristic to correct a typo file name by removing leading and
+  // trailing non-isAlphanumeric characters.
+  auto CorrectTypoFilename = [](llvm::StringRef Filename) {
+Filename = Filename.drop_until(isAlphanumeric);
+while (!Filename.empty() && !isAlphanumeric(Filename.back())) {
+  Filename = Filename.drop_back();
+}
+return Filename;
+  };
+  Filename = CorrectTypoFilename(Filename);
+  File = LookupFile(
+  FilenameLoc,
+  LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
+  LookupFrom, LookupFromFile, CurDir,
+  Callbacks ? &SearchPath : nullptr,
+  Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped);
+  if (File) {
+SourceRange Range(FilenameTok.g

[PATCH] D43783: [OpenCL] Remove block invoke function from emitted block literal struct

2018-10-02 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh added a comment.

Reverted in r343582, test added in r343583.


Repository:
  rC Clang

https://reviews.llvm.org/D43783



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


[PATCH] D52691: [clang-tidy] NFC use CHECK-NOTES in tests for performance-move-constructor-init

2018-10-02 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 167933.
JonasToth added a comment.

  -note remove spurious reordering


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52691

Files:
  test/clang-tidy/check_clang_tidy.py
  test/clang-tidy/performance-move-constructor-init.cpp


Index: test/clang-tidy/performance-move-constructor-init.cpp
===
--- test/clang-tidy/performance-move-constructor-init.cpp
+++ test/clang-tidy/performance-move-constructor-init.cpp
@@ -30,9 +30,9 @@
 struct D : B {
   D() : B() {}
   D(const D &RHS) : B(RHS) {}
-  // CHECK-MESSAGES: :[[@LINE+3]]:16: warning: move constructor initializes 
base class by calling a copy constructor [performance-move-constructor-init]
-  // CHECK-MESSAGES: 26:3: note: copy constructor being called
-  // CHECK-MESSAGES: 27:3: note: candidate move constructor here
+  // CHECK-NOTES: :[[@LINE+3]]:16: warning: move constructor initializes base 
class by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
   D(D &&RHS) : B(RHS) {}
 };
 
@@ -75,8 +75,10 @@
 
 struct M {
   B Mem;
-  // CHECK-MESSAGES: :[[@LINE+1]]:16: warning: move constructor initializes 
class member by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: :[[@LINE+1]]:16: warning: move constructor initializes class 
member by calling a copy constructor [performance-move-constructor-init]
   M(M &&RHS) : Mem(RHS.Mem) {}
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
 };
 
 struct N {
@@ -109,7 +111,7 @@
 
 struct Positive {
   Positive(Movable M) : M_(M) {}
-  // CHECK-MESSAGES: [[@LINE-1]]:12: warning: pass by value and use std::move 
[modernize-pass-by-value]
+  // CHECK-NOTES: [[@LINE-1]]:12: warning: pass by value and use std::move 
[modernize-pass-by-value]
   // CHECK-FIXES: Positive(Movable M) : M_(std::move(M)) {}
   Movable M_;
 };
Index: test/clang-tidy/check_clang_tidy.py
===
--- test/clang-tidy/check_clang_tidy.py
+++ test/clang-tidy/check_clang_tidy.py
@@ -164,12 +164,14 @@
 
   if has_check_notes:
 notes_file = temp_file_name + '.notes'
-write_file(notes_file, clang_tidy_output)
+filtered_output = [line for line in clang_tidy_output.splitlines()
+   if not "note: FIX-IT applied suggested changes" in line]
+write_file(notes_file, '\n'.join(filtered_output))
 try:
   subprocess.check_output(
   ['FileCheck', '-input-file=' + notes_file, input_file_name,
'-check-prefix=' + check_notes_prefix,
-   '-implicit-check-not={{note|warning|error}}:'],
+   '-implicit-check-not=note|warning|error}}:'],
   stderr=subprocess.STDOUT)
 except subprocess.CalledProcessError as e:
   print('FileCheck failed:\n' + e.output.decode())


Index: test/clang-tidy/performance-move-constructor-init.cpp
===
--- test/clang-tidy/performance-move-constructor-init.cpp
+++ test/clang-tidy/performance-move-constructor-init.cpp
@@ -30,9 +30,9 @@
 struct D : B {
   D() : B() {}
   D(const D &RHS) : B(RHS) {}
-  // CHECK-MESSAGES: :[[@LINE+3]]:16: warning: move constructor initializes base class by calling a copy constructor [performance-move-constructor-init]
-  // CHECK-MESSAGES: 26:3: note: copy constructor being called
-  // CHECK-MESSAGES: 27:3: note: candidate move constructor here
+  // CHECK-NOTES: :[[@LINE+3]]:16: warning: move constructor initializes base class by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
   D(D &&RHS) : B(RHS) {}
 };
 
@@ -75,8 +75,10 @@
 
 struct M {
   B Mem;
-  // CHECK-MESSAGES: :[[@LINE+1]]:16: warning: move constructor initializes class member by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: :[[@LINE+1]]:16: warning: move constructor initializes class member by calling a copy constructor [performance-move-constructor-init]
   M(M &&RHS) : Mem(RHS.Mem) {}
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
 };
 
 struct N {
@@ -109,7 +111,7 @@
 
 struct Positive {
   Positive(Movable M) : M_(M) {}
-  // CHECK-MESSAGES: [[@LINE-1]]:12: warning: pass by value and use std::move [modernize-pass-by-value]
+  // CHECK-NOTES: [[@LINE-1]]:12: warning: pass by value and use std::move [modernize-pass-by-value]
   // CHECK-FIXES: Positive(Movable M) : M_(std::move(M)) {}
   Movable M_;
 };
Index: test/clang-tidy/check_clang_tidy.py
===
--- test/clang-tid

[PATCH] D52691: [clang-tidy] NFC use CHECK-NOTES in tests for performance-move-constructor-init

2018-10-02 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 167932.
JonasToth added a comment.

- filter with builtin python before passing to FileCheck


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52691

Files:
  test/clang-tidy/check_clang_tidy.py
  test/clang-tidy/performance-move-constructor-init.cpp


Index: test/clang-tidy/performance-move-constructor-init.cpp
===
--- test/clang-tidy/performance-move-constructor-init.cpp
+++ test/clang-tidy/performance-move-constructor-init.cpp
@@ -30,9 +30,9 @@
 struct D : B {
   D() : B() {}
   D(const D &RHS) : B(RHS) {}
-  // CHECK-MESSAGES: :[[@LINE+3]]:16: warning: move constructor initializes 
base class by calling a copy constructor [performance-move-constructor-init]
-  // CHECK-MESSAGES: 26:3: note: copy constructor being called
-  // CHECK-MESSAGES: 27:3: note: candidate move constructor here
+  // CHECK-NOTES: :[[@LINE+3]]:16: warning: move constructor initializes base 
class by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
   D(D &&RHS) : B(RHS) {}
 };
 
@@ -75,8 +75,10 @@
 
 struct M {
   B Mem;
-  // CHECK-MESSAGES: :[[@LINE+1]]:16: warning: move constructor initializes 
class member by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: :[[@LINE+1]]:16: warning: move constructor initializes class 
member by calling a copy constructor [performance-move-constructor-init]
   M(M &&RHS) : Mem(RHS.Mem) {}
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
 };
 
 struct N {
@@ -109,7 +111,7 @@
 
 struct Positive {
   Positive(Movable M) : M_(M) {}
-  // CHECK-MESSAGES: [[@LINE-1]]:12: warning: pass by value and use std::move 
[modernize-pass-by-value]
+  // CHECK-NOTES: [[@LINE-1]]:12: warning: pass by value and use std::move 
[modernize-pass-by-value]
   // CHECK-FIXES: Positive(Movable M) : M_(std::move(M)) {}
   Movable M_;
 };
Index: test/clang-tidy/check_clang_tidy.py
===
--- test/clang-tidy/check_clang_tidy.py
+++ test/clang-tidy/check_clang_tidy.py
@@ -164,12 +164,14 @@
 
   if has_check_notes:
 notes_file = temp_file_name + '.notes'
-write_file(notes_file, clang_tidy_output)
+filtered_output = [line for line in clang_tidy_output.splitlines()
+   if not "note: FIX-IT applied suggested changes" in line]
+write_file(notes_file, '\n'.join(filtered_output))
 try:
   subprocess.check_output(
   ['FileCheck', '-input-file=' + notes_file, input_file_name,
'-check-prefix=' + check_notes_prefix,
-   '-implicit-check-not={{note|warning|error}}:'],
+   '-implicit-check-not=warning|error|note}}:'],
   stderr=subprocess.STDOUT)
 except subprocess.CalledProcessError as e:
   print('FileCheck failed:\n' + e.output.decode())


Index: test/clang-tidy/performance-move-constructor-init.cpp
===
--- test/clang-tidy/performance-move-constructor-init.cpp
+++ test/clang-tidy/performance-move-constructor-init.cpp
@@ -30,9 +30,9 @@
 struct D : B {
   D() : B() {}
   D(const D &RHS) : B(RHS) {}
-  // CHECK-MESSAGES: :[[@LINE+3]]:16: warning: move constructor initializes base class by calling a copy constructor [performance-move-constructor-init]
-  // CHECK-MESSAGES: 26:3: note: copy constructor being called
-  // CHECK-MESSAGES: 27:3: note: candidate move constructor here
+  // CHECK-NOTES: :[[@LINE+3]]:16: warning: move constructor initializes base class by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
   D(D &&RHS) : B(RHS) {}
 };
 
@@ -75,8 +75,10 @@
 
 struct M {
   B Mem;
-  // CHECK-MESSAGES: :[[@LINE+1]]:16: warning: move constructor initializes class member by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: :[[@LINE+1]]:16: warning: move constructor initializes class member by calling a copy constructor [performance-move-constructor-init]
   M(M &&RHS) : Mem(RHS.Mem) {}
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
 };
 
 struct N {
@@ -109,7 +111,7 @@
 
 struct Positive {
   Positive(Movable M) : M_(M) {}
-  // CHECK-MESSAGES: [[@LINE-1]]:12: warning: pass by value and use std::move [modernize-pass-by-value]
+  // CHECK-NOTES: [[@LINE-1]]:12: warning: pass by value and use std::move [modernize-pass-by-value]
   // CHECK-FIXES: Positive(Movable M) : M_(std::move(M)) {}
   Movable M_;
 };
Index: test/clang-tidy/check_clang_tidy.py

[PATCH] D52691: [clang-tidy] NFC use CHECK-NOTES in tests for performance-move-constructor-init

2018-10-02 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added inline comments.



Comment at: test/clang-tidy/check_clang_tidy.py:172
'-check-prefix=' + check_notes_prefix,
-   '-implicit-check-not={{note|warning|error}}:'],
+   '-implicit-check-not=warning|error}}:|note: (?!FIX-IT)}}'],
   stderr=subprocess.STDOUT)

lebedev.ri wrote:
> SGTM, if it works.
Unfortunatly didnt work with LLVM regex, doing in python now


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52691



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


[PATCH] D52691: [clang-tidy] NFC use CHECK-NOTES in tests for performance-move-constructor-init

2018-10-02 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 167934.
JonasToth marked 2 inline comments as done.
JonasToth added a comment.

- finally remove spurious change


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52691

Files:
  test/clang-tidy/check_clang_tidy.py
  test/clang-tidy/performance-move-constructor-init.cpp


Index: test/clang-tidy/performance-move-constructor-init.cpp
===
--- test/clang-tidy/performance-move-constructor-init.cpp
+++ test/clang-tidy/performance-move-constructor-init.cpp
@@ -30,9 +30,9 @@
 struct D : B {
   D() : B() {}
   D(const D &RHS) : B(RHS) {}
-  // CHECK-MESSAGES: :[[@LINE+3]]:16: warning: move constructor initializes 
base class by calling a copy constructor [performance-move-constructor-init]
-  // CHECK-MESSAGES: 26:3: note: copy constructor being called
-  // CHECK-MESSAGES: 27:3: note: candidate move constructor here
+  // CHECK-NOTES: :[[@LINE+3]]:16: warning: move constructor initializes base 
class by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
   D(D &&RHS) : B(RHS) {}
 };
 
@@ -75,8 +75,10 @@
 
 struct M {
   B Mem;
-  // CHECK-MESSAGES: :[[@LINE+1]]:16: warning: move constructor initializes 
class member by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: :[[@LINE+1]]:16: warning: move constructor initializes class 
member by calling a copy constructor [performance-move-constructor-init]
   M(M &&RHS) : Mem(RHS.Mem) {}
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
 };
 
 struct N {
@@ -109,7 +111,7 @@
 
 struct Positive {
   Positive(Movable M) : M_(M) {}
-  // CHECK-MESSAGES: [[@LINE-1]]:12: warning: pass by value and use std::move 
[modernize-pass-by-value]
+  // CHECK-NOTES: [[@LINE-1]]:12: warning: pass by value and use std::move 
[modernize-pass-by-value]
   // CHECK-FIXES: Positive(Movable M) : M_(std::move(M)) {}
   Movable M_;
 };
Index: test/clang-tidy/check_clang_tidy.py
===
--- test/clang-tidy/check_clang_tidy.py
+++ test/clang-tidy/check_clang_tidy.py
@@ -164,7 +164,9 @@
 
   if has_check_notes:
 notes_file = temp_file_name + '.notes'
-write_file(notes_file, clang_tidy_output)
+filtered_output = [line for line in clang_tidy_output.splitlines()
+   if not "note: FIX-IT applied suggested changes" in line]
+write_file(notes_file, '\n'.join(filtered_output))
 try:
   subprocess.check_output(
   ['FileCheck', '-input-file=' + notes_file, input_file_name,


Index: test/clang-tidy/performance-move-constructor-init.cpp
===
--- test/clang-tidy/performance-move-constructor-init.cpp
+++ test/clang-tidy/performance-move-constructor-init.cpp
@@ -30,9 +30,9 @@
 struct D : B {
   D() : B() {}
   D(const D &RHS) : B(RHS) {}
-  // CHECK-MESSAGES: :[[@LINE+3]]:16: warning: move constructor initializes base class by calling a copy constructor [performance-move-constructor-init]
-  // CHECK-MESSAGES: 26:3: note: copy constructor being called
-  // CHECK-MESSAGES: 27:3: note: candidate move constructor here
+  // CHECK-NOTES: :[[@LINE+3]]:16: warning: move constructor initializes base class by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
   D(D &&RHS) : B(RHS) {}
 };
 
@@ -75,8 +75,10 @@
 
 struct M {
   B Mem;
-  // CHECK-MESSAGES: :[[@LINE+1]]:16: warning: move constructor initializes class member by calling a copy constructor [performance-move-constructor-init]
+  // CHECK-NOTES: :[[@LINE+1]]:16: warning: move constructor initializes class member by calling a copy constructor [performance-move-constructor-init]
   M(M &&RHS) : Mem(RHS.Mem) {}
+  // CHECK-NOTES: 26:3: note: copy constructor being called
+  // CHECK-NOTES: 27:3: note: candidate move constructor here
 };
 
 struct N {
@@ -109,7 +111,7 @@
 
 struct Positive {
   Positive(Movable M) : M_(M) {}
-  // CHECK-MESSAGES: [[@LINE-1]]:12: warning: pass by value and use std::move [modernize-pass-by-value]
+  // CHECK-NOTES: [[@LINE-1]]:12: warning: pass by value and use std::move [modernize-pass-by-value]
   // CHECK-FIXES: Positive(Movable M) : M_(std::move(M)) {}
   Movable M_;
 };
Index: test/clang-tidy/check_clang_tidy.py
===
--- test/clang-tidy/check_clang_tidy.py
+++ test/clang-tidy/check_clang_tidy.py
@@ -164,7 +164,9 @@
 
   if has_check_notes:
 notes_file = temp_file_name + '.notes'
-write_file(notes_file, clang_tidy_output)
+filtered_output = [line for line in clang_tidy_output.splitlines()
+   

[PATCH] D52773: clang-cl: Add /showFilenames option (PR31957)

2018-10-02 Thread Hans Wennborg via Phabricator via cfe-commits
hans added inline comments.



Comment at: lib/Frontend/CompilerInvocation.cpp:792
   Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
+  if (Args.hasArg(OPT_echo_main_file_name))
+llvm::outs() << Opts.MainFileName << "\n";

zturner wrote:
> steveire wrote:
> > I'll have to keep a patch around anyway for myself locally to remove this 
> > condition. But maybe someone else will benefit from this.
> > 
> > What do you think about changing CMake to so that this is passed by default 
> > when using Clang-CL?
> > 
> Do you mean llvms cmake?  Or cmake itself?  Which generator are you using?
Can't you just configure your build to pass the flag to clang-cl?

I suppose CMake could be made to do that by default when using clang-cl 
versions that support the flag and using the MSBuild generator, but that's for 
the CMake community to decide I think. Or perhaps our VS integration could do 
that, but it gets tricky because it needs to know whether the flag is supported 
or not.


https://reviews.llvm.org/D52773



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


[PATCH] D52774: [Preprocessor] Fix an assertion failure trigged in clangd #include completion.

2018-10-02 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 167935.
hokein added a comment.

Rescope the patch.


Repository:
  rC Clang

https://reviews.llvm.org/D52774

Files:
  lib/Lex/PPDirectives.cpp


Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -1898,21 +1898,24 @@
   }
   return Filename;
 };
-Filename = CorrectTypoFilename(Filename);
+StringRef TypoCorrectionName = CorrectTypoFilename(Filename);
 File = LookupFile(
 FilenameLoc,
-LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
+LangOpts.MSVCCompat ? NormalizedPath.c_str() : TypoCorrectionName, 
isAngled,
 LookupFrom, LookupFromFile, CurDir,
 Callbacks ? &SearchPath : nullptr,
 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped);
 if (File) {
   SourceRange Range(FilenameTok.getLocation(), CharEnd);
   auto Hint = isAngled ? FixItHint::CreateReplacement(
- Range, "<" + Filename.str() + ">")
+ Range, "<" + TypoCorrectionName.str() + 
">")
: FixItHint::CreateReplacement(
- Range, "\"" + Filename.str() + "\"");
+ Range, "\"" + TypoCorrectionName.str() + 
"\"");
   Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
-  << OriginalFilename << Filename << Hint;
+  << OriginalFilename << TypoCorrectionName << Hint;
+  // We found the file, so set the Filename to the name after typo
+  // correction.
+  Filename = TypoCorrectionName;
 }
   }
 


Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -1898,21 +1898,24 @@
   }
   return Filename;
 };
-Filename = CorrectTypoFilename(Filename);
+StringRef TypoCorrectionName = CorrectTypoFilename(Filename);
 File = LookupFile(
 FilenameLoc,
-LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
+LangOpts.MSVCCompat ? NormalizedPath.c_str() : TypoCorrectionName, isAngled,
 LookupFrom, LookupFromFile, CurDir,
 Callbacks ? &SearchPath : nullptr,
 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped);
 if (File) {
   SourceRange Range(FilenameTok.getLocation(), CharEnd);
   auto Hint = isAngled ? FixItHint::CreateReplacement(
- Range, "<" + Filename.str() + ">")
+ Range, "<" + TypoCorrectionName.str() + ">")
: FixItHint::CreateReplacement(
- Range, "\"" + Filename.str() + "\"");
+ Range, "\"" + TypoCorrectionName.str() + "\"");
   Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
-  << OriginalFilename << Filename << Hint;
+  << OriginalFilename << TypoCorrectionName << Hint;
+  // We found the file, so set the Filename to the name after typo
+  // correction.
+  Filename = TypoCorrectionName;
 }
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52774: [PProcesssor] Filename should fall back to the written name when typo correction fails.

2018-10-02 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

In https://reviews.llvm.org/D52774#1252294, @kristina wrote:

> Could you add a regression test please? Also could you run this through a 
> debugger and get a backtrace from a debugger instead of the crash report, it 
> seems to be missing a few things likely from optimizations which a debugger 
> will usually pick up. This seems to be asserting due to a duplicate element 
> in a set.
>
> Thank you.


Thanks for the comment. The assertion is caused by inserting an empty 
`Filename` to `StringSet`. The typo correction code change the Filename (which 
will be used afterwards) even the typo correction heuristic fails (e.g. for 
`#include "./^"`, Filename is changed to empty, which is unexpected). The 
testcase is added at https://reviews.llvm.org/D52775. Unfortunately, I couldn't 
reproduce it with a simple clang CodeCompletion test.

As discussed offline with @sammccall, it would be better to let the author of 
typo correction to fix its issues (as the typo correction code is submitted 
recently, and maybe buggy).  The original patch fixes two issues, I rescoped 
the patch to make it clearer for review.


Repository:
  rC Clang

https://reviews.llvm.org/D52774



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


[PATCH] D52773: clang-cl: Add /showFilenames option (PR31957)

2018-10-02 Thread Stephen Kelly via Phabricator via cfe-commits
steveire added inline comments.



Comment at: lib/Frontend/CompilerInvocation.cpp:792
   Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
+  if (Args.hasArg(OPT_echo_main_file_name))
+llvm::outs() << Opts.MainFileName << "\n";

hans wrote:
> zturner wrote:
> > steveire wrote:
> > > I'll have to keep a patch around anyway for myself locally to remove this 
> > > condition. But maybe someone else will benefit from this.
> > > 
> > > What do you think about changing CMake to so that this is passed by 
> > > default when using Clang-CL?
> > > 
> > Do you mean llvms cmake?  Or cmake itself?  Which generator are you using?
> Can't you just configure your build to pass the flag to clang-cl?
> 
> I suppose CMake could be made to do that by default when using clang-cl 
> versions that support the flag and using the MSBuild generator, but that's 
> for the CMake community to decide I think. Or perhaps our VS integration 
> could do that, but it gets tricky because it needs to know whether the flag 
> is supported or not.
I mean upstream cmake. My suggestion is independent of the generator, but it 
would depend on what Brad decides anyway. I don't intend to implement it, just 
report it.

I only have one clang but I have multiple buildsystems, and I don't want to 
have to add a new flag too all of them. In each toplevel CMakeLists everyone 
will need this to make use of the flag:

```

# Have to remember to use "${CMAKE_CXX_SIMULATE_ID}" instead of 
# Undecorated "CMAKE_CXX_SIMULATE_ID" because there is a 
# variable named "MSVC" and
# the way CMake variables and the "if()" command work requires this. 
if (CMAKE_CXX_COMPILER_ID STREQUAL Clang 
AND ${CMAKE_CXX_SIMULATE_ID} STREQUAL MSVC)
# CMake does not have explicit Clang-CL support yet.
# It should have a COMPILER_ID for it.
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /showFilename")
# etc
endif()
```

Upstream CMake can have the logic to add the flag instead.


https://reviews.llvm.org/D52773



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


[PATCH] D52742: [analyzer][WIP] Add macro expansions to the plist output

2018-10-02 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy added a comment.

Does this checker handle the expansion of variadic macros introduced in C++11 
(see syntax (3) and (4) here 
) and the `#` and `##` 
preprocessor operators?




Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:755
+if (It->is(tok::l_paren)) {
+  while ((++It)->isNot(tok::r_paren)) {
+assert(It->isNot(tok::eof) &&

I fear that this does not handle nested parentheses correctly; e.g. in a case 
like `MACRO_ONE(foo, MACRO_TWO(bar, baz), spam)`, it does not skip `, spam)`.


https://reviews.llvm.org/D52742



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


[PATCH] D52773: clang-cl: Add /showFilenames option (PR31957)

2018-10-02 Thread Nico Weber via Phabricator via cfe-commits
thakis accepted this revision.
thakis added a comment.
This revision is now accepted and ready to land.

Looks good. If this is passed and we invoke lld-link, should we give that a 
similar flag and pass that to lld-link as well? I think link.exe also prints 
its outputs.




Comment at: include/clang/Driver/CLCompatOptions.td:163
+  HelpText<"Print the name of each compiled file">,
+  Alias;
 def _SLASH_source_charset : CLCompileJoined<"source-charset:">,

Can you add /showFilenames- (a no-op) too, for symmetry?


https://reviews.llvm.org/D52773



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


[PATCH] D52778: [Preprocessor] Hide include typo correction behind SpellChecking.

2018-10-02 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: lib/Lex/PPDirectives.cpp:1891
   StringRef OriginalFilename = Filename;
-  if (!File) {
-// A heuristic to correct a typo file name by removing leading and
-// trailing non-isAlphanumeric characters.
-auto CorrectTypoFilename = [](llvm::StringRef Filename) {
-  Filename = Filename.drop_until(isAlphanumeric);
-  while (!Filename.empty() && !isAlphanumeric(Filename.back())) {
-Filename = Filename.drop_back();
+  if (LangOpts.SpellChecking) {
+if (!File) {

(just merge with existing if statement?)


Repository:
  rC Clang

https://reviews.llvm.org/D52778



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


[PATCH] D52746: [clang-query] Add single-letter 'q' alias for 'quit'

2018-10-02 Thread Stephen Kelly via Phabricator via cfe-commits
steveire added a comment.

@Szelethus You can approve it and then you will get the feature :).


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52746



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


[clang-tools-extra] r343589 - [clangd] Dex: add Corpus factory for iterators, rename, fold constant. NFC

2018-10-02 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Tue Oct  2 06:44:26 2018
New Revision: 343589

URL: http://llvm.org/viewvc/llvm-project?rev=343589&view=rev
Log:
[clangd] Dex: add Corpus factory for iterators, rename, fold constant. NFC

Summary:
- Corpus avoids having to pass size to the true iterator, and (soon) any
  iterator that might optimize down to true.
- Shorten names of factory functions now they're scoped to the Corpus.
  intersect() and unionOf() rather than createAnd() or createOr() as this
  seems to read better to me, and fits with other short names. Opinion wanted!
- DEFAULT_BOOST_SCORE --> 1. This is a multiplier, don't obfuscate identity.
- Simplify variadic templates in Iterator.h

Reviewers: ioeric

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

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

Modified:
clang-tools-extra/trunk/clangd/index/dex/Dex.cpp
clang-tools-extra/trunk/clangd/index/dex/Dex.h
clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp
clang-tools-extra/trunk/clangd/index/dex/Iterator.h
clang-tools-extra/trunk/clangd/index/dex/PostingList.cpp
clang-tools-extra/trunk/unittests/clangd/DexTests.cpp

Modified: clang-tools-extra/trunk/clangd/index/dex/Dex.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/dex/Dex.cpp?rev=343589&r1=343588&r2=343589&view=diff
==
--- clang-tools-extra/trunk/clangd/index/dex/Dex.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/dex/Dex.cpp Tue Oct  2 06:44:26 2018
@@ -56,7 +56,8 @@ std::vector generateSearchTokens(
 std::vector> createFileProximityIterators(
 llvm::ArrayRef ProximityPaths,
 llvm::ArrayRef URISchemes,
-const llvm::DenseMap &InvertedIndex) {
+const llvm::DenseMap &InvertedIndex,
+const Corpus &Corpus) {
   std::vector> BoostingIterators;
   // Deduplicate parent URIs extracted from the ProximityPaths.
   llvm::StringSet<> ParentURIs;
@@ -91,8 +92,8 @@ std::vector> c
 if (It != InvertedIndex.end()) {
   // FIXME(kbobyrev): Append LIMIT on top of every BOOST iterator.
   PathProximitySignals.SymbolURI = ParentURI;
-  BoostingIterators.push_back(createBoost(It->second.iterator(&It->first),
-  
PathProximitySignals.evaluate()));
+  BoostingIterators.push_back(Corpus.boost(
+  It->second.iterator(&It->first), PathProximitySignals.evaluate()));
 }
   }
   return BoostingIterators;
@@ -101,6 +102,7 @@ std::vector> c
 } // namespace
 
 void Dex::buildIndex() {
+  this->Corpus = dex::Corpus(Symbols.size());
   std::vector> ScoredSymbols(Symbols.size());
 
   for (size_t I = 0; I < Symbols.size(); ++I) {
@@ -159,7 +161,7 @@ bool Dex::fuzzyFind(const FuzzyFindReque
   TrigramIterators.push_back(It->second.iterator(&It->first));
   }
   if (!TrigramIterators.empty())
-TopLevelChildren.push_back(createAnd(move(TrigramIterators)));
+TopLevelChildren.push_back(Corpus.intersect(move(TrigramIterators)));
 
   // Generate scope tokens for search query.
   std::vector> ScopeIterators;
@@ -170,22 +172,22 @@ bool Dex::fuzzyFind(const FuzzyFindReque
   ScopeIterators.push_back(It->second.iterator(&It->first));
   }
   if (Req.AnyScope)
-ScopeIterators.push_back(createBoost(createTrue(Symbols.size()),
- ScopeIterators.empty() ? 1.0 : 0.2));
+ScopeIterators.push_back(
+Corpus.boost(Corpus.all(), ScopeIterators.empty() ? 1.0 : 0.2));
 
   // Add OR iterator for scopes if there are any Scope Iterators.
   if (!ScopeIterators.empty())
-TopLevelChildren.push_back(createOr(move(ScopeIterators)));
+TopLevelChildren.push_back(Corpus.unionOf(move(ScopeIterators)));
 
   // Add proximity paths boosting.
   auto BoostingIterators = createFileProximityIterators(
-  Req.ProximityPaths, URISchemes, InvertedIndex);
+  Req.ProximityPaths, URISchemes, InvertedIndex, Corpus);
   // Boosting iterators do not actually filter symbols. In order to preserve
   // the validity of resulting query, TRUE iterator should be added along
   // BOOSTs.
   if (!BoostingIterators.empty()) {
-BoostingIterators.push_back(createTrue(Symbols.size()));
-TopLevelChildren.push_back(createOr(move(BoostingIterators)));
+BoostingIterators.push_back(Corpus.all());
+TopLevelChildren.push_back(Corpus.unionOf(move(BoostingIterators)));
   }
 
   if (Req.RestrictForCodeCompletion)
@@ -196,14 +198,14 @@ bool Dex::fuzzyFind(const FuzzyFindReque
   // Use TRUE iterator if both trigrams and scopes from the query are not
   // present in the symbol index.
   auto QueryIterator = TopLevelChildren.empty()
-   ? createTrue(Symbols.size())
-   : createAnd(move(TopLevelChildren));
+   ? Corpus.all()
+   : Corpus.intersect(move(TopLevelChildren));
   // Retrieve more items

[PATCH] D52711: [clangd] Dex: add Corpus factory for iterators, rename, fold constant. NFC

2018-10-02 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
sammccall marked an inline comment as done.
Closed by commit rL343589: [clangd] Dex: add Corpus factory for iterators, 
rename, fold constant. NFC (authored by sammccall, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D52711?vs=167687&id=167938#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D52711

Files:
  clang-tools-extra/trunk/clangd/index/dex/Dex.cpp
  clang-tools-extra/trunk/clangd/index/dex/Dex.h
  clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp
  clang-tools-extra/trunk/clangd/index/dex/Iterator.h
  clang-tools-extra/trunk/clangd/index/dex/PostingList.cpp
  clang-tools-extra/trunk/unittests/clangd/DexTests.cpp

Index: clang-tools-extra/trunk/clangd/index/dex/PostingList.cpp
===
--- clang-tools-extra/trunk/clangd/index/dex/PostingList.cpp
+++ clang-tools-extra/trunk/clangd/index/dex/PostingList.cpp
@@ -63,7 +63,7 @@
   float consume() override {
 assert(!reachedEnd() &&
"Posting List iterator can't consume() at the end.");
-return DEFAULT_BOOST_SCORE;
+return 1;
   }
 
   size_t estimateSize() const override {
Index: clang-tools-extra/trunk/clangd/index/dex/Iterator.h
===
--- clang-tools-extra/trunk/clangd/index/dex/Iterator.h
+++ clang-tools-extra/trunk/clangd/index/dex/Iterator.h
@@ -101,8 +101,6 @@
 return Iterator.dump(OS);
   }
 
-  constexpr static float DEFAULT_BOOST_SCORE = 1;
-
 private:
   virtual llvm::raw_ostream &dump(llvm::raw_ostream &OS) const = 0;
 };
@@ -117,69 +115,74 @@
 /// to acquire preliminary scores of requested items.
 std::vector> consume(Iterator &It);
 
-/// Returns AND Iterator which performs the intersection of the PostingLists of
-/// its children.
-///
-/// consume(): AND Iterator returns the product of Childrens' boosting scores
-/// when not exhausted and DEFAULT_BOOST_SCORE otherwise.
-std::unique_ptr
-createAnd(std::vector> Children);
-
-/// Returns OR Iterator which performs the union of the PostingLists of its
-/// children.
-///
-/// consume(): OR Iterator returns the highest boost value among children
-/// pointing to requested item when not exhausted and DEFAULT_BOOST_SCORE
-/// otherwise.
-std::unique_ptr
-createOr(std::vector> Children);
-
-/// Returns TRUE Iterator which iterates over "virtual" PostingList containing
-/// all items in range [0, Size) in an efficient manner.
-///
-/// TRUE returns DEFAULT_BOOST_SCORE for each processed item.
-std::unique_ptr createTrue(DocID Size);
-
-/// Returns BOOST iterator which multiplies the score of each item by given
-/// factor. Boosting can be used as a computationally inexpensive filtering.
-/// Users can return significantly more items using consumeAndBoost() and then
-/// trim Top K using retrieval score.
-std::unique_ptr createBoost(std::unique_ptr Child,
-  float Factor);
-
-/// Returns LIMIT iterator, which yields up to N elements of its child iterator.
-/// Elements only count towards the limit if they are part of the final result
-/// set. Therefore the following iterator (AND (2) (LIMIT (1 2) 1)) yields (2),
-/// not ().
-std::unique_ptr createLimit(std::unique_ptr Child,
-  size_t Limit);
-
-/// This allows createAnd(create(...), create(...)) syntax.
-template  std::unique_ptr createAnd(Args... args) {
-  std::vector> Children;
-  populateChildren(Children, args...);
-  return createAnd(move(Children));
-}
-
-/// This allows createOr(create(...), create(...)) syntax.
-template  std::unique_ptr createOr(Args... args) {
-  std::vector> Children;
-  populateChildren(Children, args...);
-  return createOr(move(Children));
-}
-
-template 
+namespace detail {
+// Variadic template machinery.
+inline void populateChildren(std::vector> &) {}
+template 
 void populateChildren(std::vector> &Children,
-  HeadT &Head, TailT &... Tail) {
+  std::unique_ptr Head, TailT... Tail) {
   Children.push_back(move(Head));
-  populateChildren(Children, Tail...);
+  populateChildren(Children, move(Tail)...);
 }
+} // namespace detail
 
-template 
-void populateChildren(std::vector> &Children,
-  HeadT &Head) {
-  Children.push_back(move(Head));
-}
+// A corpus is a set of documents, and a factory for iterators over them.
+class Corpus {
+  DocID Size;
+
+public:
+  explicit Corpus(DocID Size) : Size(Size) {}
+
+  /// Returns AND Iterator which performs the intersection of the PostingLists
+  /// of its children.
+  ///
+  /// consume(): AND Iterator returns the product of Childrens' boosting
+  /// scores.
+  std::unique_ptr
+  intersect(std::vector> Children) const;
+
+  /// Returns OR Iterator which performs the union of the PostingLists of its
+  /// children.
+  ///
+  /// consume(): OR Iterat

[PATCH] D52746: [clang-query] Add single-letter 'q' alias for 'quit'

2018-10-02 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Please update `HelpQuery::run()` to print out the new mnemonic (it's the *only* 
form of public documentation we have for clang-query currently).


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52746



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


[clang-tools-extra] r343590 - [clangd] Zap TODONEs

2018-10-02 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Tue Oct  2 06:51:43 2018
New Revision: 343590

URL: http://llvm.org/viewvc/llvm-project?rev=343590&view=rev
Log:
[clangd] Zap TODONEs

Modified:
clang-tools-extra/trunk/clangd/index/dex/Iterator.h

Modified: clang-tools-extra/trunk/clangd/index/dex/Iterator.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/dex/Iterator.h?rev=343590&r1=343589&r2=343590&view=diff
==
--- clang-tools-extra/trunk/clangd/index/dex/Iterator.h (original)
+++ clang-tools-extra/trunk/clangd/index/dex/Iterator.h Tue Oct  2 06:51:43 2018
@@ -53,9 +53,6 @@ using DocID = uint32_t;
 /// (their children) to form a multi-level Query Tree. The interface is 
designed
 /// to be extensible in order to support multiple types of iterators.
 class Iterator {
-  // FIXME(kbobyrev): Implement iterator cost, an estimate of advance() calls
-  // before iterator exhaustion.
-  // FIXME(kbobyrev): Implement Limit iterator.
 public:
   /// Returns true if all valid DocIDs were processed and hence the iterator is
   /// exhausted.


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


[PATCH] D52751: Allow comments with '#' in dynamic AST Matchers

2018-10-02 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: unittests/ASTMatchers/Dynamic/ParserTest.cpp:188-190
+  for (size_t i = 0, e = Sema.Errors.size(); i != e; ++i) {
+EXPECT_EQ("", Sema.Errors[i]);
+  }

Why are empty errors created? I would have expected this to be `EXPECT_EQ(0, 
Sema.Errors.size())`.

(If this formulation is desired, it should use a range-based for loop.)


Repository:
  rC Clang

https://reviews.llvm.org/D52751



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


r343591 - [Preprocessor] Hide include typo correction behind SpellChecking.

2018-10-02 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Tue Oct  2 06:59:49 2018
New Revision: 343591

URL: http://llvm.org/viewvc/llvm-project?rev=343591&view=rev
Log:
[Preprocessor] Hide include typo correction behind SpellChecking.

Summary:
Similar to Sema typo correction, the Preprocessor typo correction should
also be hidden behind the SpellChecking flag.

Reviewers: sammccall

Subscribers: cfe-commits

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

Modified:
cfe/trunk/lib/Lex/PPDirectives.cpp

Modified: cfe/trunk/lib/Lex/PPDirectives.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/PPDirectives.cpp?rev=343591&r1=343590&r2=343591&view=diff
==
--- cfe/trunk/lib/Lex/PPDirectives.cpp (original)
+++ cfe/trunk/lib/Lex/PPDirectives.cpp Tue Oct  2 06:59:49 2018
@@ -1888,7 +1888,7 @@ void Preprocessor::HandleIncludeDirectiv
   // Check for likely typos due to leading or trailing non-isAlphanumeric
   // characters
   StringRef OriginalFilename = Filename;
-  if (!File) {
+  if (LangOpts.SpellChecking && !File) {
 // A heuristic to correct a typo file name by removing leading and
 // trailing non-isAlphanumeric characters.
 auto CorrectTypoFilename = [](llvm::StringRef Filename) {


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


[PATCH] D52778: [Preprocessor] Hide include typo correction behind SpellChecking.

2018-10-02 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 167939.
hokein added a comment.

Fix review comment.


Repository:
  rC Clang

https://reviews.llvm.org/D52778

Files:
  lib/Lex/PPDirectives.cpp


Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -1888,7 +1888,7 @@
   // Check for likely typos due to leading or trailing non-isAlphanumeric
   // characters
   StringRef OriginalFilename = Filename;
-  if (!File) {
+  if (LangOpts.SpellChecking && !File) {
 // A heuristic to correct a typo file name by removing leading and
 // trailing non-isAlphanumeric characters.
 auto CorrectTypoFilename = [](llvm::StringRef Filename) {


Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -1888,7 +1888,7 @@
   // Check for likely typos due to leading or trailing non-isAlphanumeric
   // characters
   StringRef OriginalFilename = Filename;
-  if (!File) {
+  if (LangOpts.SpellChecking && !File) {
 // A heuristic to correct a typo file name by removing leading and
 // trailing non-isAlphanumeric characters.
 auto CorrectTypoFilename = [](llvm::StringRef Filename) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52778: [Preprocessor] Hide include typo correction behind SpellChecking.

2018-10-02 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
hokein marked an inline comment as done.
Closed by commit rC343591: [Preprocessor] Hide include typo correction behind 
SpellChecking. (authored by hokein, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D52778?vs=167939&id=167941#toc

Repository:
  rC Clang

https://reviews.llvm.org/D52778

Files:
  lib/Lex/PPDirectives.cpp


Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -1888,7 +1888,7 @@
   // Check for likely typos due to leading or trailing non-isAlphanumeric
   // characters
   StringRef OriginalFilename = Filename;
-  if (!File) {
+  if (LangOpts.SpellChecking && !File) {
 // A heuristic to correct a typo file name by removing leading and
 // trailing non-isAlphanumeric characters.
 auto CorrectTypoFilename = [](llvm::StringRef Filename) {


Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -1888,7 +1888,7 @@
   // Check for likely typos due to leading or trailing non-isAlphanumeric
   // characters
   StringRef OriginalFilename = Filename;
-  if (!File) {
+  if (LangOpts.SpellChecking && !File) {
 // A heuristic to correct a typo file name by removing leading and
 // trailing non-isAlphanumeric characters.
 auto CorrectTypoFilename = [](llvm::StringRef Filename) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52774: [PProcesssor] Filename should fall back to the written name when typo correction fails.

2018-10-02 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 167942.
hokein retitled this revision from " [PProcesssor] Filename should fall back to 
the written name when typo  correction fails. " to "[PProcesssor] Filename 
should fall back to the written name when typo  correction fails.".
hokein added a comment.

Rebase.


Repository:
  rC Clang

https://reviews.llvm.org/D52774

Files:
  lib/Lex/PPDirectives.cpp


Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -1898,21 +1898,25 @@
   }
   return Filename;
 };
-Filename = CorrectTypoFilename(Filename);
+StringRef TypoCorrectionName = CorrectTypoFilename(Filename);
 File = LookupFile(
 FilenameLoc,
-LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
-LookupFrom, LookupFromFile, CurDir,
+LangOpts.MSVCCompat ? NormalizedPath.c_str() : TypoCorrectionName,
+isAngled, LookupFrom, LookupFromFile, CurDir,
 Callbacks ? &SearchPath : nullptr,
 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped);
 if (File) {
   SourceRange Range(FilenameTok.getLocation(), CharEnd);
-  auto Hint = isAngled ? FixItHint::CreateReplacement(
- Range, "<" + Filename.str() + ">")
-   : FixItHint::CreateReplacement(
- Range, "\"" + Filename.str() + "\"");
+  auto Hint = isAngled
+  ? FixItHint::CreateReplacement(
+Range, "<" + TypoCorrectionName.str() + ">")
+  : FixItHint::CreateReplacement(
+Range, "\"" + TypoCorrectionName.str() + "\"");
   Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
-  << OriginalFilename << Filename << Hint;
+  << OriginalFilename << TypoCorrectionName << Hint;
+  // We found the file, so set the Filename to the name after typo
+  // correction.
+  Filename = TypoCorrectionName;
 }
   }
 


Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -1898,21 +1898,25 @@
   }
   return Filename;
 };
-Filename = CorrectTypoFilename(Filename);
+StringRef TypoCorrectionName = CorrectTypoFilename(Filename);
 File = LookupFile(
 FilenameLoc,
-LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
-LookupFrom, LookupFromFile, CurDir,
+LangOpts.MSVCCompat ? NormalizedPath.c_str() : TypoCorrectionName,
+isAngled, LookupFrom, LookupFromFile, CurDir,
 Callbacks ? &SearchPath : nullptr,
 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped);
 if (File) {
   SourceRange Range(FilenameTok.getLocation(), CharEnd);
-  auto Hint = isAngled ? FixItHint::CreateReplacement(
- Range, "<" + Filename.str() + ">")
-   : FixItHint::CreateReplacement(
- Range, "\"" + Filename.str() + "\"");
+  auto Hint = isAngled
+  ? FixItHint::CreateReplacement(
+Range, "<" + TypoCorrectionName.str() + ">")
+  : FixItHint::CreateReplacement(
+Range, "\"" + TypoCorrectionName.str() + "\"");
   Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
-  << OriginalFilename << Filename << Hint;
+  << OriginalFilename << TypoCorrectionName << Hint;
+  // We found the file, so set the Filename to the name after typo
+  // correction.
+  Filename = TypoCorrectionName;
 }
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52727: [clang-tidy] White List Option for performance-unnecessary-value-param, performance-unnecessary-copy-initialization and performance-for-range-copy

2018-10-02 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware added inline comments.



Comment at: clang-tidy/performance/ForRangeCopyCheck.cpp:50
+  const auto VarType = Var->getType();
+  if (std::find_if(WhiteListTypes.begin(), WhiteListTypes.end(),
+   [&](llvm::StringRef WhiteListType) {

JonasToth wrote:
> lebedev.ri wrote:
> > `llvm::any_of()`
> This configuration should be used in the matchers. Please see 
> `cppcoreguidelines-no-malloc` for an example on how to do it in the matchers. 
> Having it there usually improves performance and is clearer.
`google-runtime-references` has this in the `check()` function. It seems there 
is no common agreement where to put this. `cppcoreguidelines-no-malloc` is not 
a good example since it simple compares strings instead of matching regular 
expressions. I think here we should allow regular expressions. Then we would 
need a new matcher called `matchesAnyName`. Should I create it?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52727



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


[PATCH] D52780: [OPENMP] Add 'reverse_offload' clause to OMP5.0 'requires' directive

2018-10-02 Thread Patrick Lyster via Phabricator via cfe-commits
patricklyster created this revision.
patricklyster added reviewers: ABataev, Hahnfeld, RaviNarayanaswamy, mikerice, 
kkwli0, hfinkel, gtbercea.
patricklyster added projects: clang, OpenMP.
Herald added subscribers: cfe-commits, arphaman, guansong.

Added new `reverse_offload` clause to existing OMP5.0 `requires` directive


Repository:
  rC Clang

https://reviews.llvm.org/D52780

Files:
  clang/include/clang/AST/OpenMPClause.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/Basic/OpenMPKinds.def
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/OpenMPClause.cpp
  clang/lib/AST/StmtPrinter.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/Basic/OpenMPKinds.cpp
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/OpenMP/requires_unified_address_ast_print.cpp
  clang/test/OpenMP/requires_unified_address_messages.cpp
  clang/tools/libclang/CIndex.cpp

Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -2213,6 +2213,9 @@
 void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
 const OMPUnifiedSharedMemoryClause *) {}
 
+void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
+const OMPReverseOffloadClause *) {}
+
 void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
   Visitor->AddStmt(C->getDevice());
 }
Index: clang/test/OpenMP/requires_unified_address_messages.cpp
===
--- clang/test/OpenMP/requires_unified_address_messages.cpp
+++ clang/test/OpenMP/requires_unified_address_messages.cpp
@@ -10,6 +10,10 @@
 
 #pragma omp requires unified_address, unified_address // expected-error {{Only one unified_address clause can appear on a requires directive in a single translation unit}} expected-error {{directive '#pragma omp requires' cannot contain more than one 'unified_address' clause}}
 
+#pragma omp requires reverse_offload // expected-note {{reverse_offload clause previously used here}} expected-note {{reverse_offload clause previously used here}}
+
+#pragma omp requires reverse_offload, reverse_offload // expected-error {{Only one reverse_offload clause can appear on a requires directive in a single translation unit}} expected-error {{directive '#pragma omp requires' cannot contain more than one 'reverse_offload' clause}}
+
 #pragma omp requires // expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
 #pragma omp requires invalid_clause // expected-warning {{extra tokens at the end of '#pragma omp requires' are ignored}} expected-error {{expected at least one clause on '#pragma omp requires' directive}}
@@ -20,7 +24,7 @@
 
 #pragma omp requires invalid_clause unified_address // expected-warning {{extra tokens at the end of '#pragma omp requires' are ignored}} expected-error {{expected at least one clause on '#pragma omp requires' directive}}
 
-#pragma omp requires unified_shared_memory, unified_address // expected-error {{Only one unified_shared_memory clause can appear on a requires directive in a single translation unit}} expected-error{{Only one unified_address clause can appear on a requires directive in a single translation unit}}
+#pragma omp requires unified_shared_memory, unified_address, reverse_offload // expected-error {{Only one unified_shared_memory clause can appear on a requires directive in a single translation unit}} expected-error{{Only one unified_address clause can appear on a requires directive in a single translation unit}} expected-error{{Only one reverse_offload clause can appear on a requires directive in a single translation unit}}
 
 namespace A {
   #pragma omp requires unified_address // expected-error {{Only one unified_address clause can appear on a requires directive in a single translation unit}}
Index: clang/test/OpenMP/requires_unified_address_ast_print.cpp
===
--- clang/test/OpenMP/requires_unified_address_ast_print.cpp
+++ clang/test/OpenMP/requires_unified_address_ast_print.cpp
@@ -16,4 +16,7 @@
 #pragma omp requires unified_shared_memory
 // CHECK:#pragma omp requires unified_shared_memory
 
+#pragma omp requires reverse_offload
+// CHECK:#pragma omp requires reverse_offload
+
 #endif
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -6935,3 +6935,5 @@
 
 void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause(
 OMPUnifiedSharedMemoryClause *) {}
+
+void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
Index: clang/lib/Serialization/ASTReader.cpp
===

[PATCH] D52781: [clangd] Don't make check-clangd as a dependency in check-clang-tools

2018-10-02 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added subscribers: kadircet, arphaman, jkorous, MaskRay, ioeric, 
ilya-biryukov, mgorny.

check-clang-tools will run check-clangd first, and then run the rest
tests. If clangd tests fails, check-clang-tools would be stopped.

This would block other clang-tools developers if clangd is broken.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52781

Files:
  test/CMakeLists.txt


Index: test/CMakeLists.txt
===
--- test/CMakeLists.txt
+++ test/CMakeLists.txt
@@ -52,8 +52,6 @@
   modularize
   pp-trace
 
-  check-clangd
-
   # Unit tests
   ExtraToolsUnitTests
 
@@ -65,6 +63,19 @@
   clang-tidy
   )
 
+set(CLANGD_TEST_DEPS
+  clangd
+  ClangdTests
+  # clangd-related tools which don't have tests, add them to the test to make
+  # sure we don't introduce new changes that break their compilations.
+  clangd-indexer
+  dexp
+  )
+foreach(clangd_dep ${CLANGD_TEST_DEPS})
+  list(APPEND CLANG_TOOLS_TEST_DEPS
+   ${clangd_dep})
+endforeach()
+
 add_lit_testsuite(check-clang-tools "Running the Clang extra tools' regression 
tests"
   ${CMAKE_CURRENT_BINARY_DIR}
   DEPENDS ${CLANG_TOOLS_TEST_DEPS}
@@ -74,15 +85,9 @@
 set_target_properties(check-clang-tools PROPERTIES FOLDER "Clang extra tools' 
tests")
 
 # Setup an individual test for building and testing clangd-only stuff.
-set(CLANGD_TEST_DEPS
-  clangd
-  ClangdTests
-  # clangd-related tools which don't have tests, add them to the test to make
-  # sure we don't introduce new changes that break their compilations.
-  clangd-indexer
-  dexp
-)
-# Exclude check-clangd from check-all, as check-clangd will launch via 
check-clang-tools.
+# Note: all clangd tests have been covered in check-clang-tools, this is a
+# convenient target for clangd developers.
+# Exclude check-clangd from check-all.
 set(EXCLUDE_FROM_ALL ON)
 add_lit_testsuite(check-clangd "Running the Clangd regression tests"
   ${CMAKE_CURRENT_BINARY_DIR}/Unit/clangd;${CMAKE_CURRENT_BINARY_DIR}/clangd


Index: test/CMakeLists.txt
===
--- test/CMakeLists.txt
+++ test/CMakeLists.txt
@@ -52,8 +52,6 @@
   modularize
   pp-trace
 
-  check-clangd
-
   # Unit tests
   ExtraToolsUnitTests
 
@@ -65,6 +63,19 @@
   clang-tidy
   )
 
+set(CLANGD_TEST_DEPS
+  clangd
+  ClangdTests
+  # clangd-related tools which don't have tests, add them to the test to make
+  # sure we don't introduce new changes that break their compilations.
+  clangd-indexer
+  dexp
+  )
+foreach(clangd_dep ${CLANGD_TEST_DEPS})
+  list(APPEND CLANG_TOOLS_TEST_DEPS
+   ${clangd_dep})
+endforeach()
+
 add_lit_testsuite(check-clang-tools "Running the Clang extra tools' regression tests"
   ${CMAKE_CURRENT_BINARY_DIR}
   DEPENDS ${CLANG_TOOLS_TEST_DEPS}
@@ -74,15 +85,9 @@
 set_target_properties(check-clang-tools PROPERTIES FOLDER "Clang extra tools' tests")
 
 # Setup an individual test for building and testing clangd-only stuff.
-set(CLANGD_TEST_DEPS
-  clangd
-  ClangdTests
-  # clangd-related tools which don't have tests, add them to the test to make
-  # sure we don't introduce new changes that break their compilations.
-  clangd-indexer
-  dexp
-)
-# Exclude check-clangd from check-all, as check-clangd will launch via check-clang-tools.
+# Note: all clangd tests have been covered in check-clang-tools, this is a
+# convenient target for clangd developers.
+# Exclude check-clangd from check-all.
 set(EXCLUDE_FROM_ALL ON)
 add_lit_testsuite(check-clangd "Running the Clangd regression tests"
   ${CMAKE_CURRENT_BINARY_DIR}/Unit/clangd;${CMAKE_CURRENT_BINARY_DIR}/clangd
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52780: [OPENMP] Add 'reverse_offload' clause to OMP5.0 'requires' directive

2018-10-02 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

https://reviews.llvm.org/D52780



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


[PATCH] D52782: [clang-tidy] Sequence statements with multiple parents correctly (PR39149)

2018-10-02 Thread Martin Böhme via Phabricator via cfe-commits
mboehme created this revision.
Herald added subscribers: cfe-commits, xazax.hun.

Before this fix, the bugprone-use-after-move check could incorrectly
conclude that a use and move in a function template were not sequenced.
For details, see

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


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52782

Files:
  clang-tidy/bugprone/UseAfterMoveCheck.cpp
  clang-tidy/utils/ExprSequence.cpp
  clang-tidy/utils/ExprSequence.h
  test/clang-tidy/bugprone-use-after-move.cpp


Index: test/clang-tidy/bugprone-use-after-move.cpp
===
--- test/clang-tidy/bugprone-use-after-move.cpp
+++ test/clang-tidy/bugprone-use-after-move.cpp
@@ -1195,6 +1195,18 @@
   }
 }
 
+// Null statements (and some other statements) in templates may be shared
+// between the uninstantiated and instantiated versions of the template and
+// therefore have multiple parents. Make sure the sequencing code handles this
+// correctly.
+template  void nullStatementSequencesInTemplate() {
+  int c = 0;
+  (void)c;
+  ;
+  std::move(c);
+}
+template void nullStatementSequencesInTemplate();
+
 namespace PR33020 {
 class D {
   ~D();
Index: clang-tidy/utils/ExprSequence.h
===
--- clang-tidy/utils/ExprSequence.h
+++ clang-tidy/utils/ExprSequence.h
@@ -69,8 +69,8 @@
 class ExprSequence {
 public:
   /// Initializes this `ExprSequence` with sequence information for the given
-  /// `CFG`.
-  ExprSequence(const CFG *TheCFG, ASTContext *TheContext);
+  /// `CFG`. `Root` is the root statement the CFG was built from.
+  ExprSequence(const CFG *TheCFG, const Stmt *Root, ASTContext *TheContext);
 
   /// Returns whether \p Before is sequenced before \p After.
   bool inSequence(const Stmt *Before, const Stmt *After) const;
@@ -94,6 +94,7 @@
   const Stmt *resolveSyntheticStmt(const Stmt *S) const;
 
   ASTContext *Context;
+  const Stmt *Root;
 
   llvm::DenseMap SyntheticStmtSourceMap;
 };
Index: clang-tidy/utils/ExprSequence.cpp
===
--- clang-tidy/utils/ExprSequence.cpp
+++ clang-tidy/utils/ExprSequence.cpp
@@ -63,8 +63,9 @@
 }
 }
 
-ExprSequence::ExprSequence(const CFG *TheCFG, ASTContext *TheContext)
-: Context(TheContext) {
+ExprSequence::ExprSequence(const CFG *TheCFG, const Stmt *Root,
+   ASTContext *TheContext)
+: Context(TheContext), Root(Root) {
   for (const auto &SyntheticStmt : TheCFG->synthetic_stmts()) {
 SyntheticStmtSourceMap[SyntheticStmt.first] = SyntheticStmt.second;
   }
@@ -99,6 +100,11 @@
 
 const Stmt *ExprSequence::getSequenceSuccessor(const Stmt *S) const {
   for (const Stmt *Parent : getParentStmts(S, Context)) {
+// For statements that have multiple parents, make sure we're using the
+// parent that lies within the sub-tree under Root.
+if (!isDescendantOrEqual(Parent, Root, Context))
+  continue;
+
 if (const auto *BO = dyn_cast(Parent)) {
   // Comma operator: Right-hand side is sequenced after the left-hand side.
   if (BO->getLHS() == S && BO->getOpcode() == BO_Comma)
Index: clang-tidy/bugprone/UseAfterMoveCheck.cpp
===
--- clang-tidy/bugprone/UseAfterMoveCheck.cpp
+++ clang-tidy/bugprone/UseAfterMoveCheck.cpp
@@ -102,8 +102,9 @@
   if (!TheCFG)
 return false;
 
-  Sequence.reset(new ExprSequence(TheCFG.get(), Context));
-  BlockMap.reset(new StmtToBlockMap(TheCFG.get(), Context));
+  Sequence =
+  llvm::make_unique(TheCFG.get(), FunctionBody, Context);
+  BlockMap = llvm::make_unique(TheCFG.get(), Context);
   Visited.clear();
 
   const CFGBlock *Block = BlockMap->blockContainingStmt(MovingCall);


Index: test/clang-tidy/bugprone-use-after-move.cpp
===
--- test/clang-tidy/bugprone-use-after-move.cpp
+++ test/clang-tidy/bugprone-use-after-move.cpp
@@ -1195,6 +1195,18 @@
   }
 }
 
+// Null statements (and some other statements) in templates may be shared
+// between the uninstantiated and instantiated versions of the template and
+// therefore have multiple parents. Make sure the sequencing code handles this
+// correctly.
+template  void nullStatementSequencesInTemplate() {
+  int c = 0;
+  (void)c;
+  ;
+  std::move(c);
+}
+template void nullStatementSequencesInTemplate();
+
 namespace PR33020 {
 class D {
   ~D();
Index: clang-tidy/utils/ExprSequence.h
===
--- clang-tidy/utils/ExprSequence.h
+++ clang-tidy/utils/ExprSequence.h
@@ -69,8 +69,8 @@
 class ExprSequence {
 public:
   /// Initializes this `ExprSequence` with sequence information for the given
-  /// `CFG`.
-  ExprSequence(const CFG *TheCFG, ASTContext *TheContext);
+  /// `CFG`. `Root` is the root statement the CFG was built from.
+  ExprSequence(const CFG *TheCFG, co

r343592 - [Preprocesssor] Filename should fall back to the written name when typo correction fails.

2018-10-02 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Tue Oct  2 07:42:51 2018
New Revision: 343592

URL: http://llvm.org/viewvc/llvm-project?rev=343592&view=rev
Log:
[Preprocesssor] Filename should fall back to the written name when typo 
correction fails.

Summary:
The test is added in  Testcase is at https://reviews.llvm.org/D52775. I tried 
to add the test to clang's code
completion test, it doesn't reproduce the crash.

Reviewers: sammccall, kristina

Reviewed By: sammccall

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

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

Modified:
cfe/trunk/lib/Lex/PPDirectives.cpp

Modified: cfe/trunk/lib/Lex/PPDirectives.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/PPDirectives.cpp?rev=343592&r1=343591&r2=343592&view=diff
==
--- cfe/trunk/lib/Lex/PPDirectives.cpp (original)
+++ cfe/trunk/lib/Lex/PPDirectives.cpp Tue Oct  2 07:42:51 2018
@@ -1898,21 +1898,25 @@ void Preprocessor::HandleIncludeDirectiv
   }
   return Filename;
 };
-Filename = CorrectTypoFilename(Filename);
+StringRef TypoCorrectionName = CorrectTypoFilename(Filename);
 File = LookupFile(
 FilenameLoc,
-LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
-LookupFrom, LookupFromFile, CurDir,
+LangOpts.MSVCCompat ? NormalizedPath.c_str() : TypoCorrectionName,
+isAngled, LookupFrom, LookupFromFile, CurDir,
 Callbacks ? &SearchPath : nullptr,
 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped);
 if (File) {
   SourceRange Range(FilenameTok.getLocation(), CharEnd);
-  auto Hint = isAngled ? FixItHint::CreateReplacement(
- Range, "<" + Filename.str() + ">")
-   : FixItHint::CreateReplacement(
- Range, "\"" + Filename.str() + "\"");
+  auto Hint = isAngled
+  ? FixItHint::CreateReplacement(
+Range, "<" + TypoCorrectionName.str() + ">")
+  : FixItHint::CreateReplacement(
+Range, "\"" + TypoCorrectionName.str() + "\"");
   Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
-  << OriginalFilename << Filename << Hint;
+  << OriginalFilename << TypoCorrectionName << Hint;
+  // We found the file, so set the Filename to the name after typo
+  // correction.
+  Filename = TypoCorrectionName;
 }
   }
 


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


[PATCH] D52774: [PProcesssor] Filename should fall back to the written name when typo correction fails.

2018-10-02 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC343592: [Preprocesssor] Filename should fall back to the 
written name when typo… (authored by hokein, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D52774?vs=167942&id=167948#toc

Repository:
  rC Clang

https://reviews.llvm.org/D52774

Files:
  lib/Lex/PPDirectives.cpp


Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -1898,21 +1898,25 @@
   }
   return Filename;
 };
-Filename = CorrectTypoFilename(Filename);
+StringRef TypoCorrectionName = CorrectTypoFilename(Filename);
 File = LookupFile(
 FilenameLoc,
-LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
-LookupFrom, LookupFromFile, CurDir,
+LangOpts.MSVCCompat ? NormalizedPath.c_str() : TypoCorrectionName,
+isAngled, LookupFrom, LookupFromFile, CurDir,
 Callbacks ? &SearchPath : nullptr,
 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped);
 if (File) {
   SourceRange Range(FilenameTok.getLocation(), CharEnd);
-  auto Hint = isAngled ? FixItHint::CreateReplacement(
- Range, "<" + Filename.str() + ">")
-   : FixItHint::CreateReplacement(
- Range, "\"" + Filename.str() + "\"");
+  auto Hint = isAngled
+  ? FixItHint::CreateReplacement(
+Range, "<" + TypoCorrectionName.str() + ">")
+  : FixItHint::CreateReplacement(
+Range, "\"" + TypoCorrectionName.str() + "\"");
   Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
-  << OriginalFilename << Filename << Hint;
+  << OriginalFilename << TypoCorrectionName << Hint;
+  // We found the file, so set the Filename to the name after typo
+  // correction.
+  Filename = TypoCorrectionName;
 }
   }
 


Index: lib/Lex/PPDirectives.cpp
===
--- lib/Lex/PPDirectives.cpp
+++ lib/Lex/PPDirectives.cpp
@@ -1898,21 +1898,25 @@
   }
   return Filename;
 };
-Filename = CorrectTypoFilename(Filename);
+StringRef TypoCorrectionName = CorrectTypoFilename(Filename);
 File = LookupFile(
 FilenameLoc,
-LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, isAngled,
-LookupFrom, LookupFromFile, CurDir,
+LangOpts.MSVCCompat ? NormalizedPath.c_str() : TypoCorrectionName,
+isAngled, LookupFrom, LookupFromFile, CurDir,
 Callbacks ? &SearchPath : nullptr,
 Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped);
 if (File) {
   SourceRange Range(FilenameTok.getLocation(), CharEnd);
-  auto Hint = isAngled ? FixItHint::CreateReplacement(
- Range, "<" + Filename.str() + ">")
-   : FixItHint::CreateReplacement(
- Range, "\"" + Filename.str() + "\"");
+  auto Hint = isAngled
+  ? FixItHint::CreateReplacement(
+Range, "<" + TypoCorrectionName.str() + ">")
+  : FixItHint::CreateReplacement(
+Range, "\"" + TypoCorrectionName.str() + "\"");
   Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
-  << OriginalFilename << Filename << Hint;
+  << OriginalFilename << TypoCorrectionName << Hint;
+  // We found the file, so set the Filename to the name after typo
+  // correction.
+  Filename = TypoCorrectionName;
 }
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r343593 - [clangd] Add a #include completion test that triggers an assertion.

2018-10-02 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Tue Oct  2 07:46:08 2018
New Revision: 343593

URL: http://llvm.org/viewvc/llvm-project?rev=343593&view=rev
Log:
[clangd] Add a #include completion test that triggers an assertion.

Summary: Test for https://reviews.llvm.org/D52774.

Reviewers: sammccall

Reviewed By: sammccall

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

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

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

Modified: clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp?rev=343593&r1=343592&r2=343593&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp Tue Oct  2 
07:46:08 2018
@@ -2093,6 +2093,15 @@ TEST(CompletionTest, IncludedCompletionK
 Has("bar.h\"", CompletionItemKind::File)));
 }
 
+TEST(CompletionTest, NoCrashAtNonAlphaIncludeHeader) {
+  auto Results = completions(
+  R"cpp(
+#include "./^"
+  )cpp"
+  );
+  EXPECT_TRUE(Results.Completions.empty());
+}
+
 TEST(CompletionTest, NoAllScopesCompletionWhenQualified) {
   clangd::CodeCompleteOptions Opts = {};
   Opts.AllScopes = true;


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


[PATCH] D52775: [clangd] Add a #include completion test that triggers an assertion.

2018-10-02 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE343593: [clangd] Add a #include completion test that 
triggers an assertion. (authored by hokein, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D52775?vs=167908&id=167949#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52775

Files:
  unittests/clangd/CodeCompleteTests.cpp


Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -2093,6 +2093,15 @@
 Has("bar.h\"", CompletionItemKind::File)));
 }
 
+TEST(CompletionTest, NoCrashAtNonAlphaIncludeHeader) {
+  auto Results = completions(
+  R"cpp(
+#include "./^"
+  )cpp"
+  );
+  EXPECT_TRUE(Results.Completions.empty());
+}
+
 TEST(CompletionTest, NoAllScopesCompletionWhenQualified) {
   clangd::CodeCompleteOptions Opts = {};
   Opts.AllScopes = true;


Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -2093,6 +2093,15 @@
 Has("bar.h\"", CompletionItemKind::File)));
 }
 
+TEST(CompletionTest, NoCrashAtNonAlphaIncludeHeader) {
+  auto Results = completions(
+  R"cpp(
+#include "./^"
+  )cpp"
+  );
+  EXPECT_TRUE(Results.Completions.empty());
+}
+
 TEST(CompletionTest, NoAllScopesCompletionWhenQualified) {
   clangd::CodeCompleteOptions Opts = {};
   Opts.AllScopes = true;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52781: [clangd] Don't make check-clangd as a dependency in check-clang-tools

2018-10-02 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

Verified that it does not block other clang-extra tools if clangd tests fail. 
Thank you very much for fixing!


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52781



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


Re: [PATCH] D52781: [clangd] Don't make check-clangd as a dependency in check-clang-tools

2018-10-02 Thread Roman Lebedev via cfe-commits
On Tue, Oct 2, 2018 at 5:54 PM Jonas Toth via Phabricator via
cfe-commits  wrote:
>
> JonasToth added a comment.
>
> Verified that it does not block other clang-extra tools if clangd tests fail. 
> Thank you very much for fixing!
Would be great to get check-clang-tidy target 'while there'.
>
> Repository:
>   rCTE Clang Tools Extra
>
> https://reviews.llvm.org/D52781
>
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52377: [HIP] Support early finalization of device code for -fno-gpu-rdc

2018-10-02 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 167952.
yaxunl edited the summary of this revision.
yaxunl added a comment.

Added -f{no}-cuda-rdc as alias to -f{no}-gpu-rdc.


https://reviews.llvm.org/D52377

Files:
  include/clang/Basic/LangOptions.def
  include/clang/Driver/Options.td
  include/clang/Driver/Types.def
  lib/AST/Decl.cpp
  lib/CodeGen/CGCUDANV.cpp
  lib/Driver/Driver.cpp
  lib/Driver/ToolChains/Clang.cpp
  lib/Driver/ToolChains/CommonArgs.cpp
  lib/Driver/ToolChains/Cuda.cpp
  lib/Driver/ToolChains/HIP.cpp
  lib/Driver/ToolChains/HIP.h
  lib/Frontend/CompilerInvocation.cpp
  lib/Sema/SemaDeclAttr.cpp
  test/CodeGenCUDA/device-stub.cu
  test/Driver/cuda-external-tools.cu
  test/Driver/cuda-phases.cu
  test/Driver/hip-output-file-name.hip
  test/Driver/hip-toolchain-no-rdc.hip
  test/Driver/hip-toolchain-rdc.hip
  test/Driver/hip-toolchain.hip
  test/SemaCUDA/extern-shared.cu

Index: test/SemaCUDA/extern-shared.cu
===
--- test/SemaCUDA/extern-shared.cu
+++ test/SemaCUDA/extern-shared.cu
@@ -1,8 +1,8 @@
 // RUN: %clang_cc1 -fsyntax-only -Wundefined-internal -verify %s
 // RUN: %clang_cc1 -fsyntax-only -Wundefined-internal -fcuda-is-device -verify %s
 
-// RUN: %clang_cc1 -fsyntax-only -Wundefined-internal -fcuda-rdc -verify=rdc %s
-// RUN: %clang_cc1 -fsyntax-only -Wundefined-internal -fcuda-is-device -fcuda-rdc -verify=rdc %s
+// RUN: %clang_cc1 -fsyntax-only -Wundefined-internal -fgpu-rdc -verify=rdc %s
+// RUN: %clang_cc1 -fsyntax-only -Wundefined-internal -fcuda-is-device -fgpu-rdc -verify=rdc %s
 
 // Most of these declarations are fine in separate compilation mode.
 
Index: test/Driver/hip-toolchain.hip
===
--- test/Driver/hip-toolchain.hip
+++ /dev/null
@@ -1,86 +0,0 @@
-// REQUIRES: clang-driver
-// REQUIRES: x86-registered-target
-// REQUIRES: amdgpu-registered-target
-
-// RUN: %clang -### -target x86_64-linux-gnu \
-// RUN:   -x hip --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
-// RUN:   --hip-device-lib=lib1.bc --hip-device-lib=lib2.bc \
-// RUN:   --hip-device-lib-path=%S/Inputs/hip_multiple_inputs/lib1 \
-// RUN:   --hip-device-lib-path=%S/Inputs/hip_multiple_inputs/lib2 \
-// RUN:   -fuse-ld=lld \
-// RUN:   %S/Inputs/hip_multiple_inputs/a.cu \
-// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
-// RUN: 2>&1 | FileCheck %s
-
-// CHECK: [[CLANG:".*clang.*"]] "-cc1" "-triple" "amdgcn-amd-amdhsa" 
-// CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu" "-emit-llvm-bc"
-// CHECK-SAME: {{.*}} "-main-file-name" "a.cu" {{.*}} "-target-cpu" "gfx803"
-// CHECK-SAME: "-fcuda-is-device" "-fvisibility" "hidden"
-// CHECK-SAME: {{.*}} "-o" [[A_BC:".*bc"]] "-x" "hip"
-// CHECK-SAME: {{.*}} [[A_SRC:".*a.cu"]]
-
-// CHECK: [[CLANG]] "-cc1" "-triple" "amdgcn-amd-amdhsa"
-// CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu" "-emit-llvm-bc"
-// CHECK-SAME: {{.*}} "-main-file-name" "b.hip" {{.*}} "-target-cpu" "gfx803"
-// CHECK-SAME: "-fcuda-is-device" "-fvisibility" "hidden"
-// CHECK-SAME: {{.*}} "-o" [[B_BC:".*bc"]] "-x" "hip"
-// CHECK-SAME: {{.*}} [[B_SRC:".*b.hip"]]
-
-// CHECK: [[LLVM_LINK:"*.llvm-link"]] [[A_BC]] [[B_BC]]
-// CHECK-SAME: "{{.*}}lib1.bc" "{{.*}}lib2.bc"
-// CHECK-SAME: "-o" [[LINKED_BC_DEV1:".*-gfx803-linked-.*bc"]]
-
-// CHECK: [[OPT:".*opt"]] [[LINKED_BC_DEV1]] "-mtriple=amdgcn-amd-amdhsa"
-// CHECK-SAME: "-mcpu=gfx803"
-// CHECK-SAME: "-o" [[OPT_BC_DEV1:".*-gfx803-optimized.*bc"]]
-
-// CHECK: [[LLC: ".*llc"]] [[OPT_BC_DEV1]] "-mtriple=amdgcn-amd-amdhsa"
-// CHECK-SAME: "-filetype=obj" "-mcpu=gfx803" "-o" [[OBJ_DEV1:".*-gfx803-.*o"]]
-
-// CHECK: [[LLD: ".*lld"]] "-flavor" "gnu" "--no-undefined" "-shared"
-// CHECK-SAME: "-o" "[[IMG_DEV1:.*out]]" [[OBJ_DEV1]]
-
-// CHECK: [[CLANG]] "-cc1" "-triple" "amdgcn-amd-amdhsa" 
-// CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu" "-emit-llvm-bc"
-// CHECK-SAME: {{.*}} "-main-file-name" "a.cu" {{.*}} "-target-cpu" "gfx900"
-// CHECK-SAME: "-fcuda-is-device" {{.*}} "-o" [[A_BC:".*bc"]] "-x" "hip"
-// CHECK-SAME: {{.*}} [[A_SRC]]
-
-// CHECK: [[CLANG]] "-cc1" "-triple" "amdgcn-amd-amdhsa"
-// CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu" "-emit-llvm-bc"
-// CHECK-SAME: {{.*}} "-main-file-name" "b.hip" {{.*}} "-target-cpu" "gfx900"
-// CHECK-SAME: "-fcuda-is-device" {{.*}} "-o" [[B_BC:".*bc"]] "-x" "hip"
-// CHECK-SAME: {{.*}} [[B_SRC]]
-
-// CHECK: [[LLVM_LINK]] [[A_BC]] [[B_BC]]
-// CHECK-SAME: "{{.*}}lib1.bc" "{{.*}}lib2.bc"
-// CHECK-SAME: "-o" [[LINKED_BC_DEV2:".*-gfx900-linked-.*bc"]]
-
-// CHECK: [[OPT]] [[LINKED_BC_DEV2]] "-mtriple=amdgcn-amd-amdhsa"
-// CHECK-SAME: "-mcpu=gfx900"
-// CHECK-SAME: "-o" [[OPT_BC_DEV2:".*-gfx900-optimized.*bc"]]
-
-// CHECK: [[LLC]] [[OPT_BC_DEV2]] "-mtriple=amdgcn-amd-amdhsa"
-// CHECK-SAME: "-filetype=obj" "-mcpu=gfx900" "-o" [[OBJ_DEV2:".*-gfx900-.*o"]]
-
-// CHECK: [[LLD]] "-flavor" "gnu" "--no-undefined" "-shared"
-// CHECK-SAME: "-o" "[[IMG_DEV2:.*out]]" [[

[PATCH] D52784: [ARM][AArch64] Pass through endianness flags to the GNU assembler

2018-10-02 Thread Peter Smith via Phabricator via cfe-commits
peter.smith created this revision.
peter.smith added reviewers: rengolin, compnerd, olista01.
Herald added subscribers: chrib, kristof.beyls, srhines.
Herald added a reviewer: javed.absar.

The big-endian arm32 Linux builds are currently failing when the -mbig-endian 
and -fno-use-integrated-as flags are used and the assembler default is little 
endian. We are not registering that the clang -mbig-endian flag needs to be 
passed through to the assembler to override its default target.

  

The patch always passes through -EL or -BE to the assembler, taking into 
account the target and the -mbig-endian and -mlittle-endian flag.

  

Fixes pr38770

FIXME: While fixing this I note that giving the endianness in march does not 
override the endianness in the triple. This is not specific to 
-fno-integrated-as so if I write --target=arm-linux-gnueabihf -march=armebv7-a 
then the output is little endian. I've updated the targets in the test so that 
the target endian matches the march endianness.

I think that this behaviour is wrong for a couple of reasons:

- -march=armebv7-a should either give an error message if it disagrees with the 
triple or should override the triple.
- The GNU assembler doesn't understand eb in march so we should ideally not 
pass it through, or rely on people to not use march that way.

This can be fixed but I've not done so in this patch.


https://reviews.llvm.org/D52784

Files:
  lib/Driver/ToolChains/Gnu.cpp
  test/Driver/linux-as.c

Index: test/Driver/linux-as.c
===
--- test/Driver/linux-as.c
+++ test/Driver/linux-as.c
@@ -3,129 +3,140 @@
 // RUN: %clang -target arm-linux -### \
 // RUN:   -no-integrated-as -c %s 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHECK-ARM %s
-// CHECK-ARM: as{{(.exe)?}}" "-mfloat-abi=soft"
+// CHECK-ARM: as{{(.exe)?}}" "-EL" "-mfloat-abi=soft"
 //
 // RUN: %clang -target arm-linux -mcpu=cortex-a8 -### \
 // RUN:   -no-integrated-as -c %s 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHECK-ARM-MCPU %s
-// CHECK-ARM-MCPU: as{{(.exe)?}}" "-mfloat-abi=soft" "-mcpu=cortex-a8"
+// CHECK-ARM-MCPU: as{{(.exe)?}}" "-EL" "-mfloat-abi=soft" "-mcpu=cortex-a8"
 //
 // RUN: %clang -target arm-linux -mfpu=neon -### \
 // RUN:   -no-integrated-as -c %s 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHECK-ARM-MFPU %s
-// CHECK-ARM-MFPU: as{{(.exe)?}}" "-mfloat-abi=soft" "-mfpu=neon"
+// CHECK-ARM-MFPU: as{{(.exe)?}}" "-EL" "-mfloat-abi=soft" "-mfpu=neon"
 //
 // RUN: %clang -target arm-linux -march=armv7-a -### \
 // RUN:   -no-integrated-as -c %s 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHECK-ARM-MARCH %s
-// CHECK-ARM-MARCH: as{{(.exe)?}}" "-mfloat-abi=soft" "-march=armv7-a"
+// CHECK-ARM-MARCH: as{{(.exe)?}}" "-EL" "-mfloat-abi=soft" "-march=armv7-a"
+//
+// RUN: %clang -target armeb-linux -mlittle-endian -mcpu=cortex-a8 -mfpu=neon -march=armv7-a -### \
+// RUN:   -no-integrated-as -c %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-ARM-ALL %s
+// CHECK-ARM-ALL: as{{(.exe)?}}" "-EL" "-mfloat-abi=soft" "-march=armv7-a" "-mcpu=cortex-a8" "-mfpu=neon"
 //
 // RUN: %clang -target arm-linux -mcpu=cortex-a8 -mfpu=neon -march=armv7-a -### \
 // RUN:   -no-integrated-as -c %s 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHECK-ARM-ALL %s
-// CHECK-ARM-ALL: as{{(.exe)?}}" "-mfloat-abi=soft" "-march=armv7-a" "-mcpu=cortex-a8" "-mfpu=neon"
 //
-// RUN: %clang -target arm-linux -mcpu=cortex-a8 -mfpu=neon -march=armebv7-a -### \
+// RUN: %clang -target armeb-linux -mcpu=cortex-a8 -mfpu=neon -march=armebv7-a -### \
+// RUN:   -no-integrated-as -c %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-ARMEB-ALL %s
+// CHECK-ARMEB-ALL: as{{(.exe)?}}" "-EB" "-mfloat-abi=soft" "-march=armebv7-a" "-mcpu=cortex-a8" "-mfpu=neon"
+//
+// RUN: %clang -target arm-linux -mcpu=cortex-a8 -mfpu=neon -march=armebv7-a -mbig-endian -### \
 // RUN:   -no-integrated-as -c %s 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHECK-ARMEB-ALL %s
-// CHECK-ARMEB-ALL: as{{(.exe)?}}" "-mfloat-abi=soft" "-march=armebv7-a" "-mcpu=cortex-a8" "-mfpu=neon"
 //
 // RUN: %clang -target thumb-linux -mcpu=cortex-a8 -mfpu=neon -march=thumbv7-a -### \
 // RUN:   -no-integrated-as -c %s 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHECK-THUMB-ALL %s
-// CHECK-THUMB-ALL: as{{(.exe)?}}" "-mfloat-abi=soft" "-march=thumbv7-a" "-mcpu=cortex-a8" "-mfpu=neon"
+// CHECK-THUMB-ALL: as{{(.exe)?}}" "-EL" "-mfloat-abi=soft" "-march=thumbv7-a" "-mcpu=cortex-a8" "-mfpu=neon"
 //
-// RUN: %clang -target thumb-linux -mcpu=cortex-a8 -mfpu=neon -march=thumbebv7-a -### \
+// RUN: %clang -target thumbeb-linux -mcpu=cortex-a8 -mfpu=neon -march=thumbebv7-a -### \
 // RUN:   -no-integrated-as -c %s 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHECK-THUMBEB-ALL %s
-// CHECK-THUMBEB-ALL: as{{(.exe)?}}" "-mfloat-abi=soft" "-march=thumbebv7-a" "-mcpu=cortex-a8" "-mfpu=neon"
+// CHECK-THUMBEB-ALL: as{{(.exe)?}}" "-EB" "-mfloat-abi=soft" "-march=thumbebv7-a" "-mcpu=cortex-a8" "-mfpu=neo

[PATCH] D52784: [ARM][AArch64] Pass through endianness flags to the GNU assembler

2018-10-02 Thread Renato Golin via Phabricator via cfe-commits
rengolin added a comment.

Hi Peter,

Looks ok. Why did you need to change all cmdlines to have -EL? I imagine you 
just need one for each case, everything else remains the default (which should 
still work).

Also, it would be interesting to know what happens on cases like "aarch64_be 
-EL" et al, and have negative tests for them.

cheers,
--renato


https://reviews.llvm.org/D52784



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


[PATCH] D52784: [ARM][AArch64] Pass through endianness flags to the GNU assembler

2018-10-02 Thread Peter Smith via Phabricator via cfe-commits
peter.smith added a comment.

In https://reviews.llvm.org/D52784#1252569, @rengolin wrote:

> Hi Peter,
>
> Looks ok. Why did you need to change all cmdlines to have -EL? I imagine you 
> just need one for each case, everything else remains the default (which 
> should still work).


I thought that in general we wouldn't know what the default endianness of the 
assembler we are targeting is so it was safest to be explicit. For a 
cross-toolchain it is probably inherent in the name, but in theory we could be 
running clang on a native big-endian system where the assembler is just called 
as.

> Also, it would be interesting to know what happens on cases like "aarch64_be 
> -EL" et al, and have negative tests for them.

Ok will add some more tests.

> cheers,
> --renato




https://reviews.llvm.org/D52784



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


  1   2   3   >