[PATCH] D49838: [AST] Sink 'part of explicit cast' down into ImplicitCastExpr

2018-07-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri created this revision.
lebedev.ri added reviewers: rsmith, rjmccall, erichkeane, aaron.ballman.
lebedev.ri added a project: clang.
lebedev.ri added a dependency: D49508: [Sema] Mark implicitly-inserted ICE's as 
being part of explicit cast (PR38166).

As discussed in IRC with @rsmith, it is slightly not good to keep that in the 
`CastExpr` itself:
Given the explicit cast, which is represented in AST as an `ExplicitCastExpr` + 
`ImplicitCastExpr`'s,
only the  `ImplicitCastExpr`'s will be marked as `PartOfExplicitCast`, but not 
the `ExplicitCastExpr` itself.
Thus, it is only ever `true` for `ImplicitCastExpr`'s, so we don't need to 
write/read/dump it for `ExplicitCastExpr`'s.


Repository:
  rC Clang

https://reviews.llvm.org/D49838

Files:
  include/clang/AST/Expr.h
  include/clang/AST/Stmt.h
  lib/AST/ASTDumper.cpp
  lib/Sema/SemaCast.cpp
  lib/Serialization/ASTReaderStmt.cpp
  lib/Serialization/ASTWriterStmt.cpp

Index: lib/Serialization/ASTWriterStmt.cpp
===
--- lib/Serialization/ASTWriterStmt.cpp
+++ lib/Serialization/ASTWriterStmt.cpp
@@ -665,7 +665,6 @@
   Record.push_back(E->path_size());
   Record.AddStmt(E->getSubExpr());
   Record.push_back(E->getCastKind()); // FIXME: stable encoding
-  Record.push_back(E->getIsPartOfExplicitCast());
 
   for (CastExpr::path_iterator
  PI = E->path_begin(), PE = E->path_end(); PI != PE; ++PI)
@@ -714,6 +713,7 @@
 
 void ASTStmtWriter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
   VisitCastExpr(E);
+  Record.push_back(E->getIsPartOfExplicitCast());
 
   if (E->path_size() == 0)
 AbbrevToUse = Writer.getExprImplicitCastAbbrev();
Index: lib/Serialization/ASTReaderStmt.cpp
===
--- lib/Serialization/ASTReaderStmt.cpp
+++ lib/Serialization/ASTReaderStmt.cpp
@@ -723,7 +723,6 @@
   assert(NumBaseSpecs == E->path_size());
   E->setSubExpr(Record.readSubExpr());
   E->setCastKind((CastKind)Record.readInt());
-  E->setIsPartOfExplicitCast(Record.readInt());
   CastExpr::path_iterator BaseI = E->path_begin();
   while (NumBaseSpecs--) {
 auto *BaseSpec = new (Record.getContext()) CXXBaseSpecifier;
@@ -770,6 +769,7 @@
 
 void ASTStmtReader::VisitImplicitCastExpr(ImplicitCastExpr *E) {
   VisitCastExpr(E);
+  E->setIsPartOfExplicitCast(Record.readInt());
 }
 
 void ASTStmtReader::VisitExplicitCastExpr(ExplicitCastExpr *E) {
Index: lib/Sema/SemaCast.cpp
===
--- lib/Sema/SemaCast.cpp
+++ lib/Sema/SemaCast.cpp
@@ -94,7 +94,7 @@
   // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE
   // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched.
   while ((CE = dyn_cast(CE->getSubExpr(
-CE->setIsPartOfExplicitCast(true);
+dyn_cast(CE)->setIsPartOfExplicitCast(true);
 }
 
 /// Complete an apparently-successful cast operation that yields
Index: lib/AST/ASTDumper.cpp
===
--- lib/AST/ASTDumper.cpp
+++ lib/AST/ASTDumper.cpp
@@ -521,6 +521,7 @@
 // Exprs
 void VisitExpr(const Expr *Node);
 void VisitCastExpr(const CastExpr *Node);
+void VisitImplicitCastExpr(const ImplicitCastExpr *Node);
 void VisitDeclRefExpr(const DeclRefExpr *Node);
 void VisitPredefinedExpr(const PredefinedExpr *Node);
 void VisitCharacterLiteral(const CharacterLiteral *Node);
@@ -2117,7 +2118,10 @@
   }
   dumpBasePath(OS, Node);
   OS << ">";
+}
 
+void ASTDumper::VisitImplicitCastExpr(const ImplicitCastExpr *Node) {
+  VisitCastExpr(Node);
   if (Node->getIsPartOfExplicitCast())
 OS << " part_of_explicit_cast";
 }
Index: include/clang/AST/Stmt.h
===
--- include/clang/AST/Stmt.h
+++ include/clang/AST/Stmt.h
@@ -198,6 +198,7 @@
 
   class CastExprBitfields {
 friend class CastExpr;
+friend class ImplicitCastExpr;
 
 unsigned : NumExprBits;
 
Index: include/clang/AST/Expr.h
===
--- include/clang/AST/Expr.h
+++ include/clang/AST/Expr.h
@@ -2821,7 +2821,6 @@
   (op && op->containsUnexpandedParameterPack(,
 Op(op) {
 CastExprBits.Kind = kind;
-CastExprBits.PartOfExplicitCast = false;
 setBasePathSize(BasePathSize);
 assert(CastConsistency());
   }
@@ -2836,13 +2835,6 @@
   CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
   void setCastKind(CastKind K) { CastExprBits.Kind = K; }
 
-  bool getIsPartOfExplicitCast() const {
-return CastExprBits.PartOfExplicitCast;
-  }
-  void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
-CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
-  }
-
   static const char *getCastKindName(CastKind CK);
   const char *getCastKindName() const { return getCastKindName(getCastKind()); }
 
@@ -2917,18

[PATCH] D49627: [CFG] [analyzer] Constructors of member CXXOperatorCallExpr's argument 0 are not argument constructors.

2018-07-26 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware added a comment.

"Actually supporting such this-argument construction contexts would address the 
FIXME that we've added in https://reviews.llvm.org/D32642 but this patch 
doesn't go that far."

Maybe a FIXME here so we do not forget to continue it in the future?


https://reviews.llvm.org/D49627



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


[PATCH] D49627: [CFG] [analyzer] Constructors of member CXXOperatorCallExpr's argument 0 are not argument constructors.

2018-07-26 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware added a comment.

How much different is a correct `this`-argument construction context from real 
argument construction contexts?


https://reviews.llvm.org/D49627



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


[PATCH] D49650: Targets/AMDGPU: Don't set fp32-denormals feature for r600

2018-07-26 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added a comment.

In https://reviews.llvm.org/D49650#1175461, @jvesely wrote:

> In https://reviews.llvm.org/D49650#1175438, @arsenm wrote:
>
> > According to cayman manual, these registers do exist so we should probably 
> > just make the feature accepted on r600 as well
>
>
> sure, that's the way it was before r335942. I assumed the removal was 
> intentional.


Probably accidental because nothing in r600 was actually using it


Repository:
  rC Clang

https://reviews.llvm.org/D49650



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


[PATCH] D49833: [clangd] Receive compilationDatabasePath in 'initialize' request

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

Not strictly opposed to this change, but should any reason why the clients 
can't guarantee they'll send didChangeConfiguration right after clangd is 
initialized?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49833



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


[PATCH] D49783: [clangd] Do not rebuild AST if inputs have not changed

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

- Move OldPreamble.reset() out of the lock, add a comment


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49783

Files:
  clangd/TUScheduler.cpp
  test/clangd/extra-flags.test
  unittests/clangd/TUSchedulerTests.cpp
  unittests/clangd/TestFS.cpp
  unittests/clangd/TestFS.h

Index: unittests/clangd/TestFS.h
===
--- unittests/clangd/TestFS.h
+++ unittests/clangd/TestFS.h
@@ -23,7 +23,8 @@
 // Builds a VFS that provides access to the provided files, plus temporary
 // directories.
 llvm::IntrusiveRefCntPtr
-buildTestFS(llvm::StringMap const &Files);
+buildTestFS(llvm::StringMap const &Files,
+llvm::StringMap const &Timestamps = {});
 
 // A VFS provider that returns TestFSes containing a provided set of files.
 class MockFSProvider : public FileSystemProvider {
Index: unittests/clangd/TestFS.cpp
===
--- unittests/clangd/TestFS.cpp
+++ unittests/clangd/TestFS.cpp
@@ -19,13 +19,15 @@
 using namespace llvm;
 
 IntrusiveRefCntPtr
-buildTestFS(StringMap const &Files) {
+buildTestFS(llvm::StringMap const &Files,
+llvm::StringMap const &Timestamps) {
   IntrusiveRefCntPtr MemFS(
   new vfs::InMemoryFileSystem);
   for (auto &FileAndContents : Files) {
-MemFS->addFile(FileAndContents.first(), time_t(),
-   MemoryBuffer::getMemBufferCopy(FileAndContents.second,
-  FileAndContents.first()));
+StringRef File = FileAndContents.first();
+MemFS->addFile(
+File, Timestamps.lookup(File),
+MemoryBuffer::getMemBufferCopy(FileAndContents.second, File));
   }
   return MemFS;
 }
Index: unittests/clangd/TUSchedulerTests.cpp
===
--- unittests/clangd/TUSchedulerTests.cpp
+++ unittests/clangd/TUSchedulerTests.cpp
@@ -33,13 +33,12 @@
 class TUSchedulerTests : public ::testing::Test {
 protected:
   ParseInputs getInputs(PathRef File, std::string Contents) {
-return ParseInputs{*CDB.getCompileCommand(File), buildTestFS(Files),
-   std::move(Contents)};
+return ParseInputs{*CDB.getCompileCommand(File),
+   buildTestFS(Files, Timestamps), std::move(Contents)};
   }
 
   llvm::StringMap Files;
-
-private:
+  llvm::StringMap Timestamps;
   MockCompilationDatabase CDB;
 };
 
@@ -263,6 +262,10 @@
 int* a;
 double* b = a;
   )cpp";
+  llvm::StringLiteral OtherSourceContents = R"cpp(
+int* a;
+double* b = a + 0;
+  )cpp";
 
   auto Foo = testPath("foo.cpp");
   auto Bar = testPath("bar.cpp");
@@ -288,7 +291,7 @@
   ASSERT_THAT(S.getFilesWithCachedAST(), UnorderedElementsAre(Bar, Baz));
 
   // Access the old file again.
-  S.update(Foo, getInputs(Foo, SourceContents), WantDiagnostics::Yes,
+  S.update(Foo, getInputs(Foo, OtherSourceContents), WantDiagnostics::Yes,
[&BuiltASTCounter](std::vector Diags) { ++BuiltASTCounter; });
   ASSERT_TRUE(S.blockUntilIdle(timeoutSeconds(1)));
   ASSERT_EQ(BuiltASTCounter.load(), 4);
@@ -334,5 +337,58 @@
   ASSERT_THAT(Preambles, Each(Preambles[0]));
 }
 
+TEST_F(TUSchedulerTests, NoopOnEmptyChanges) {
+  TUScheduler S(
+  /*AsyncThreadsCount=*/getDefaultAsyncThreadsCount(),
+  /*StorePreambleInMemory=*/true, PreambleParsedCallback(),
+  /*UpdateDebounce=*/std::chrono::steady_clock::duration::zero(),
+  ASTRetentionPolicy());
+
+  auto Source = testPath("foo.cpp");
+  auto Header = testPath("foo.h");
+
+  Files[Header] = "int a;";
+  Timestamps[Header] = time_t(0);
+
+  auto SourceContents = R"cpp(
+  #include "foo.h"
+  int b = a;
+)cpp";
+
+  // Return value indicates if the updated callback was received.
+  auto DoUpdate = [&](ParseInputs Inputs) -> bool {
+std::atomic Updated(false);
+Updated = false;
+S.update(Source, std::move(Inputs), WantDiagnostics::Yes,
+ [&Updated](std::vector) { Updated = true; });
+bool UpdateFinished = S.blockUntilIdle(timeoutSeconds(1));
+if (!UpdateFinished)
+  ADD_FAILURE() << "Updated has not finished in one second. Threading bug?";
+return Updated;
+  };
+
+  // Test that subsequent updates with the same inputs do not cause rebuilds.
+  ASSERT_TRUE(DoUpdate(getInputs(Source, SourceContents)));
+  ASSERT_FALSE(DoUpdate(getInputs(Source, SourceContents)));
+
+  // Update to a header should cause a rebuild, though.
+  Files[Header] = time_t(1);
+  ASSERT_TRUE(DoUpdate(getInputs(Source, SourceContents)));
+  ASSERT_FALSE(DoUpdate(getInputs(Source, SourceContents)));
+
+  // Update to the contents should cause a rebuild.
+  auto OtherSourceContents = R"cpp(
+  #include "foo.h"
+  int c = d;
+)cpp";
+  ASSERT_TRUE(DoUpdate(getInputs(Source, OtherSourceContents)));
+  ASSERT_FALSE(DoUpdate(getInputs(Source, OtherSourceCo

[clang-tools-extra] r338012 - [clangd] Do not rebuild AST if inputs have not changed

2018-07-26 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Thu Jul 26 02:21:07 2018
New Revision: 338012

URL: http://llvm.org/viewvc/llvm-project?rev=338012&view=rev
Log:
[clangd] Do not rebuild AST if inputs have not changed

Summary:
If the contents are the same, the update most likely comes from the
fact that compile commands were invalidated. In that case we want to
avoid rebuilds in case the compile commands are actually the same.

Reviewers: ioeric

Reviewed By: ioeric

Subscribers: simark, javed.absar, MaskRay, jkorous, arphaman, jfb, cfe-commits

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

Modified:
clang-tools-extra/trunk/clangd/TUScheduler.cpp
clang-tools-extra/trunk/test/clangd/extra-flags.test
clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp
clang-tools-extra/trunk/unittests/clangd/TestFS.cpp
clang-tools-extra/trunk/unittests/clangd/TestFS.h

Modified: clang-tools-extra/trunk/clangd/TUScheduler.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/TUScheduler.cpp?rev=338012&r1=338011&r2=338012&view=diff
==
--- clang-tools-extra/trunk/clangd/TUScheduler.cpp (original)
+++ clang-tools-extra/trunk/clangd/TUScheduler.cpp Thu Jul 26 02:21:07 2018
@@ -324,6 +324,11 @@ void ASTWorker::update(
 ParseInputs Inputs, WantDiagnostics WantDiags,
 llvm::unique_function)> OnUpdated) {
   auto Task = [=](decltype(OnUpdated) OnUpdated) mutable {
+// Will be used to check if we can avoid rebuilding the AST.
+bool InputsAreTheSame =
+std::tie(FileInputs.CompileCommand, FileInputs.Contents) ==
+std::tie(Inputs.CompileCommand, Inputs.Contents);
+
 tooling::CompileCommand OldCommand = std::move(FileInputs.CompileCommand);
 FileInputs = Inputs;
 // Remove the old AST if it's still in cache.
@@ -343,16 +348,38 @@ void ASTWorker::update(
   return;
 }
 
-std::shared_ptr NewPreamble = buildPreamble(
-FileName, *Invocation, getPossiblyStalePreamble(), OldCommand, Inputs,
-PCHs, StorePreambleInMemory, PreambleCallback);
+std::shared_ptr OldPreamble =
+getPossiblyStalePreamble();
+std::shared_ptr NewPreamble =
+buildPreamble(FileName, *Invocation, OldPreamble, OldCommand, Inputs,
+  PCHs, StorePreambleInMemory, PreambleCallback);
+
+bool CanReuseAST = InputsAreTheSame && (OldPreamble == NewPreamble);
 {
   std::lock_guard Lock(Mutex);
   if (NewPreamble)
 LastBuiltPreamble = NewPreamble;
 }
+// Before doing the expensive AST reparse, we want to release our reference
+// to the old preamble, so it can be freed if there are no other references
+// to it.
+OldPreamble.reset();
 PreambleWasBuilt.notify();
 
+if (CanReuseAST) {
+  // Take a shortcut and don't build the AST, neither the inputs nor the
+  // preamble have changed.
+  // Note that we do not report the diagnostics, since they should not have
+  // changed either. All the clients should handle the lack of OnUpdated()
+  // call anyway, to handle empty result from buildAST.
+  // FIXME(ibiryukov): the AST could actually change if non-preamble
+  // includes changed, but we choose to ignore it.
+  // FIXME(ibiryukov): should we refresh the cache in IdleASTs for the
+  // current file at this point?
+  log("Skipping rebuild of the AST for {0}, inputs are the same.",
+  FileName);
+  return;
+}
 // Build the AST for diagnostics.
 llvm::Optional AST =
 buildAST(FileName, std::move(Invocation), Inputs, NewPreamble, PCHs);

Modified: clang-tools-extra/trunk/test/clangd/extra-flags.test
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clangd/extra-flags.test?rev=338012&r1=338011&r2=338012&view=diff
==
--- clang-tools-extra/trunk/test/clangd/extra-flags.test (original)
+++ clang-tools-extra/trunk/test/clangd/extra-flags.test Thu Jul 26 02:21:07 
2018
@@ -23,7 +23,7 @@
 # CHECK-NEXT:"uri": "file://{{.*}}/foo.c"
 # CHECK-NEXT:  }
 ---
-{"jsonrpc":"2.0","method":"textDocument/didChange","params":{"textDocument":{"uri":"test:///foo.c","version":2},"contentChanges":[{"text":"int
 main() { int i; return i; }"}]}}
+{"jsonrpc":"2.0","method":"textDocument/didChange","params":{"textDocument":{"uri":"test:///foo.c","version":2},"contentChanges":[{"text":"int
 main() { int i; return i+1; }"}]}}
 #  CHECK:  "method": "textDocument/publishDiagnostics",
 # CHECK-NEXT:  "params": {
 # CHECK-NEXT:"diagnostics": [

Modified: clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp?rev=338012&r1=338011&r2=338012&view=diff
==
--- clang-tools-extra/trunk/unittes

[PATCH] D49783: [clangd] Do not rebuild AST if inputs have not changed

2018-07-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clangd/TUScheduler.cpp:360
   std::lock_guard Lock(Mutex);
+  OldPreamble.reset();
   if (NewPreamble)

ioeric wrote:
> ilya-biryukov wrote:
> > ioeric wrote:
> > > Why reset?
> > We don't need the old preamble at this point, so we give it a chance to die 
> > (if there are no more references).
> > Note that there's an expensive operation that follows (building the AST), 
> > so removing the preamble before it seems like a win
> sg. and do we guard this with mutex because the same old preamble data can be 
> accessed  by other threads? might worth a comment.
Guarding with mutex is not actually required. Moved it out of the locked 
section and added a comment, thanks!


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49783



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


[PATCH] D49783: [clangd] Do not rebuild AST if inputs have not changed

2018-07-26 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL338012: [clangd] Do not rebuild AST if inputs have not 
changed (authored by ibiryukov, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D49783

Files:
  clang-tools-extra/trunk/clangd/TUScheduler.cpp
  clang-tools-extra/trunk/test/clangd/extra-flags.test
  clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp
  clang-tools-extra/trunk/unittests/clangd/TestFS.cpp
  clang-tools-extra/trunk/unittests/clangd/TestFS.h

Index: clang-tools-extra/trunk/clangd/TUScheduler.cpp
===
--- clang-tools-extra/trunk/clangd/TUScheduler.cpp
+++ clang-tools-extra/trunk/clangd/TUScheduler.cpp
@@ -324,6 +324,11 @@
 ParseInputs Inputs, WantDiagnostics WantDiags,
 llvm::unique_function)> OnUpdated) {
   auto Task = [=](decltype(OnUpdated) OnUpdated) mutable {
+// Will be used to check if we can avoid rebuilding the AST.
+bool InputsAreTheSame =
+std::tie(FileInputs.CompileCommand, FileInputs.Contents) ==
+std::tie(Inputs.CompileCommand, Inputs.Contents);
+
 tooling::CompileCommand OldCommand = std::move(FileInputs.CompileCommand);
 FileInputs = Inputs;
 // Remove the old AST if it's still in cache.
@@ -343,16 +348,38 @@
   return;
 }
 
-std::shared_ptr NewPreamble = buildPreamble(
-FileName, *Invocation, getPossiblyStalePreamble(), OldCommand, Inputs,
-PCHs, StorePreambleInMemory, PreambleCallback);
+std::shared_ptr OldPreamble =
+getPossiblyStalePreamble();
+std::shared_ptr NewPreamble =
+buildPreamble(FileName, *Invocation, OldPreamble, OldCommand, Inputs,
+  PCHs, StorePreambleInMemory, PreambleCallback);
+
+bool CanReuseAST = InputsAreTheSame && (OldPreamble == NewPreamble);
 {
   std::lock_guard Lock(Mutex);
   if (NewPreamble)
 LastBuiltPreamble = NewPreamble;
 }
+// Before doing the expensive AST reparse, we want to release our reference
+// to the old preamble, so it can be freed if there are no other references
+// to it.
+OldPreamble.reset();
 PreambleWasBuilt.notify();
 
+if (CanReuseAST) {
+  // Take a shortcut and don't build the AST, neither the inputs nor the
+  // preamble have changed.
+  // Note that we do not report the diagnostics, since they should not have
+  // changed either. All the clients should handle the lack of OnUpdated()
+  // call anyway, to handle empty result from buildAST.
+  // FIXME(ibiryukov): the AST could actually change if non-preamble
+  // includes changed, but we choose to ignore it.
+  // FIXME(ibiryukov): should we refresh the cache in IdleASTs for the
+  // current file at this point?
+  log("Skipping rebuild of the AST for {0}, inputs are the same.",
+  FileName);
+  return;
+}
 // Build the AST for diagnostics.
 llvm::Optional AST =
 buildAST(FileName, std::move(Invocation), Inputs, NewPreamble, PCHs);
Index: clang-tools-extra/trunk/test/clangd/extra-flags.test
===
--- clang-tools-extra/trunk/test/clangd/extra-flags.test
+++ clang-tools-extra/trunk/test/clangd/extra-flags.test
@@ -23,7 +23,7 @@
 # CHECK-NEXT:"uri": "file://{{.*}}/foo.c"
 # CHECK-NEXT:  }
 ---
-{"jsonrpc":"2.0","method":"textDocument/didChange","params":{"textDocument":{"uri":"test:///foo.c","version":2},"contentChanges":[{"text":"int main() { int i; return i; }"}]}}
+{"jsonrpc":"2.0","method":"textDocument/didChange","params":{"textDocument":{"uri":"test:///foo.c","version":2},"contentChanges":[{"text":"int main() { int i; return i+1; }"}]}}
 #  CHECK:  "method": "textDocument/publishDiagnostics",
 # CHECK-NEXT:  "params": {
 # CHECK-NEXT:"diagnostics": [
Index: clang-tools-extra/trunk/unittests/clangd/TestFS.h
===
--- clang-tools-extra/trunk/unittests/clangd/TestFS.h
+++ clang-tools-extra/trunk/unittests/clangd/TestFS.h
@@ -23,7 +23,8 @@
 // Builds a VFS that provides access to the provided files, plus temporary
 // directories.
 llvm::IntrusiveRefCntPtr
-buildTestFS(llvm::StringMap const &Files);
+buildTestFS(llvm::StringMap const &Files,
+llvm::StringMap const &Timestamps = {});
 
 // A VFS provider that returns TestFSes containing a provided set of files.
 class MockFSProvider : public FileSystemProvider {
Index: clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp
@@ -33,13 +33,12 @@
 class TUSchedulerTests : public ::testing::Test {
 protected:
   ParseInputs getInputs(PathRef File, std::string Conten

[PATCH] D49783: [clangd] Do not rebuild AST if inputs have not changed

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

In https://reviews.llvm.org/D49783#1175688, @simark wrote:

> Thanks, that's simple and efficient.  I'll update 
> https://reviews.llvm.org/D49267 (to call `reparseOpenFiles` once again) once 
> this is merged.


LG, thanks!


Repository:
  rL LLVM

https://reviews.llvm.org/D49783



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


[PATCH] D49228: [analyzer][UninitializedObjectChecker] Void pointer objects are casted back to their dynmic type in note message

2018-07-26 Thread Whisperity via Phabricator via cfe-commits
whisperity added inline comments.



Comment at: test/Analysis/cxx-uninitialized-object-ptr-ref.cpp:290
 struct IntDynTypedVoidPointerTest1 {
-  void *vptr; // expected-note{{uninitialized pointee 'this->vptr'}}
+  void *vptr; // expected-note{{uninitialized pointee 'this->static_cast(vptr)'}}
   int dontGetFilteredByNonPedanticMode = 0;

NoQ wrote:
> Shouldn't this rather say something like `static_cast(this->vptr)`? 
> That's the normal syntax to do this sort of stuff, i guess.
Not just "normal syntax", this syntax of the output does not compile.

```
foo.cpp:6:13: error: expected unqualified-id
  this->static_cast(vptr) = new int();
```


https://reviews.llvm.org/D49228



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


[PATCH] D49546: [clangd] Proof-of-concept query iterators for Dex symbol index

2018-07-26 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 157439.
kbobyrev added a comment.

Typo: "Returns false if ..., false otherwise" ->"Returns false if ..., true 
otherwise".


https://reviews.llvm.org/D49546

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/index/dex/Iterator.cpp
  clang-tools-extra/clangd/index/dex/Iterator.h
  clang-tools-extra/unittests/clangd/CMakeLists.txt
  clang-tools-extra/unittests/clangd/DexIndexTests.cpp

Index: clang-tools-extra/unittests/clangd/DexIndexTests.cpp
===
--- /dev/null
+++ clang-tools-extra/unittests/clangd/DexIndexTests.cpp
@@ -0,0 +1,232 @@
+//===--- DexIndexTests.cpp *- C++ -*---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "index/dex/Iterator.h"
+#include "llvm/Support/ScopedPrinter.h"
+#include "llvm/Support/raw_ostream.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+namespace clang {
+namespace clangd {
+namespace dex {
+
+using ::testing::ElementsAre;
+
+TEST(DexIndexIterators, DocumentIterator) {
+  auto DocIterator = create({4, 7, 8, 20, 42, 100});
+
+  EXPECT_EQ(DocIterator->peek(), 4U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advance();
+  EXPECT_EQ(DocIterator->peek(), 7U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advanceTo(20);
+  EXPECT_EQ(DocIterator->peek(), 20U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advanceTo(65);
+  EXPECT_EQ(DocIterator->peek(), 100U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advanceTo(420);
+  EXPECT_EQ(DocIterator->reachedEnd(), true);
+}
+
+TEST(DexIndexIterators, AndWithEmpty) {
+  const PostingList L0;
+  const PostingList L1 = {0, 5, 7, 10, 42, 320, 9000};
+
+  auto AndEmpty = createAnd({create(L0)});
+  EXPECT_EQ(AndEmpty->reachedEnd(), true);
+
+  auto AndWithEmpty = createAnd({create(L0), create(L1)});
+  EXPECT_EQ(AndWithEmpty->reachedEnd(), true);
+
+  EXPECT_THAT(consume(*AndWithEmpty), ElementsAre());
+}
+
+TEST(DexIndexIterators, AndTwoLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+
+  auto And = createAnd({create(L1), create(L0)});
+
+  EXPECT_EQ(And->reachedEnd(), false);
+  EXPECT_THAT(consume(*And), ElementsAre(0U, 7U, 10U, 320U, 9000U));
+
+  And = createAnd({create(L0), create(L1)});
+
+  And->advanceTo(0);
+  EXPECT_EQ(And->peek(), 0U);
+  And->advanceTo(5);
+  EXPECT_EQ(And->peek(), 7U);
+  And->advanceTo(10);
+  EXPECT_EQ(And->peek(), 10U);
+  And->advanceTo(42);
+  EXPECT_EQ(And->peek(), 320U);
+  And->advanceTo(8999);
+  EXPECT_EQ(And->peek(), 9000U);
+  And->advanceTo(9001);
+}
+
+TEST(DexIndexIterators, AndThreeLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+  const PostingList L2 = {1, 4, 7, 11, 30, 60, 320, 9000};
+
+  auto And = createAnd({create(L0), create(L1), create(L2)});
+  EXPECT_EQ(And->peek(), 7U);
+  And->advanceTo(300);
+  EXPECT_EQ(And->peek(), 320U);
+  And->advanceTo(10);
+
+  EXPECT_EQ(And->reachedEnd(), true);
+}
+
+TEST(DexIndexIterators, OrWithEmpty) {
+  const PostingList L0;
+  const PostingList L1 = {0, 5, 7, 10, 42, 320, 9000};
+
+  auto OrEmpty = createOr({create(L0)});
+  EXPECT_EQ(OrEmpty->reachedEnd(), true);
+
+  auto OrWithEmpty = createOr({create(L0), create(L1)});
+  EXPECT_EQ(OrWithEmpty->reachedEnd(), false);
+
+  EXPECT_THAT(consume(*OrWithEmpty),
+  ElementsAre(0U, 5U, 7U, 10U, 42U, 320U, 9000U));
+}
+
+TEST(DexIndexIterators, OrTwoLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+
+  auto Or = createOr({create(L0), create(L1)});
+
+  EXPECT_EQ(Or->reachedEnd(), false);
+  EXPECT_EQ(Or->peek(), 0U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 4U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 5U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 7U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 10U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 30U);
+  Or->advanceTo(42);
+  EXPECT_EQ(Or->peek(), 42U);
+  Or->advanceTo(300);
+  EXPECT_EQ(Or->peek(), 320U);
+  Or->advanceTo(9000);
+  EXPECT_EQ(Or->peek(), 9000U);
+  Or->advanceTo(9001);
+  EXPECT_EQ(Or->reachedEnd(), true);
+
+  Or = createOr({create(L0), create(L1)});
+
+  EXPECT_THAT(consume(*Or),
+  ElementsAre(0U, 4U, 5U, 7U, 10U, 30U, 42U, 60U, 320U, 9000U));
+}
+
+TEST(DexIndexIterators, OrThreeLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+  const PostingList L2 = {1, 4, 7, 11, 30, 60, 320, 9000};
+
+  auto Or = createOr

[PATCH] D49546: [clangd] Proof-of-concept query iterators for Dex symbol index

2018-07-26 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 157438.
kbobyrev marked 30 inline comments as done.
kbobyrev added a comment.

Addressed a round of comments: cleaned up the code, improved documentation and 
properly introduced such terms like Posting List and Query Tree. Tests are now 
more modular and each specific piece tests a certain part of implementation.

`$ ninja check-clang-tools` is green.


https://reviews.llvm.org/D49546

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/index/dex/Iterator.cpp
  clang-tools-extra/clangd/index/dex/Iterator.h
  clang-tools-extra/unittests/clangd/CMakeLists.txt
  clang-tools-extra/unittests/clangd/DexIndexTests.cpp

Index: clang-tools-extra/unittests/clangd/DexIndexTests.cpp
===
--- /dev/null
+++ clang-tools-extra/unittests/clangd/DexIndexTests.cpp
@@ -0,0 +1,232 @@
+//===--- DexIndexTests.cpp *- C++ -*---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "index/dex/Iterator.h"
+#include "llvm/Support/ScopedPrinter.h"
+#include "llvm/Support/raw_ostream.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+namespace clang {
+namespace clangd {
+namespace dex {
+
+using ::testing::ElementsAre;
+
+TEST(DexIndexIterators, DocumentIterator) {
+  auto DocIterator = create({4, 7, 8, 20, 42, 100});
+
+  EXPECT_EQ(DocIterator->peek(), 4U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advance();
+  EXPECT_EQ(DocIterator->peek(), 7U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advanceTo(20);
+  EXPECT_EQ(DocIterator->peek(), 20U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advanceTo(65);
+  EXPECT_EQ(DocIterator->peek(), 100U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advanceTo(420);
+  EXPECT_EQ(DocIterator->reachedEnd(), true);
+}
+
+TEST(DexIndexIterators, AndWithEmpty) {
+  const PostingList L0;
+  const PostingList L1 = {0, 5, 7, 10, 42, 320, 9000};
+
+  auto AndEmpty = createAnd({create(L0)});
+  EXPECT_EQ(AndEmpty->reachedEnd(), true);
+
+  auto AndWithEmpty = createAnd({create(L0), create(L1)});
+  EXPECT_EQ(AndWithEmpty->reachedEnd(), true);
+
+  EXPECT_THAT(consume(*AndWithEmpty), ElementsAre());
+}
+
+TEST(DexIndexIterators, AndTwoLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+
+  auto And = createAnd({create(L1), create(L0)});
+
+  EXPECT_EQ(And->reachedEnd(), false);
+  EXPECT_THAT(consume(*And), ElementsAre(0U, 7U, 10U, 320U, 9000U));
+
+  And = createAnd({create(L0), create(L1)});
+
+  And->advanceTo(0);
+  EXPECT_EQ(And->peek(), 0U);
+  And->advanceTo(5);
+  EXPECT_EQ(And->peek(), 7U);
+  And->advanceTo(10);
+  EXPECT_EQ(And->peek(), 10U);
+  And->advanceTo(42);
+  EXPECT_EQ(And->peek(), 320U);
+  And->advanceTo(8999);
+  EXPECT_EQ(And->peek(), 9000U);
+  And->advanceTo(9001);
+}
+
+TEST(DexIndexIterators, AndThreeLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+  const PostingList L2 = {1, 4, 7, 11, 30, 60, 320, 9000};
+
+  auto And = createAnd({create(L0), create(L1), create(L2)});
+  EXPECT_EQ(And->peek(), 7U);
+  And->advanceTo(300);
+  EXPECT_EQ(And->peek(), 320U);
+  And->advanceTo(10);
+
+  EXPECT_EQ(And->reachedEnd(), true);
+}
+
+TEST(DexIndexIterators, OrWithEmpty) {
+  const PostingList L0;
+  const PostingList L1 = {0, 5, 7, 10, 42, 320, 9000};
+
+  auto OrEmpty = createOr({create(L0)});
+  EXPECT_EQ(OrEmpty->reachedEnd(), true);
+
+  auto OrWithEmpty = createOr({create(L0), create(L1)});
+  EXPECT_EQ(OrWithEmpty->reachedEnd(), false);
+
+  EXPECT_THAT(consume(*OrWithEmpty),
+  ElementsAre(0U, 5U, 7U, 10U, 42U, 320U, 9000U));
+}
+
+TEST(DexIndexIterators, OrTwoLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+
+  auto Or = createOr({create(L0), create(L1)});
+
+  EXPECT_EQ(Or->reachedEnd(), false);
+  EXPECT_EQ(Or->peek(), 0U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 4U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 5U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 7U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 10U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 30U);
+  Or->advanceTo(42);
+  EXPECT_EQ(Or->peek(), 42U);
+  Or->advanceTo(300);
+  EXPECT_EQ(Or->peek(), 320U);
+  Or->advanceTo(9000);
+  EXPECT_EQ(Or->peek(), 9000U);
+  Or->advanceTo(9001);
+  EXPECT_EQ(Or->reachedEnd(), true);
+
+  Or = createOr({create(L0), create(L1)});
+
+  EXPECT_THAT(consume(*Or),
+  ElementsAre(0U, 4U, 5U, 7U, 10U, 30U, 42U, 60U, 320U, 9000U));
+}
+
+TEST(Dex

[clang-tools-extra] r338015 - [clangd] Give an example for symbol-builder usage

2018-07-26 Thread Kirill Bobyrev via cfe-commits
Author: omtcyfz
Date: Thu Jul 26 02:41:24 2018
New Revision: 338015

URL: http://llvm.org/viewvc/llvm-project?rev=338015&view=rev
Log:
[clangd] Give an example for symbol-builder usage

`global-symbol-builder` help message mentions `-executor=`
option, but doesn't give any example of what the value could be

Assuming the most popular use case to be building the whole project
index, help message should probably give an example of such usage.

Reviewers: ioeric

Subscribers: cfe-commits

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

Modified:

clang-tools-extra/trunk/clangd/global-symbol-builder/GlobalSymbolBuilderMain.cpp

Modified: 
clang-tools-extra/trunk/clangd/global-symbol-builder/GlobalSymbolBuilderMain.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/global-symbol-builder/GlobalSymbolBuilderMain.cpp?rev=338015&r1=338014&r2=338015&view=diff
==
--- 
clang-tools-extra/trunk/clangd/global-symbol-builder/GlobalSymbolBuilderMain.cpp
 (original)
+++ 
clang-tools-extra/trunk/clangd/global-symbol-builder/GlobalSymbolBuilderMain.cpp
 Thu Jul 26 02:41:24 2018
@@ -150,10 +150,23 @@ SymbolSlab mergeSymbols(tooling::ToolRes
 int main(int argc, const char **argv) {
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
-  const char* Overview =
-  "This is an **experimental** tool to generate YAML-format "
-  "project-wide symbols for clangd (global code completion). It would be "
-  "changed and deprecated eventually. Don't use it in production code!";
+  const char *Overview = R"(
+  This is an **experimental** tool to generate YAML-format project-wide symbols
+  for clangd (global code completion). It would be changed and deprecated
+  eventually. Don't use it in production code!
+
+  Example usage for building index for the whole project using CMake compile
+  commands:
+
+  $ global-symbol-builder --executor=all-TUs compile_commands.json > index.yaml
+
+  Example usage for file sequence index without flags:
+
+  $ global-symbol-builder File1.cpp File2.cpp ... FileN.cpp > index.yaml
+
+  Note: only symbols from header files will be collected.
+  )";
+
   auto Executor = clang::tooling::createExecutorFromCommandLineArgs(
   argc, argv, cl::GeneralCategory, Overview);
 


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


[PATCH] D49785: [clangd] Give an example for global-symbol-builder usage

2018-07-26 Thread Kirill Bobyrev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL338015: [clangd] Give an example for symbol-builder usage 
(authored by omtcyfz, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D49785?vs=157263&id=157440#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D49785

Files:
  
clang-tools-extra/trunk/clangd/global-symbol-builder/GlobalSymbolBuilderMain.cpp


Index: 
clang-tools-extra/trunk/clangd/global-symbol-builder/GlobalSymbolBuilderMain.cpp
===
--- 
clang-tools-extra/trunk/clangd/global-symbol-builder/GlobalSymbolBuilderMain.cpp
+++ 
clang-tools-extra/trunk/clangd/global-symbol-builder/GlobalSymbolBuilderMain.cpp
@@ -150,10 +150,23 @@
 int main(int argc, const char **argv) {
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
-  const char* Overview =
-  "This is an **experimental** tool to generate YAML-format "
-  "project-wide symbols for clangd (global code completion). It would be "
-  "changed and deprecated eventually. Don't use it in production code!";
+  const char *Overview = R"(
+  This is an **experimental** tool to generate YAML-format project-wide symbols
+  for clangd (global code completion). It would be changed and deprecated
+  eventually. Don't use it in production code!
+
+  Example usage for building index for the whole project using CMake compile
+  commands:
+
+  $ global-symbol-builder --executor=all-TUs compile_commands.json > index.yaml
+
+  Example usage for file sequence index without flags:
+
+  $ global-symbol-builder File1.cpp File2.cpp ... FileN.cpp > index.yaml
+
+  Note: only symbols from header files will be collected.
+  )";
+
   auto Executor = clang::tooling::createExecutorFromCommandLineArgs(
   argc, argv, cl::GeneralCategory, Overview);
 


Index: clang-tools-extra/trunk/clangd/global-symbol-builder/GlobalSymbolBuilderMain.cpp
===
--- clang-tools-extra/trunk/clangd/global-symbol-builder/GlobalSymbolBuilderMain.cpp
+++ clang-tools-extra/trunk/clangd/global-symbol-builder/GlobalSymbolBuilderMain.cpp
@@ -150,10 +150,23 @@
 int main(int argc, const char **argv) {
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
-  const char* Overview =
-  "This is an **experimental** tool to generate YAML-format "
-  "project-wide symbols for clangd (global code completion). It would be "
-  "changed and deprecated eventually. Don't use it in production code!";
+  const char *Overview = R"(
+  This is an **experimental** tool to generate YAML-format project-wide symbols
+  for clangd (global code completion). It would be changed and deprecated
+  eventually. Don't use it in production code!
+
+  Example usage for building index for the whole project using CMake compile
+  commands:
+
+  $ global-symbol-builder --executor=all-TUs compile_commands.json > index.yaml
+
+  Example usage for file sequence index without flags:
+
+  $ global-symbol-builder File1.cpp File2.cpp ... FileN.cpp > index.yaml
+
+  Note: only symbols from header files will be collected.
+  )";
+
   auto Executor = clang::tooling::createExecutorFromCommandLineArgs(
   argc, argv, cl::GeneralCategory, Overview);
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D49840: [AST] Add MatchFinder::matchSubtree

2018-07-26 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added reviewers: klimek, aprantl, pcc, sbenza, Prazek, dblaikie, 
balazske, xazax.hun.
Herald added subscribers: cfe-commits, dkrupp, rnkovacs.

Add matchSubtree, so we can traverse on a subtree rooted on a specific node.

Currently, we can match **one** node against a matcher, but we will not traverse
into the children (this is MatchFinder::match).
Or we can traverse through the whole tree rooted at the TUDecl (this
is MatchFinder::matchAST).
Note, findAll may provide an alternative, but that will traverse throught the
whole AST, and that has some weaknesses:
https://bugs.llvm.org/show_bug.cgi?id=38318


Repository:
  rC Clang

https://reviews.llvm.org/D49840

Files:
  include/clang/ASTMatchers/ASTMatchFinder.h
  lib/ASTMatchers/ASTMatchFinder.cpp
  unittests/ASTMatchers/ASTMatchersInternalTest.cpp

Index: unittests/ASTMatchers/ASTMatchersInternalTest.cpp
===
--- unittests/ASTMatchers/ASTMatchersInternalTest.cpp
+++ unittests/ASTMatchers/ASTMatchersInternalTest.cpp
@@ -236,5 +236,53 @@
 
 #endif // _WIN32
 
+
+TEST(Matcher, matchSubtree) {
+
+  std::unique_ptr AST =
+  clang::tooling::buildASTFromCode(
+  R"(
+  template 
+  struct X {
+void f() {}
+void g() {}
+  };
+  void foo() {
+  X xc;
+  xc.f();
+  X xi;
+  }
+  )");
+  ASSERT_TRUE(AST.get());
+
+  // To get the "f" FunctionDecl inside the instantiation ...
+  auto FullPattern =
+  functionDecl(hasName("f")
+  // ... we must specify the parent.
+  ,hasParent(classTemplateSpecializationDecl()));
+  auto *FunD = selectFirst(
+  "dontcare", match(FullPattern.bind("dontcare"), AST->getASTContext()));
+
+
+  auto *SpecD = selectFirst(
+  "dontcare", match(classTemplateSpecializationDecl().bind("dontcare"),
+AST->getASTContext()));
+  MatchFinder Finder;
+  struct TestCallback : MatchFinder::MatchCallback {
+FunctionDecl *Node = nullptr;
+void run(const MatchFinder::MatchResult &Result) override {
+  Node =
+  const_cast(Result.Nodes.getNodeAs(""));
+}
+  };
+  TestCallback Cb;
+
+  // With matchSubtree we can traverse through the given instantiation.
+  auto SimplePattern = functionDecl(hasName("f"));
+  Finder.addMatcher(SimplePattern.bind(""), &Cb);
+  Finder.matchSubtree(*SpecD, AST->getASTContext());
+  EXPECT_EQ(FunD, Cb.Node);
+}
+
 } // end namespace ast_matchers
 } // end namespace clang
Index: lib/ASTMatchers/ASTMatchFinder.cpp
===
--- lib/ASTMatchers/ASTMatchFinder.cpp
+++ lib/ASTMatchers/ASTMatchFinder.cpp
@@ -1015,6 +1015,32 @@
   Visitor.match(Node);
 }
 
+void MatchFinder::matchSubtree(const clang::ast_type_traits::DynTypedNode &Node,
+   ASTContext &Context) {
+  internal::MatchASTVisitor Visitor(&Matchers, Options);
+  Visitor.set_active_ast_context(&Context);
+  // FIXME: Improve this with a switch or a visitor pattern.
+  if (auto *N = Node.get()) {
+if (dyn_cast(N))
+  Visitor.onStartOfTranslationUnit();
+Visitor.TraverseDecl(const_cast(N));
+if (dyn_cast(N))
+  Visitor.onEndOfTranslationUnit();
+  } else if (auto *N = Node.get()) {
+Visitor.TraverseStmt(const_cast(N));
+  } else if (auto *N = Node.get()) {
+Visitor.TraverseType(*N);
+  } else if (auto *N = Node.get()) {
+Visitor.TraverseTypeLoc(*N);
+  } else if (auto *N = Node.get()) {
+Visitor.TraverseNestedNameSpecifier(const_cast(N));
+  } else if (auto *N = Node.get()) {
+Visitor.TraverseNestedNameSpecifierLoc(*N);
+  } else if (auto *N = Node.get()) {
+Visitor.TraverseConstructorInitializer(const_cast(N));
+  }
+}
+
 void MatchFinder::matchAST(ASTContext &Context) {
   internal::MatchASTVisitor Visitor(&Matchers, Options);
   Visitor.set_active_ast_context(&Context);
Index: include/clang/ASTMatchers/ASTMatchFinder.h
===
--- include/clang/ASTMatchers/ASTMatchFinder.h
+++ include/clang/ASTMatchers/ASTMatchFinder.h
@@ -189,6 +189,15 @@
  ASTContext &Context);
   /// @}
 
+  /// \brief Finds all matches in the given subtree rooted at \p Node
+  /// @{
+  template  void matchSubtree(const T &Node, ASTContext &Context) {
+matchSubtree(clang::ast_type_traits::DynTypedNode::create(Node), Context);
+  }
+  void matchSubtree(const clang::ast_type_traits::DynTypedNode &Node,
+ASTContext &Context);
+  /// @}
+
   /// Finds all matches in the given AST.
   void matchAST(ASTContext &Context);
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D49725: [OpenCL] Forbid size dependent types used as kernel arguments

2018-07-26 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: lib/Sema/SemaDecl.cpp:8267
 
-  S.Diag(PD->getLocation(), diag::note_within_field_of_type)
-<< PD->getDeclName();
+  S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
+  << OrigRecDecl->getDeclName();

Should this bit go into https://reviews.llvm.org/D49725?


Repository:
  rC Clang

https://reviews.llvm.org/D49725



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


[PATCH] D47196: [Time-report ](2): Recursive timers in Clang

2018-07-26 Thread Andrew V. Tischenko via Phabricator via cfe-commits
avt77 added a comment.

Ping!

efriedma, do you have any other comments/requirements?


https://reviews.llvm.org/D47196



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


[PATCH] D49793: [AArch64] - return address signing

2018-07-26 Thread Luke Cheeseman via Phabricator via cfe-commits
LukeCheeseman updated this revision to Diff 157444.
LukeCheeseman added a comment.

Change codegen option partial to non-leaf to match msign-return-address scope 
values


https://reviews.llvm.org/D49793

Files:
  include/clang/Driver/Options.td
  include/clang/Frontend/CodeGenOptions.def
  include/clang/Frontend/CodeGenOptions.h
  lib/CodeGen/TargetInfo.cpp
  lib/Driver/ToolChains/Clang.cpp
  lib/Frontend/CompilerInvocation.cpp
  test/CodeGen/aarch64-sign-return-address.c

Index: test/CodeGen/aarch64-sign-return-address.c
===
--- /dev/null
+++ test/CodeGen/aarch64-sign-return-address.c
@@ -0,0 +1,14 @@
+// RUN: %clang -target aarch64-arm-none-eabi -S -emit-llvm -o - -msign-return-address=none  %s | FileCheck %s --check-prefix=CHECK-NONE
+// RUN: %clang -target aarch64-arm-none-eabi -S -emit-llvm -o - -msign-return-address=non-leaf %s | FileCheck %s --check-prefix=CHECK-PARTIAL
+// RUN: %clang -target aarch64-arm-none-eabi -S -emit-llvm -o - -msign-return-address=all %s | FileCheck %s --check-prefix=CHECK-ALL
+
+// CHECK-NONE: @foo() #[[ATTR:[0-9]*]]
+// CHECK-NONE-NOT: attributes #[[ATTR]] = { {{.*}} "sign-return-address"={{.*}} }}
+
+// CHECK-PARTIAL: @foo() #[[ATTR:[0-9]*]]
+// CHECK-PARTIAL: attributes #[[ATTR]] = { {{.*}} "sign-return-address"="non-leaf" {{.*}}}
+
+// CHECK-ALL: @foo() #[[ATTR:[0-9]*]]
+// CHECK-ALL: attributes #[[ATTR]] = { {{.*}} "sign-return-address"="all" {{.*}} }
+
+void foo() {}
Index: lib/Frontend/CompilerInvocation.cpp
===
--- lib/Frontend/CompilerInvocation.cpp
+++ lib/Frontend/CompilerInvocation.cpp
@@ -1125,6 +1125,19 @@
 
   Opts.Addrsig = Args.hasArg(OPT_faddrsig);
 
+  if (Arg *A = Args.getLastArg(OPT_msign_return_address)) {
+StringRef SignScope = A->getValue();
+if (SignScope.equals_lower("none"))
+  Opts.setSignReturnAddress(CodeGenOptions::SignReturnAddressScope::None);
+else if (SignScope.equals_lower("all"))
+  Opts.setSignReturnAddress(CodeGenOptions::SignReturnAddressScope::All);
+else if (SignScope.equals_lower("non-leaf"))
+  Opts.setSignReturnAddress(CodeGenOptions::SignReturnAddressScope::NonLeaf);
+else
+  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
+<< A->getValue();
+  }
+
   return Success;
 }
 
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -4073,6 +4073,11 @@
 options::OPT_mno_stack_arg_probe, true))
 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
 
+  if (Arg *A = Args.getLastArg(options::OPT_msign_return_address)) {
+CmdArgs.push_back(
+Args.MakeArgString(Twine("-msign-return-address=") + A->getValue()));
+  }
+
   if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
options::OPT_mno_restrict_it)) {
 if (A->getOption().matches(options::OPT_mrestrict_it)) {
Index: lib/CodeGen/TargetInfo.cpp
===
--- lib/CodeGen/TargetInfo.cpp
+++ lib/CodeGen/TargetInfo.cpp
@@ -4969,6 +4969,23 @@
   }
 
   bool doesReturnSlotInterfereWithArgs() const override { return false; }
+
+  void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
+   CodeGen::CodeGenModule &CGM) const override {
+const FunctionDecl *FD = dyn_cast_or_null(D);
+if (!FD)
+  return;
+llvm::Function *Fn = cast(GV);
+
+auto Kind = CGM.getCodeGenOpts().getSignReturnAddress();
+if (Kind == CodeGenOptions::SignReturnAddressScope::None)
+  return;
+
+Fn->addFnAttr("sign-return-address",
+  Kind == CodeGenOptions::SignReturnAddressScope::All
+  ? "all"
+  : "non-leaf");
+  }
 };
 
 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
Index: include/clang/Frontend/CodeGenOptions.h
===
--- include/clang/Frontend/CodeGenOptions.h
+++ include/clang/Frontend/CodeGenOptions.h
@@ -108,6 +108,12 @@
 Embed_Marker// Embed a marker as a placeholder for bitcode.
   };
 
+  enum SignReturnAddressScope {
+None,   // No signing for any function
+NonLeaf,// Sign the return address of functions that spill LR
+All // Sign the return address of all functions
+  };
+
   /// The code model to use (-mcmodel).
   std::string CodeModel;
 
Index: include/clang/Frontend/CodeGenOptions.def
===
--- include/clang/Frontend/CodeGenOptions.def
+++ include/clang/Frontend/CodeGenOptions.def
@@ -339,6 +339,7 @@
 /// Whether to emit an address-significance table into the object file.
 CODEGENOPT(Addrsig, 1, 0)
 
+ENUM_C

[PATCH] D49840: [AST] Add MatchFinder::matchSubtree

2018-07-26 Thread Manuel Klimek via Phabricator via cfe-commits
klimek added a comment.

Usually we use match(anyOf(node), hasDescendant(node)). Or did I misunderstand 
what you want?


Repository:
  rC Clang

https://reviews.llvm.org/D49840



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


[PATCH] D49546: [clangd] Proof-of-concept query iterators for Dex symbol index

2018-07-26 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 157447.
kbobyrev added a comment.

Rebase on top of https://reviews.llvm.org/rL337901


https://reviews.llvm.org/D49546

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/index/dex/Iterator.cpp
  clang-tools-extra/clangd/index/dex/Iterator.h
  clang-tools-extra/unittests/clangd/DexIndexTests.cpp

Index: clang-tools-extra/unittests/clangd/DexIndexTests.cpp
===
--- clang-tools-extra/unittests/clangd/DexIndexTests.cpp
+++ clang-tools-extra/unittests/clangd/DexIndexTests.cpp
@@ -7,18 +7,229 @@
 //
 //===--===//
 
+#include "index/dex/Iterator.h"
 #include "index/dex/Token.h"
 #include "index/dex/Trigram.h"
+#include "llvm/Support/ScopedPrinter.h"
+#include "llvm/Support/raw_ostream.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
-
 #include 
 #include 
 
 namespace clang {
 namespace clangd {
 namespace dex {
 
+using ::testing::ElementsAre;
+
+TEST(DexIndexIterators, DocumentIterator) {
+  auto DocIterator = create({4, 7, 8, 20, 42, 100});
+
+  EXPECT_EQ(DocIterator->peek(), 4U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advance();
+  EXPECT_EQ(DocIterator->peek(), 7U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advanceTo(20);
+  EXPECT_EQ(DocIterator->peek(), 20U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advanceTo(65);
+  EXPECT_EQ(DocIterator->peek(), 100U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advanceTo(420);
+  EXPECT_EQ(DocIterator->reachedEnd(), true);
+}
+
+TEST(DexIndexIterators, AndWithEmpty) {
+  const PostingList L0;
+  const PostingList L1 = {0, 5, 7, 10, 42, 320, 9000};
+
+  auto AndEmpty = createAnd({create(L0)});
+  EXPECT_EQ(AndEmpty->reachedEnd(), true);
+
+  auto AndWithEmpty = createAnd({create(L0), create(L1)});
+  EXPECT_EQ(AndWithEmpty->reachedEnd(), true);
+
+  EXPECT_THAT(consume(*AndWithEmpty), ElementsAre());
+}
+
+TEST(DexIndexIterators, AndTwoLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+
+  auto And = createAnd({create(L1), create(L0)});
+
+  EXPECT_EQ(And->reachedEnd(), false);
+  EXPECT_THAT(consume(*And), ElementsAre(0U, 7U, 10U, 320U, 9000U));
+
+  And = createAnd({create(L0), create(L1)});
+
+  And->advanceTo(0);
+  EXPECT_EQ(And->peek(), 0U);
+  And->advanceTo(5);
+  EXPECT_EQ(And->peek(), 7U);
+  And->advanceTo(10);
+  EXPECT_EQ(And->peek(), 10U);
+  And->advanceTo(42);
+  EXPECT_EQ(And->peek(), 320U);
+  And->advanceTo(8999);
+  EXPECT_EQ(And->peek(), 9000U);
+  And->advanceTo(9001);
+}
+
+TEST(DexIndexIterators, AndThreeLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+  const PostingList L2 = {1, 4, 7, 11, 30, 60, 320, 9000};
+
+  auto And = createAnd({create(L0), create(L1), create(L2)});
+  EXPECT_EQ(And->peek(), 7U);
+  And->advanceTo(300);
+  EXPECT_EQ(And->peek(), 320U);
+  And->advanceTo(10);
+
+  EXPECT_EQ(And->reachedEnd(), true);
+}
+
+TEST(DexIndexIterators, OrWithEmpty) {
+  const PostingList L0;
+  const PostingList L1 = {0, 5, 7, 10, 42, 320, 9000};
+
+  auto OrEmpty = createOr({create(L0)});
+  EXPECT_EQ(OrEmpty->reachedEnd(), true);
+
+  auto OrWithEmpty = createOr({create(L0), create(L1)});
+  EXPECT_EQ(OrWithEmpty->reachedEnd(), false);
+
+  EXPECT_THAT(consume(*OrWithEmpty),
+  ElementsAre(0U, 5U, 7U, 10U, 42U, 320U, 9000U));
+}
+
+TEST(DexIndexIterators, OrTwoLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+
+  auto Or = createOr({create(L0), create(L1)});
+
+  EXPECT_EQ(Or->reachedEnd(), false);
+  EXPECT_EQ(Or->peek(), 0U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 4U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 5U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 7U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 10U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 30U);
+  Or->advanceTo(42);
+  EXPECT_EQ(Or->peek(), 42U);
+  Or->advanceTo(300);
+  EXPECT_EQ(Or->peek(), 320U);
+  Or->advanceTo(9000);
+  EXPECT_EQ(Or->peek(), 9000U);
+  Or->advanceTo(9001);
+  EXPECT_EQ(Or->reachedEnd(), true);
+
+  Or = createOr({create(L0), create(L1)});
+
+  EXPECT_THAT(consume(*Or),
+  ElementsAre(0U, 4U, 5U, 7U, 10U, 30U, 42U, 60U, 320U, 9000U));
+}
+
+TEST(DexIndexIterators, OrThreeLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+  const PostingList L2 = {1, 4, 7, 11, 30, 60, 320, 9000};
+
+  auto Or = createOr({create(L0), create(L1), create(L2)});
+
+  EXPECT_EQ(Or->reachedEnd(), false);
+  EXPECT_EQ(Or->peek(), 0U);
+
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 1U);
+
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 4U);
+
+  Or->advanceTo(7);

[PATCH] D49546: [clangd] Proof-of-concept query iterators for Dex symbol index

2018-07-26 Thread Eric Liu via Phabricator via cfe-commits
ioeric accepted this revision.
ioeric added a comment.
This revision is now accepted and ready to land.

lg! just a few nits.




Comment at: clang-tools-extra/clangd/index/dex/Iterator.cpp:109
+private:
+  /// Restores class invariants: each child should point to the same element.
+  void sync() {

This is the post-condition, not a precondition right?

To be clearer, ` ... each child will point to the same element after sync`





Comment at: clang-tools-extra/clangd/index/dex/Iterator.cpp:162
+
+  /// Returns false if any child is not exhausted, true otherwise.
+  bool reachedEnd() const override {

Or `Returns true if all children are exhausted.` No need for otherwise if it's 
trivial.



Comment at: clang-tools-extra/clangd/index/dex/Iterator.h:12
+// symbol, such as high fuzzy matching score, scope, type etc. The lists of all
+// symbols matching some criteria (e.g. belonging to "clang::clangd" scope) are
+// expressed in a form of Search Tokens which are stored in the inverted index.

nit: Just to match the actual implementation, use "clang::clangd::" to avoid 
confusion.



Comment at: clang-tools-extra/clangd/index/dex/Iterator.h:15
+// Inverted index maps these tokens to the posting lists - sorted (e.g. by
+// number of references) sequences of symbol IDs matching the token, e.g. scope
+// token "clangd::clangd" is mapped to the list of IDs of all symbols which are

"number of references" is too specific. Maybe "by symbol quality"?



Comment at: clang-tools-extra/clangd/index/dex/Iterator.h:25
+// because it allows receiving a certain number of the most valuable items 
(e.g.
+// symbols with most number of references if that is the sorting key in the
+// first place) without processing all items with requested qualities (this

Again, replace number of references with quality for generalization.



Comment at: clang-tools-extra/clangd/index/dex/Iterator.h:26
+// symbols with most number of references if that is the sorting key in the
+// first place) without processing all items with requested qualities (this
+// might not be computationally effective if search request is not very

with the requested *properties*?



Comment at: clang-tools-extra/clangd/index/dex/Iterator.h:61
+/// to be extensible in order to support multiple types of iterators, some of
+/// which are not yet introduced.
+class Iterator {

nit: drop "some of which are not yet introduced" as it's not relevant to the 
interface itself.



Comment at: clang-tools-extra/clangd/index/dex/Iterator.h:72
+  /// crash, false otherwise.
+  virtual bool reachedEnd() const = 0;
+  /// Moves to next valid DocID. If it doesn't exist, the iterator is exhausted

Just "return true if ...". 

There is no need to mention `advance()` and `advanceTo()` here as they are 
already covered in their own documentation. 



Comment at: clang-tools-extra/clangd/index/dex/Iterator.h:76
+  ///
+  /// Note: calls to advance() would trigger assertion (if enabled) or crash if
+  /// reachedEnd().

Just `reachedEnd() must be false.` which usually implies assertion. Same 
elsewhere.



Comment at: clang-tools-extra/clangd/index/dex/Iterator.h:127
+
+/// Allows calling createAnd() with {} braces by constructing an array of
+/// r-values rather than an initializer list.

An example of usage would be simpler and easier to understand here. Same below.

Example:
`This allows createAnd({create(...), create(...)})`


https://reviews.llvm.org/D49546



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


[PATCH] D48903: [VirtualFileSystem] InMemoryFileSystem::status: Return a Status with the requested name

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

Many thanks! Great cleanup. Just a few nits and we're good to go




Comment at: lib/Basic/VirtualFileSystem.cpp:475
   InMemoryNodeKind Kind;
+  Status Stat;
+

NIT: maybe keep the order of members the same to keep the patch more focused? 
Unless there's a good reason to swap them.



Comment at: lib/Basic/VirtualFileSystem.cpp:528
   InMemoryFile &Node;
 
+  /// The name to use when returning a Status for this file.

NIT: remove this blank line to follow the code style of the file more closely?



Comment at: lib/Basic/VirtualFileSystem.cpp:770
+  llvm::sys::path::append(Path, I->second->getFileName());
+  CurrentEntry = I->second->getStatus(Path.str());
+} else {

NIT: `Path.str()` can be replaced with `Path` (SmallString is convertible to 
StringRef)



Comment at: unittests/Basic/VirtualFileSystemTest.cpp:155
+
+auto ReplaceBackslashes = [](std::string S) {
+  std::replace(S.begin(), S.end(), '\\', '/');

Maybe replace lambda with a funciton?



Comment at: unittests/Basic/VirtualFileSystemTest.cpp:155
+
+auto ReplaceBackslashes = [](std::string S) {
+  std::replace(S.begin(), S.end(), '\\', '/');

ilya-biryukov wrote:
> Maybe replace lambda with a funciton?
Could the name mention the expected result? E.g. `getUnixPath()` or something 
similar



Comment at: unittests/Basic/VirtualFileSystemTest.cpp:156
+auto ReplaceBackslashes = [](std::string S) {
+  std::replace(S.begin(), S.end(), '\\', '/');
+  return S;

Maybe use `llvm::sys::path::native(S, style::posix)`?



Comment at: unittests/Basic/VirtualFileSystemTest.cpp:790
   ASSERT_FALSE(EC);
-  ASSERT_EQ("/b/c", I->getName());
+  ASSERT_EQ("/b/c", ReplaceBackslashes(I->getName()));
   I.increment(EC);

Maybe add a comment about windows and the path we get there?


Repository:
  rC Clang

https://reviews.llvm.org/D48903



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


[PATCH] D49793: [AArch64] - return address signing

2018-07-26 Thread Luke Cheeseman via Phabricator via cfe-commits
LukeCheeseman added inline comments.



Comment at: include/clang/Frontend/CodeGenOptions.h:114
+Partial,// Sign the return address of functions that spill LR
+All // Sign the return address of all functions
+  };

kcc wrote:
> what's the purpose of signing LR if it is not spilled? 
Assuming you are in a context where you have managed to gain control of the 
flow of execution. If you don't sign functions that spill LR then those 
functions become good candidates for finding gadgets as now execution can start 
from any point in that function.


https://reviews.llvm.org/D49793



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


[PATCH] D49546: [clangd] Proof-of-concept query iterators for Dex symbol index

2018-07-26 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 157450.
kbobyrev marked 10 inline comments as done.
kbobyrev added a comment.

Address post-lg round of comments.


https://reviews.llvm.org/D49546

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/index/dex/Iterator.cpp
  clang-tools-extra/clangd/index/dex/Iterator.h
  clang-tools-extra/unittests/clangd/DexIndexTests.cpp

Index: clang-tools-extra/unittests/clangd/DexIndexTests.cpp
===
--- clang-tools-extra/unittests/clangd/DexIndexTests.cpp
+++ clang-tools-extra/unittests/clangd/DexIndexTests.cpp
@@ -7,18 +7,229 @@
 //
 //===--===//
 
+#include "index/dex/Iterator.h"
 #include "index/dex/Token.h"
 #include "index/dex/Trigram.h"
+#include "llvm/Support/ScopedPrinter.h"
+#include "llvm/Support/raw_ostream.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
-
 #include 
 #include 
 
 namespace clang {
 namespace clangd {
 namespace dex {
 
+using ::testing::ElementsAre;
+
+TEST(DexIndexIterators, DocumentIterator) {
+  auto DocIterator = create({4, 7, 8, 20, 42, 100});
+
+  EXPECT_EQ(DocIterator->peek(), 4U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advance();
+  EXPECT_EQ(DocIterator->peek(), 7U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advanceTo(20);
+  EXPECT_EQ(DocIterator->peek(), 20U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advanceTo(65);
+  EXPECT_EQ(DocIterator->peek(), 100U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advanceTo(420);
+  EXPECT_EQ(DocIterator->reachedEnd(), true);
+}
+
+TEST(DexIndexIterators, AndWithEmpty) {
+  const PostingList L0;
+  const PostingList L1 = {0, 5, 7, 10, 42, 320, 9000};
+
+  auto AndEmpty = createAnd({create(L0)});
+  EXPECT_EQ(AndEmpty->reachedEnd(), true);
+
+  auto AndWithEmpty = createAnd({create(L0), create(L1)});
+  EXPECT_EQ(AndWithEmpty->reachedEnd(), true);
+
+  EXPECT_THAT(consume(*AndWithEmpty), ElementsAre());
+}
+
+TEST(DexIndexIterators, AndTwoLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+
+  auto And = createAnd({create(L1), create(L0)});
+
+  EXPECT_EQ(And->reachedEnd(), false);
+  EXPECT_THAT(consume(*And), ElementsAre(0U, 7U, 10U, 320U, 9000U));
+
+  And = createAnd({create(L0), create(L1)});
+
+  And->advanceTo(0);
+  EXPECT_EQ(And->peek(), 0U);
+  And->advanceTo(5);
+  EXPECT_EQ(And->peek(), 7U);
+  And->advanceTo(10);
+  EXPECT_EQ(And->peek(), 10U);
+  And->advanceTo(42);
+  EXPECT_EQ(And->peek(), 320U);
+  And->advanceTo(8999);
+  EXPECT_EQ(And->peek(), 9000U);
+  And->advanceTo(9001);
+}
+
+TEST(DexIndexIterators, AndThreeLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+  const PostingList L2 = {1, 4, 7, 11, 30, 60, 320, 9000};
+
+  auto And = createAnd({create(L0), create(L1), create(L2)});
+  EXPECT_EQ(And->peek(), 7U);
+  And->advanceTo(300);
+  EXPECT_EQ(And->peek(), 320U);
+  And->advanceTo(10);
+
+  EXPECT_EQ(And->reachedEnd(), true);
+}
+
+TEST(DexIndexIterators, OrWithEmpty) {
+  const PostingList L0;
+  const PostingList L1 = {0, 5, 7, 10, 42, 320, 9000};
+
+  auto OrEmpty = createOr({create(L0)});
+  EXPECT_EQ(OrEmpty->reachedEnd(), true);
+
+  auto OrWithEmpty = createOr({create(L0), create(L1)});
+  EXPECT_EQ(OrWithEmpty->reachedEnd(), false);
+
+  EXPECT_THAT(consume(*OrWithEmpty),
+  ElementsAre(0U, 5U, 7U, 10U, 42U, 320U, 9000U));
+}
+
+TEST(DexIndexIterators, OrTwoLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+
+  auto Or = createOr({create(L0), create(L1)});
+
+  EXPECT_EQ(Or->reachedEnd(), false);
+  EXPECT_EQ(Or->peek(), 0U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 4U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 5U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 7U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 10U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 30U);
+  Or->advanceTo(42);
+  EXPECT_EQ(Or->peek(), 42U);
+  Or->advanceTo(300);
+  EXPECT_EQ(Or->peek(), 320U);
+  Or->advanceTo(9000);
+  EXPECT_EQ(Or->peek(), 9000U);
+  Or->advanceTo(9001);
+  EXPECT_EQ(Or->reachedEnd(), true);
+
+  Or = createOr({create(L0), create(L1)});
+
+  EXPECT_THAT(consume(*Or),
+  ElementsAre(0U, 4U, 5U, 7U, 10U, 30U, 42U, 60U, 320U, 9000U));
+}
+
+TEST(DexIndexIterators, OrThreeLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+  const PostingList L2 = {1, 4, 7, 11, 30, 60, 320, 9000};
+
+  auto Or = createOr({create(L0), create(L1), create(L2)});
+
+  EXPECT_EQ(Or->reachedEnd(), false);
+  EXPECT_EQ(Or->peek(), 0U);
+
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 1U);
+
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 

[PATCH] D49546: [clangd] Proof-of-concept query iterators for Dex symbol index

2018-07-26 Thread Kirill Bobyrev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE338017: [clangd] Proof-of-concept query iterators for Dex 
symbol index (authored by omtcyfz, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D49546?vs=157450&id=157451#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49546

Files:
  clangd/CMakeLists.txt
  clangd/index/dex/Iterator.cpp
  clangd/index/dex/Iterator.h
  unittests/clangd/DexIndexTests.cpp

Index: unittests/clangd/DexIndexTests.cpp
===
--- unittests/clangd/DexIndexTests.cpp
+++ unittests/clangd/DexIndexTests.cpp
@@ -7,18 +7,229 @@
 //
 //===--===//
 
+#include "index/dex/Iterator.h"
 #include "index/dex/Token.h"
 #include "index/dex/Trigram.h"
+#include "llvm/Support/ScopedPrinter.h"
+#include "llvm/Support/raw_ostream.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
-
 #include 
 #include 
 
 namespace clang {
 namespace clangd {
 namespace dex {
 
+using ::testing::ElementsAre;
+
+TEST(DexIndexIterators, DocumentIterator) {
+  auto DocIterator = create({4, 7, 8, 20, 42, 100});
+
+  EXPECT_EQ(DocIterator->peek(), 4U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advance();
+  EXPECT_EQ(DocIterator->peek(), 7U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advanceTo(20);
+  EXPECT_EQ(DocIterator->peek(), 20U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advanceTo(65);
+  EXPECT_EQ(DocIterator->peek(), 100U);
+  EXPECT_EQ(DocIterator->reachedEnd(), false);
+
+  DocIterator->advanceTo(420);
+  EXPECT_EQ(DocIterator->reachedEnd(), true);
+}
+
+TEST(DexIndexIterators, AndWithEmpty) {
+  const PostingList L0;
+  const PostingList L1 = {0, 5, 7, 10, 42, 320, 9000};
+
+  auto AndEmpty = createAnd({create(L0)});
+  EXPECT_EQ(AndEmpty->reachedEnd(), true);
+
+  auto AndWithEmpty = createAnd({create(L0), create(L1)});
+  EXPECT_EQ(AndWithEmpty->reachedEnd(), true);
+
+  EXPECT_THAT(consume(*AndWithEmpty), ElementsAre());
+}
+
+TEST(DexIndexIterators, AndTwoLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+
+  auto And = createAnd({create(L1), create(L0)});
+
+  EXPECT_EQ(And->reachedEnd(), false);
+  EXPECT_THAT(consume(*And), ElementsAre(0U, 7U, 10U, 320U, 9000U));
+
+  And = createAnd({create(L0), create(L1)});
+
+  And->advanceTo(0);
+  EXPECT_EQ(And->peek(), 0U);
+  And->advanceTo(5);
+  EXPECT_EQ(And->peek(), 7U);
+  And->advanceTo(10);
+  EXPECT_EQ(And->peek(), 10U);
+  And->advanceTo(42);
+  EXPECT_EQ(And->peek(), 320U);
+  And->advanceTo(8999);
+  EXPECT_EQ(And->peek(), 9000U);
+  And->advanceTo(9001);
+}
+
+TEST(DexIndexIterators, AndThreeLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+  const PostingList L2 = {1, 4, 7, 11, 30, 60, 320, 9000};
+
+  auto And = createAnd({create(L0), create(L1), create(L2)});
+  EXPECT_EQ(And->peek(), 7U);
+  And->advanceTo(300);
+  EXPECT_EQ(And->peek(), 320U);
+  And->advanceTo(10);
+
+  EXPECT_EQ(And->reachedEnd(), true);
+}
+
+TEST(DexIndexIterators, OrWithEmpty) {
+  const PostingList L0;
+  const PostingList L1 = {0, 5, 7, 10, 42, 320, 9000};
+
+  auto OrEmpty = createOr({create(L0)});
+  EXPECT_EQ(OrEmpty->reachedEnd(), true);
+
+  auto OrWithEmpty = createOr({create(L0), create(L1)});
+  EXPECT_EQ(OrWithEmpty->reachedEnd(), false);
+
+  EXPECT_THAT(consume(*OrWithEmpty),
+  ElementsAre(0U, 5U, 7U, 10U, 42U, 320U, 9000U));
+}
+
+TEST(DexIndexIterators, OrTwoLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+
+  auto Or = createOr({create(L0), create(L1)});
+
+  EXPECT_EQ(Or->reachedEnd(), false);
+  EXPECT_EQ(Or->peek(), 0U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 4U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 5U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 7U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 10U);
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 30U);
+  Or->advanceTo(42);
+  EXPECT_EQ(Or->peek(), 42U);
+  Or->advanceTo(300);
+  EXPECT_EQ(Or->peek(), 320U);
+  Or->advanceTo(9000);
+  EXPECT_EQ(Or->peek(), 9000U);
+  Or->advanceTo(9001);
+  EXPECT_EQ(Or->reachedEnd(), true);
+
+  Or = createOr({create(L0), create(L1)});
+
+  EXPECT_THAT(consume(*Or),
+  ElementsAre(0U, 4U, 5U, 7U, 10U, 30U, 42U, 60U, 320U, 9000U));
+}
+
+TEST(DexIndexIterators, OrThreeLists) {
+  const PostingList L0 = {0, 5, 7, 10, 42, 320, 9000};
+  const PostingList L1 = {0, 4, 7, 10, 30, 60, 320, 9000};
+  const PostingList L2 = {1, 4, 7, 11, 30, 60, 320, 9000};
+
+  auto Or = createOr({create(L0), create(L1), create(L2)});
+
+  EXPECT_EQ(Or->reachedEnd(), false);
+  EXPECT_EQ(Or->peek(), 0U);
+
+  Or->advance();
+  EXPECT_EQ(Or->peek(), 1U)

[clang-tools-extra] r338017 - [clangd] Proof-of-concept query iterators for Dex symbol index

2018-07-26 Thread Kirill Bobyrev via cfe-commits
Author: omtcyfz
Date: Thu Jul 26 03:42:31 2018
New Revision: 338017

URL: http://llvm.org/viewvc/llvm-project?rev=338017&view=rev
Log:
[clangd] Proof-of-concept query iterators for Dex symbol index

This patch introduces three essential types of query iterators:
`DocumentIterator`, `AndIterator`, `OrIterator`. It provides a
convenient API for query tree generation and serves as a building block
for the next generation symbol index - Dex. Currently, many
optimizations are missed to improve code readability and to serve as the
reference implementation. Potential improvements are briefly mentioned
in `FIXME`s and will be addressed in the following patches.

Dex RFC in the mailing list:
http://lists.llvm.org/pipermail/clangd-dev/2018-July/22.html

Iterators, their applications and potential extensions are explained in
detail in the design proposal:
https://docs.google.com/document/d/1C-A6PGT6TynyaX4PXyExNMiGmJ2jL1UwV91Kyx11gOI/edit#heading=h.903u1zon9nkj

Reviewers: ioeric, sammccall, ilya-biryukov

Subscribers: cfe-commits, klimek, jfb, mgrang, mgorny, MaskRay, jkorous,
arphaman

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

Added:
clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp
clang-tools-extra/trunk/clangd/index/dex/Iterator.h
Modified:
clang-tools-extra/trunk/clangd/CMakeLists.txt
clang-tools-extra/trunk/unittests/clangd/DexIndexTests.cpp

Modified: clang-tools-extra/trunk/clangd/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CMakeLists.txt?rev=338017&r1=338016&r2=338017&view=diff
==
--- clang-tools-extra/trunk/clangd/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clangd/CMakeLists.txt Thu Jul 26 03:42:31 2018
@@ -43,6 +43,7 @@ add_clang_library(clangDaemon
   index/SymbolCollector.cpp
   index/SymbolYAML.cpp
 
+  index/dex/Iterator.cpp
   index/dex/Trigram.cpp
 
   LINK_LIBS

Added: 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=338017&view=auto
==
--- clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp (added)
+++ clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp Thu Jul 26 03:42:31 
2018
@@ -0,0 +1,244 @@
+//===--- Iterator.cpp - Query Symbol Retrieval --*- C++ 
-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "Iterator.h"
+#include 
+#include 
+#include 
+
+namespace clang {
+namespace clangd {
+namespace dex {
+
+namespace {
+
+/// Implements Iterator over a PostingList. DocumentIterator is the most basic
+/// iterator: it doesn't have any children (hence it is the leaf of iterator
+/// tree) and is simply a wrapper around PostingList::const_iterator.
+class DocumentIterator : public Iterator {
+public:
+  DocumentIterator(PostingListRef Documents)
+  : Documents(Documents), Index(std::begin(Documents)) {}
+
+  bool reachedEnd() const override { return Index == std::end(Documents); }
+
+  /// Advances cursor to the next item.
+  void advance() override {
+assert(!reachedEnd() && "DocumentIterator can't advance at the end.");
+++Index;
+  }
+
+  /// Applies binary search to advance cursor to the next item with DocID equal
+  /// or higher than the given one.
+  void advanceTo(DocID ID) override {
+assert(!reachedEnd() && "DocumentIterator can't advance at the end.");
+Index = std::lower_bound(Index, std::end(Documents), ID);
+  }
+
+  DocID peek() const override {
+assert(!reachedEnd() && "DocumentIterator can't call peek() at the end.");
+return *Index;
+  }
+
+  llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
+OS << '[';
+auto Separator = "";
+for (const auto &ID : Documents) {
+  OS << Separator << ID;
+  Separator = ", ";
+}
+OS << ']';
+return OS;
+  }
+
+private:
+  PostingListRef Documents;
+  PostingListRef::const_iterator Index;
+};
+
+/// Implements Iterator over the intersection of other iterators.
+///
+/// AndIterator iterates through common items among all children. It becomes
+/// exhausted as soon as any child becomes exhausted. After each mutation, the
+/// iterator restores the invariant: all children must point to the same item.
+class AndIterator : public Iterator {
+public:
+  AndIterator(std::vector> AllChildren)
+  : Children(std::move(AllChildren)) {
+assert(!Children.empty() && "AndIterator should have at least one child.");
+// Establish invariants.
+sync();
+  }
+
+  bool reachedEnd() const override { return ReachedEnd; }
+
+  /// Advances all children to the next common item.
+  void advance

[PATCH] D49840: [AST] Add MatchFinder::matchSubtree

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

> Usually we use match(anyOf(node), hasDescendant(node)). Or did I 
> misunderstand what you want?

My understanding is that, the free function template `match` uses 
`MatchFinder::matchAST`, which will start the traverse from the 
TranslationUnitDecl.
And there is no option to pick a specific node and specify that as the root of 
the traverse. I'd like an option to be able to start the traverse from a 
specific node, if it makes sense.


Repository:
  rC Clang

https://reviews.llvm.org/D49840



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


[PATCH] D49736: [Basic] Emit warning flag suggestion only in case there's existing flag *similar* to the unknown one

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

I like that idea! It looks like it's living in a wrong place anyway as it 
doesn't need access to any of implementation details (private members) of 
DiagnosticID. I would still like to preserve it as a function so this block of 
code has clear semantics and interface. 
How about I refactor it to a static free function in Warnings.cpp?


Repository:
  rC Clang

https://reviews.llvm.org/D49736



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


[PATCH] D49797: [clang-format] Indent after breaking Javadoc annotated line

2018-07-26 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 157452.
krasimir added a comment.

- Update tests


Repository:
  rC Clang

https://reviews.llvm.org/D49797

Files:
  lib/Format/BreakableToken.cpp
  lib/Format/BreakableToken.h
  lib/Format/ContinuationIndenter.cpp
  unittests/Format/FormatTestComments.cpp
  unittests/Format/FormatTestJS.cpp

Index: unittests/Format/FormatTestJS.cpp
===
--- unittests/Format/FormatTestJS.cpp
+++ unittests/Format/FormatTestJS.cpp
@@ -2058,8 +2058,8 @@
   verifyFormat(
   "/**\n"
   " * @param This is a\n"
-  " * long comment but\n"
-  " * no type\n"
+  " * long comment\n"
+  " * but no type\n"
   " */",
   "/**\n"
   " * @param This is a long comment but no type\n"
Index: unittests/Format/FormatTestComments.cpp
===
--- unittests/Format/FormatTestComments.cpp
+++ unittests/Format/FormatTestComments.cpp
@@ -3105,6 +3105,87 @@
 // clang-format on
 }
 
+TEST_F(FormatTestComments, IndentsLongJavadocAnnotatedLines) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_Java);
+  Style.ColumnLimit = 60;
+  FormatStyle Style20 = getGoogleStyle(FormatStyle::LK_Java);
+  Style20.ColumnLimit = 20;
+  EXPECT_EQ(
+  "/**\n"
+  " * @param x long long long long long long long long long\n"
+  " * long\n"
+  " */\n",
+  format("/**\n"
+ " * @param x long long long long long long long long long long\n"
+ " */\n",
+ Style));
+  EXPECT_EQ("/**\n"
+" * @param x long long long long long long long long long\n"
+" * long long long long long long long long long long\n"
+" */\n",
+format("/**\n"
+   " * @param x long long long long long long long long long "
+   "long long long long long long long long long long\n"
+   " */\n",
+   Style));
+  EXPECT_EQ("/**\n"
+" * @param x long long long long long long long long long\n"
+" * long long long long long long long long long long\n"
+" * long\n"
+" */\n",
+format("/**\n"
+   " * @param x long long long long long long long long long "
+   "long long long long long long long long long long long\n"
+   " */\n",
+   Style));
+  EXPECT_EQ(
+  "/**\n"
+  " * Sentence that\n"
+  " * should be broken.\n"
+  " * @param short\n"
+  " * keep indentation\n"
+  " */\n", format(
+  "/**\n"
+  " * Sentence that should be broken.\n"
+  " * @param short\n"
+  " * keep indentation\n"
+  " */\n", Style20));
+
+  EXPECT_EQ("/**\n"
+" * @param l1 long1\n"
+" * to break\n"
+" * @param l2 long2\n"
+" * to break\n"
+" */\n",
+format("/**\n"
+   " * @param l1 long1 to break\n"
+   " * @param l2 long2 to break\n"
+   " */\n",
+   Style20));
+
+  EXPECT_EQ("/**\n"
+" * @param xx to\n"
+" * break\n"
+" * no reflow\n"
+" */\n",
+format("/**\n"
+   " * @param xx to break\n"
+   " * no reflow\n"
+   " */\n",
+   Style20));
+
+  EXPECT_EQ("/**\n"
+" * @param xx to\n"
+" * break yes\n"
+" * reflow\n"
+" */\n",
+format("/**\n"
+   " * @param xx to break\n"
+   " * yes reflow\n"
+   " */\n",
+   Style20));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: lib/Format/ContinuationIndenter.cpp
===
--- lib/Format/ContinuationIndenter.cpp
+++ lib/Format/ContinuationIndenter.cpp
@@ -1782,6 +1782,7 @@
   if (!DryRun)
 Token->adaptStartOfLine(0, Whitespaces);
 
+  unsigned ContentIndent = 0;
   unsigned Penalty = 0;
   LLVM_DEBUG(llvm::dbgs() << "Breaking protruding token at column "
   << StartColumn << ".\n");
@@ -1903,8 +1904,15 @@
 }
   }
   LLVM_DEBUG(llvm::dbgs() << "Breaking...\n");
-  ContentStartColumn =
-  Token->getContentStartColumn(LineIndex, /*Break=*/true);
+  // Update the ContentIndent only if the current line was not reflown with
+  // the previous line, since in that case the previous line should still
+  // determine the ContentIndent.
+  if (!Reflow) ContentIndent = Token->getContentIndent(LineIndex);
+  LLVM_DEBUG(llvm::dbgs()
+ << "ContentIndent: " << ContentIndent << "\n");
+  ContentStartColumn = ContentIndent + Token->getContentStartColumn(
+  

[PATCH] D49844: [AST] Add a isActuallyImplicitCast() helper to the CastExpr class.

2018-07-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri created this revision.
lebedev.ri added reviewers: rsmith, erichkeane, rjmccall, aaron.ballman.
Herald added a subscriber: cfe-commits.
lebedev.ri added a dependency: D49838: [AST] Sink 'part of explicit cast' down 
into ImplicitCastExpr.

This is mostly factored out of https://reviews.llvm.org/D48958.
As of https://reviews.llvm.org/D49838, `ImplicitCastExpr` can tell whether it 
is a part of ExplicitCastExpr group.
But given just the `CastExpr`, one still has to check that it is not 
`ExplicitCastExpr` itself,
before using `ImplicitCastExpr::getIsPartOfExplicitCast()`.
Thus, it makes sense to factor out it into a helper function in `CastExpr` 
baseclass.

This indeed does not have tests. Would be happy to add those, if needed and 
told how to write those.


Repository:
  rC Clang

https://reviews.llvm.org/D49844

Files:
  include/clang/AST/Expr.h


Index: include/clang/AST/Expr.h
===
--- include/clang/AST/Expr.h
+++ include/clang/AST/Expr.h
@@ -2850,6 +2850,15 @@
 return const_cast(this)->getSubExprAsWritten();
   }
 
+  /// There are two global types of casts - implicit and explicit.
+  /// The Explicit cast is something that was directly written in the source
+  /// code. And the implicit cast is expected to be the opposite.
+  /// But in AST, some explicit casts are represented as ExplicitCastExpr plus
+  /// one or more immediate ImplicitCastExpr (i.e. with nothing inbetween).
+  /// This function returns false if this cast is either an ExplicitCastExpr
+  /// itself, or it is a part of the ExplicitCastExpr group.
+  bool isActuallyImplicitCast() const;
+
   /// If this cast applies a user-defined conversion, retrieve the conversion
   /// function that it invokes.
   NamedDecl *getConversionFunction() const;
@@ -3011,6 +3020,14 @@
   }
 };
 
+inline bool CastExpr::isActuallyImplicitCast() const {
+  // If this is an Implicit cast, is it *NOT* a part of Explicit cast group?
+  if (auto *IC = dyn_cast(this))
+return !IC->getIsPartOfExplicitCast();
+  assert(isa(this) && "it has to be Explicit cast then.");
+  return false; // Explicit cast is clearly not an Implicit cast.
+}
+
 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
 /// cast in C++ (C++ [expr.cast]), which uses the syntax
 /// (Type)expr. For example: @c (int)f.


Index: include/clang/AST/Expr.h
===
--- include/clang/AST/Expr.h
+++ include/clang/AST/Expr.h
@@ -2850,6 +2850,15 @@
 return const_cast(this)->getSubExprAsWritten();
   }
 
+  /// There are two global types of casts - implicit and explicit.
+  /// The Explicit cast is something that was directly written in the source
+  /// code. And the implicit cast is expected to be the opposite.
+  /// But in AST, some explicit casts are represented as ExplicitCastExpr plus
+  /// one or more immediate ImplicitCastExpr (i.e. with nothing inbetween).
+  /// This function returns false if this cast is either an ExplicitCastExpr
+  /// itself, or it is a part of the ExplicitCastExpr group.
+  bool isActuallyImplicitCast() const;
+
   /// If this cast applies a user-defined conversion, retrieve the conversion
   /// function that it invokes.
   NamedDecl *getConversionFunction() const;
@@ -3011,6 +3020,14 @@
   }
 };
 
+inline bool CastExpr::isActuallyImplicitCast() const {
+  // If this is an Implicit cast, is it *NOT* a part of Explicit cast group?
+  if (auto *IC = dyn_cast(this))
+return !IC->getIsPartOfExplicitCast();
+  assert(isa(this) && "it has to be Explicit cast then.");
+  return false; // Explicit cast is clearly not an Implicit cast.
+}
+
 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
 /// cast in C++ (C++ [expr.cast]), which uses the syntax
 /// (Type)expr. For example: @c (int)f.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r338020 - [analyzer] Fixed method to get APSInt model

2018-07-26 Thread Mikhail R. Gadelha via cfe-commits
Author: mramalho
Date: Thu Jul 26 04:17:13 2018
New Revision: 338020

URL: http://llvm.org/viewvc/llvm-project?rev=338020&view=rev
Log:
[analyzer] Fixed method to get APSInt model

Summary:
This patch replaces the current method of getting an `APSInt` from Z3's model 
by calling generic API method `getBitvector` instead of `Z3_get_numeral_uint64`.

By calling `getBitvector`, there's no need to handle bitvectors with bit width 
== 128 separately.

And, as a bonus, clang now compiles correctly with Z3 4.7.1.

Reviewers: NoQ, george.karpenkov

Reviewed By: george.karpenkov

Subscribers: xazax.hun, szepet, a.sidorin

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

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTSolver.h
cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTSolver.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTSolver.h?rev=338020&r1=338019&r2=338020&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTSolver.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SMTSolver.h Thu 
Jul 26 04:17:13 2018
@@ -931,7 +931,8 @@ public:
   virtual SMTExprRef getFloatRoundingMode() = 0;
 
   // If the a model is available, returns the value of a given bitvector symbol
-  virtual const llvm::APSInt getBitvector(const SMTExprRef &Exp) = 0;
+  virtual llvm::APSInt getBitvector(const SMTExprRef &Exp, unsigned BitWidth,
+bool isUnsigned) = 0;
 
   // If the a model is available, returns the value of a given boolean symbol
   virtual bool getBoolean(const SMTExprRef &Exp) = 0;

Modified: cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp?rev=338020&r1=338019&r2=338020&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp Thu Jul 26 
04:17:13 2018
@@ -734,10 +734,11 @@ public:
 toZ3Sort(*Sort).Sort)));
   }
 
-  const llvm::APSInt getBitvector(const SMTExprRef &Exp) override {
-// FIXME: this returns a string and the bitWidth is overridden
-return llvm::APSInt(
-Z3_get_numeral_string(Context.Context, toZ3Expr(*Exp).AST));
+  llvm::APSInt getBitvector(const SMTExprRef &Exp, unsigned BitWidth,
+bool isUnsigned) override {
+return llvm::APSInt(llvm::APInt(
+BitWidth, Z3_get_numeral_string(Context.Context, toZ3Expr(*Exp).AST),
+10));
   }
 
   bool getBoolean(const SMTExprRef &Exp) override {
@@ -814,26 +815,20 @@ public:
 return false;
   }
 
-  uint64_t Value[2];
-  // Force cast because Z3 defines __uint64 to be a unsigned long long
-  // type, which isn't compatible with a unsigned long type, even if they
-  // are the same size.
-  Z3_get_numeral_uint64(Context.Context, toZ3Expr(*AST).AST,
-reinterpret_cast<__uint64 *>(&Value[0]));
-  if (Sort->getBitvectorSortSize() <= 64) {
-Int = llvm::APSInt(llvm::APInt(Int.getBitWidth(), Value[0]),
-   Int.isUnsigned());
-  } else if (Sort->getBitvectorSortSize() == 128) {
-SMTExprRef ASTHigh = mkBVExtract(127, 64, AST);
-Z3_get_numeral_uint64(Context.Context, toZ3Expr(*AST).AST,
-  reinterpret_cast<__uint64 *>(&Value[1]));
-Int = llvm::APSInt(llvm::APInt(Int.getBitWidth(), Value),
-   Int.isUnsigned());
-  } else {
-assert(false && "Bitwidth not supported!");
-return false;
+  // FIXME: This function is also used to retrieve floating-point values,
+  // which can be 16, 32, 64 or 128 bits long. Bitvectors can be anything
+  // between 1 and 64 bits long, which is the reason we have this weird
+  // guard. In the future, we need proper calls in the backend to retrieve
+  // floating-points and its special values (NaN, +/-infinity, +/-zero),
+  // then we can drop this weird condition.
+  if (Sort->getBitvectorSortSize() <= 64 ||
+  Sort->getBitvectorSortSize() == 128) {
+Int = getBitvector(AST, Int.getBitWidth(), Int.isUnsigned());
+return true;
   }
-  return true;
+
+  assert(false && "Bitwidth not supported!");
+  return false;
 }
 
 if (Sort->isBooleanSort()) {


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


[PATCH] D48958: [clang][ubsan] Implicit Cast Sanitizer - integer truncation - clang part

2018-07-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri updated this revision to Diff 157458.
lebedev.ri marked an inline comment as done.
lebedev.ri added a reviewer: erichkeane.
lebedev.ri added a subscriber: erichkeane.
lebedev.ri added a comment.

Address @rsmith & @erichkeane [IRC] review notes:

- https://reviews.llvm.org/D49838 - [AST] Sink 'part of explicit cast' down 
into ImplicitCastExpr
- https://reviews.llvm.org/D49844 - [AST] Add a isActuallyImplicitCast() helper 
to the CastExpr class.
- Drop no longer needed `CastExprStackGuard`, 
`ScalarExprEmitter::IsTopCastPartOfExplictCast()`, just use 
`CastExpr::isActuallyImplicitCast()` directly.

This should be a NFC change, there should not be any functionality change 
because of this.


Repository:
  rC Clang

https://reviews.llvm.org/D48958

Files:
  docs/ReleaseNotes.rst
  docs/UndefinedBehaviorSanitizer.rst
  include/clang/Basic/Sanitizers.def
  include/clang/Basic/Sanitizers.h
  lib/CodeGen/CGExprScalar.cpp
  lib/CodeGen/CodeGenFunction.h
  lib/Driver/SanitizerArgs.cpp
  lib/Driver/ToolChain.cpp
  test/CodeGen/catch-implicit-integer-truncations.c
  test/CodeGenCXX/catch-implicit-integer-truncations.cpp
  test/Driver/fsanitize.c

Index: test/Driver/fsanitize.c
===
--- test/Driver/fsanitize.c
+++ test/Driver/fsanitize.c
@@ -31,6 +31,21 @@
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=integer %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-INTEGER -implicit-check-not="-fsanitize-address-use-after-scope"
 // CHECK-INTEGER: "-fsanitize={{((signed-integer-overflow|unsigned-integer-overflow|integer-divide-by-zero|shift-base|shift-exponent),?){5}"}}
 
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=implicit-cast %s -### 2>&1 | FileCheck %s --check-prefixes=CHECK-IMPLICIT-CAST,CHECK-IMPLICIT-CAST-RECOVER
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=implicit-cast -fsanitize-recover=implicit-cast %s -### 2>&1 | FileCheck %s --check-prefixes=CHECK-IMPLICIT-CAST,CHECK-IMPLICIT-CAST-RECOVER
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=implicit-cast -fno-sanitize-recover=implicit-cast %s -### 2>&1 | FileCheck %s --check-prefixes=CHECK-IMPLICIT-CAST,CHECK-IMPLICIT-CAST-NORECOVER
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=implicit-cast -fsanitize-trap=implicit-cast %s -### 2>&1 | FileCheck %s --check-prefixes=CHECK-IMPLICIT-CAST,CHECK-IMPLICIT-CAST-TRAP
+// CHECK-IMPLICIT-CAST: "-fsanitize={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-RECOVER: "-fsanitize-recover={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-RECOVER-NOT: "-fno-sanitize-recover={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-RECOVER-NOT: "-fsanitize-trap={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-NORECOVER-NOT: "-fno-sanitize-recover={{((implicit-integer-truncation),?){1}"}} // ???
+// CHECK-IMPLICIT-CAST-NORECOVER-NOT: "-fsanitize-recover={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-NORECOVER-NOT: "-fsanitize-trap={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-TRAP: "-fsanitize-trap={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-TRAP-NOT: "-fsanitize-recover={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-TRAP-NOT: "-fno-sanitize-recover={{((implicit-integer-truncation),?){1}"}}
+
 // RUN: %clang -fsanitize=bounds -### -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix=CHECK-BOUNDS
 // CHECK-BOUNDS: "-fsanitize={{((array-bounds|local-bounds),?){2}"}}
 
Index: test/CodeGenCXX/catch-implicit-integer-truncations.cpp
===
--- /dev/null
+++ test/CodeGenCXX/catch-implicit-integer-truncations.cpp
@@ -0,0 +1,256 @@
+// RUN: %clang_cc1 -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefix=CHECK
+// RUN: %clang_cc1 -fsanitize=implicit-integer-truncation -fno-sanitize-recover=implicit-integer-truncation -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-ANYRECOVER,CHECK-SANITIZE-NORECOVER
+// RUN: %clang_cc1 -fsanitize=implicit-integer-truncation -fsanitize-recover=implicit-integer-truncation -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-ANYRECOVER,CHECK-SANITIZE-RECOVER
+// RUN: %clang_cc1 -fsanitize=implicit-integer-truncation -fsanitize-trap=implicit-integer-truncation -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-TRAP
+
+extern "C" { // Disable name mangling.
+
+// == //
+// Check that explicit cast does not interfere with implicit cast
+// == //
+// These contain one implicit truncating cast, and one explicit truncating cast.
+// We want to make sure that we still diagnose the im

[PATCH] D48958: [clang][ubsan] Implicit Cast Sanitizer - integer truncation - clang part

2018-07-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added inline comments.



Comment at: test/CodeGenCXX/catch-implicit-integer-truncations.cpp:8-33
+// == 
//
+// Check that explicit cast does not interfere with implicit cast
+// == 
//
+// These contain one implicit truncating cast, and one explicit truncating 
cast.
+// We want to make sure that we still diagnose the implicit cast.
+
+// Implicit truncation after explicit truncation.

@rsmith these tests //should// be equivalent to what you have brought up, so 
that situation was already tested.


Repository:
  rC Clang

https://reviews.llvm.org/D48958



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


[clang-tools-extra] r338021 - [clangd] Fix (most) naming warnings from clang-tidy. NFC

2018-07-26 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Thu Jul 26 05:05:31 2018
New Revision: 338021

URL: http://llvm.org/viewvc/llvm-project?rev=338021&view=rev
Log:
[clangd] Fix (most) naming warnings from clang-tidy. NFC

Modified:
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/CodeCompletionStrings.cpp
clang-tools-extra/trunk/clangd/JSONRPCDispatcher.cpp
clang-tools-extra/trunk/clangd/JSONRPCDispatcher.h
clang-tools-extra/trunk/clangd/Protocol.cpp
clang-tools-extra/trunk/clangd/Quality.cpp
clang-tools-extra/trunk/clangd/TUScheduler.cpp
clang-tools-extra/trunk/clangd/XRefs.cpp
clang-tools-extra/trunk/clangd/index/Merge.cpp
clang-tools-extra/trunk/clangd/index/SymbolYAML.cpp
clang-tools-extra/trunk/clangd/index/SymbolYAML.h
clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp
clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp
clang-tools-extra/trunk/unittests/clangd/TestTU.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdUnit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdUnit.cpp?rev=338021&r1=338020&r2=338021&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdUnit.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdUnit.cpp Thu Jul 26 05:05:31 2018
@@ -121,7 +121,7 @@ void clangd::dumpAST(ParsedAST &AST, llv
 }
 
 llvm::Optional
-ParsedAST::Build(std::unique_ptr CI,
+ParsedAST::build(std::unique_ptr CI,
  std::shared_ptr Preamble,
  std::unique_ptr Buffer,
  std::shared_ptr PCHs,
@@ -367,7 +367,7 @@ llvm::Optional clangd::buildA
 // dirs.
   }
 
-  return ParsedAST::Build(
+  return ParsedAST::build(
   llvm::make_unique(*Invocation), Preamble,
   llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents), PCHs, Inputs.FS);
 }

Modified: clang-tools-extra/trunk/clangd/ClangdUnit.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdUnit.h?rev=338021&r1=338020&r2=338021&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdUnit.h (original)
+++ clang-tools-extra/trunk/clangd/ClangdUnit.h Thu Jul 26 05:05:31 2018
@@ -68,7 +68,7 @@ public:
   /// Attempts to run Clang and store parsed AST. If \p Preamble is non-null
   /// it is reused during parsing.
   static llvm::Optional
-  Build(std::unique_ptr CI,
+  build(std::unique_ptr CI,
 std::shared_ptr Preamble,
 std::unique_ptr Buffer,
 std::shared_ptr PCHs,

Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=338021&r1=338020&r2=338021&view=diff
==
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Thu Jul 26 05:05:31 2018
@@ -704,7 +704,7 @@ public:
   CurrentArg, S, *Allocator, CCTUInfo, true);
   assert(CCS && "Expected the CodeCompletionString to be non-null");
   // FIXME: for headers, we need to get a comment from the index.
-  SigHelp.signatures.push_back(ProcessOverloadCandidate(
+  SigHelp.signatures.push_back(processOverloadCandidate(
   Candidate, *CCS,
   getParameterDocComment(S.getASTContext(), Candidate, CurrentArg,
  /*CommentsFromHeaders=*/false)));
@@ -719,7 +719,7 @@ private:
   // FIXME(ioeric): consider moving CodeCompletionString logic here to
   // CompletionString.h.
   SignatureInformation
-  ProcessOverloadCandidate(const OverloadCandidate &Candidate,
+  processOverloadCandidate(const OverloadCandidate &Candidate,
const CodeCompletionString &CCS,
llvm::StringRef DocComment) const {
 SignatureInformation Result;

Modified: clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp?rev=338021&r1=338020&r2=338021&view=diff
==
--- clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp Thu Jul 26 
05:05:31 2018
@@ -32,7 +32,7 @@ void appendEscapeSnippet(const llvm::Str
   }
 }
 
-bool LooksLikeDocComment(llvm::StringRef CommentText) {
+bool looksLikeDocComment(llvm::StringRef CommentText) {
   // We don't report comments that only contain "special" chars.
   // This avoids reporting various delimiters, like:
   //   =
@@ -67,7 +67,7 @@ std::string getDocComment(const ASTConte
   // write them into PCH, because they are racy and slow to load.
   asse

[PATCH] D49797: [clang-format] Indent after breaking Javadoc annotated line

2018-07-26 Thread Martin Probst via Phabricator via cfe-commits
mprobst added inline comments.



Comment at: lib/Format/BreakableToken.cpp:526
+  0, Content[LineIndex].find_first_of(Blanks));
+  if (FirstWord == "@param")
+return Style.ContinuationIndentWidth;

Shouldn't this check the set above?



Comment at: unittests/Format/FormatTestComments.cpp:3109
+TEST_F(FormatTestComments, IndentsLongJavadocAnnotatedLines) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_Java);
+  Style.ColumnLimit = 60;

add a test using `@return` or `@type`?



Comment at: unittests/Format/FormatTestComments.cpp:3154
+
+  EXPECT_EQ("/**\n"
+" * @param l1 long1\n"

do we already have a test that `@param {oh noes this is really long} foo` isn't 
broken?


Repository:
  rC Clang

https://reviews.llvm.org/D49797



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


[PATCH] D49848: Parse a possible trailing postsfix expression suffix after a fold expression

2018-07-26 Thread Nicolas Lesser via Phabricator via cfe-commits
Rakete created this revision.
Rakete added a reviewer: rsmith.

This patch allows the parsing of a postfix expression involving a fold 
expression, which is legal as a fold-expression is a primary-expression.

See also https://llvm.org/pr38282


Repository:
  rC Clang

https://reviews.llvm.org/D49848

Files:
  lib/Parse/ParseExpr.cpp
  test/Parser/cxx1z-fold-expressions.cpp


Index: test/Parser/cxx1z-fold-expressions.cpp
===
--- test/Parser/cxx1z-fold-expressions.cpp
+++ test/Parser/cxx1z-fold-expressions.cpp
@@ -60,3 +60,21 @@
 }
 
 static_assert(nestedFoldOperator<3, 1>() == 1);
+
+// A fold-expression is a primary-expression.
+template 
+constexpr auto castSum(Ts... Args) {
+  return (T)(Args + ...).Value; // expected-error{{member reference base type 
'int' is not a structure or union}}
+}
+
+void prim() {
+  castSum(1, 2);
+  // expected-note@-1{{in instantiation of function template specialization}}
+
+  struct Number {
+int Value;
+constexpr Number operator+(Number Rhs) const { return {Rhs.Value + Value}; 
}
+  };
+
+  static_assert(castSum(Number{1}, Number{2}) == 3);
+}
Index: lib/Parse/ParseExpr.cpp
===
--- lib/Parse/ParseExpr.cpp
+++ lib/Parse/ParseExpr.cpp
@@ -2514,7 +2514,10 @@
 }
   } else if (Tok.is(tok::ellipsis) &&
  isFoldOperator(NextToken().getKind())) {
-return ParseFoldExpression(ExprResult(), T);
+Result = ParseFoldExpression(ExprResult(), T);
+if (!Result.isInvalid())
+  Result = ParsePostfixExpressionSuffix(Result.get());
+return Result;
   } else if (isTypeCast) {
 // Parse the expression-list.
 InMessageExpressionRAIIObject InMessage(*this, false);
@@ -2526,8 +2529,12 @@
   // FIXME: If we ever support comma expressions as operands to
   // fold-expressions, we'll need to allow multiple ArgExprs here.
   if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) &&
-  NextToken().is(tok::ellipsis))
-return ParseFoldExpression(ArgExprs[0], T);
+  NextToken().is(tok::ellipsis)) {
+Result = ParseFoldExpression(ArgExprs[0], T);
+if (!Result.isInvalid())
+  Result = ParsePostfixExpressionSuffix(Result.get());
+return Result;
+  }
 
   ExprType = SimpleExpr;
   Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
@@ -2544,8 +2551,12 @@
 }
 ExprType = SimpleExpr;
 
-if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis))
-  return ParseFoldExpression(Result, T);
+if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis)) {
+  Result = ParseFoldExpression(Result, T);
+  if (!Result.isInvalid())
+Result = ParsePostfixExpressionSuffix(Result.get());
+  return Result;
+}
 
 // Don't build a paren expression unless we actually match a ')'.
 if (!Result.isInvalid() && Tok.is(tok::r_paren))


Index: test/Parser/cxx1z-fold-expressions.cpp
===
--- test/Parser/cxx1z-fold-expressions.cpp
+++ test/Parser/cxx1z-fold-expressions.cpp
@@ -60,3 +60,21 @@
 }
 
 static_assert(nestedFoldOperator<3, 1>() == 1);
+
+// A fold-expression is a primary-expression.
+template 
+constexpr auto castSum(Ts... Args) {
+  return (T)(Args + ...).Value; // expected-error{{member reference base type 'int' is not a structure or union}}
+}
+
+void prim() {
+  castSum(1, 2);
+  // expected-note@-1{{in instantiation of function template specialization}}
+
+  struct Number {
+int Value;
+constexpr Number operator+(Number Rhs) const { return {Rhs.Value + Value}; }
+  };
+
+  static_assert(castSum(Number{1}, Number{2}) == 3);
+}
Index: lib/Parse/ParseExpr.cpp
===
--- lib/Parse/ParseExpr.cpp
+++ lib/Parse/ParseExpr.cpp
@@ -2514,7 +2514,10 @@
 }
   } else if (Tok.is(tok::ellipsis) &&
  isFoldOperator(NextToken().getKind())) {
-return ParseFoldExpression(ExprResult(), T);
+Result = ParseFoldExpression(ExprResult(), T);
+if (!Result.isInvalid())
+  Result = ParsePostfixExpressionSuffix(Result.get());
+return Result;
   } else if (isTypeCast) {
 // Parse the expression-list.
 InMessageExpressionRAIIObject InMessage(*this, false);
@@ -2526,8 +2529,12 @@
   // FIXME: If we ever support comma expressions as operands to
   // fold-expressions, we'll need to allow multiple ArgExprs here.
   if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) &&
-  NextToken().is(tok::ellipsis))
-return ParseFoldExpression(ArgExprs[0], T);
+  NextToken().is(tok::ellipsis)) {
+Result = ParseFoldExpression(ArgExprs[0], T);
+if (!Result.isInvalid())
+  Result = ParsePostfixExpressionSuffix(Result.get());
+return Result;
+  }
 
   ExprType = SimpleExpr;
 

[PATCH] D48903: [VirtualFileSystem] InMemoryFileSystem::status: Return a Status with the requested name

2018-07-26 Thread Simon Marchi via Phabricator via cfe-commits
simark marked 7 inline comments as done.
simark added inline comments.



Comment at: lib/Basic/VirtualFileSystem.cpp:475
   InMemoryNodeKind Kind;
+  Status Stat;
+

ilya-biryukov wrote:
> NIT: maybe keep the order of members the same to keep the patch more focused? 
> Unless there's a good reason to swap them.
Oops, that was not intended.


Repository:
  rC Clang

https://reviews.llvm.org/D48903



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


[PATCH] D48903: [VirtualFileSystem] InMemoryFileSystem::status: Return a Status with the requested name

2018-07-26 Thread Simon Marchi via Phabricator via cfe-commits
simark updated this revision to Diff 157467.
simark marked an inline comment as done.
simark added a comment.

I think this addresses all of Ilya's comments.


Repository:
  rC Clang

https://reviews.llvm.org/D48903

Files:
  lib/Basic/FileManager.cpp
  lib/Basic/VirtualFileSystem.cpp
  unittests/Basic/VirtualFileSystemTest.cpp
  unittests/Driver/ToolChainTest.cpp

Index: unittests/Driver/ToolChainTest.cpp
===
--- unittests/Driver/ToolChainTest.cpp
+++ unittests/Driver/ToolChainTest.cpp
@@ -113,7 +113,7 @@
   std::replace(S.begin(), S.end(), '\\', '/');
 #endif
   EXPECT_EQ("Found candidate GCC installation: "
-"/home/test/lib/gcc/arm-linux-gnueabi/4.6.1\n"
+"/home/test/bin/../lib/gcc/arm-linux-gnueabi/4.6.1\n"
 "Selected GCC installation: "
 "/home/test/bin/../lib/gcc/arm-linux-gnueabi/4.6.1\n"
 "Candidate multilib: .;@m32\n"
Index: unittests/Basic/VirtualFileSystemTest.cpp
===
--- unittests/Basic/VirtualFileSystemTest.cpp
+++ unittests/Basic/VirtualFileSystemTest.cpp
@@ -13,6 +13,7 @@
 #include "llvm/Support/Errc.h"
 #include "llvm/Support/Host.h"
 #include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
 #include "llvm/Support/SourceMgr.h"
 #include "gtest/gtest.h"
 #include 
@@ -151,6 +152,13 @@
 addEntry(Path, S);
   }
 };
+
+/// Replace back-slashes by front-slashes.
+std::string getPosixPath(std::string S) {
+  SmallString<128> Result;
+  llvm::sys::path::native(S, Result, llvm::sys::path::Style::posix);
+  return Result.str();
+};
 } // end anonymous namespace
 
 TEST(VirtualFileSystemTest, StatusQueries) {
@@ -782,7 +790,9 @@
 
   I = FS.dir_begin("/b", EC);
   ASSERT_FALSE(EC);
-  ASSERT_EQ("/b/c", I->getName());
+  // When on Windows, we end up with "/b\\c" as the name.  Convert to Posix
+  // path for the sake of the comparison.
+  ASSERT_EQ("/b/c", getPosixPath(I->getName()));
   I.increment(EC);
   ASSERT_FALSE(EC);
   ASSERT_EQ(vfs::directory_iterator(), I);
@@ -794,23 +804,19 @@
 
   auto Stat = FS.status("/b/c");
   ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
-  ASSERT_EQ("c", Stat->getName());
+  ASSERT_EQ("/b/c", Stat->getName());
   ASSERT_EQ("/b", *FS.getCurrentWorkingDirectory());
 
   Stat = FS.status("c");
   ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
 
-  auto ReplaceBackslashes = [](std::string S) {
-std::replace(S.begin(), S.end(), '\\', '/');
-return S;
-  };
   NormalizedFS.setCurrentWorkingDirectory("/b/c");
   NormalizedFS.setCurrentWorkingDirectory(".");
-  ASSERT_EQ("/b/c", ReplaceBackslashes(
-NormalizedFS.getCurrentWorkingDirectory().get()));
+  ASSERT_EQ("/b/c",
+getPosixPath(NormalizedFS.getCurrentWorkingDirectory().get()));
   NormalizedFS.setCurrentWorkingDirectory("..");
-  ASSERT_EQ("/b", ReplaceBackslashes(
-  NormalizedFS.getCurrentWorkingDirectory().get()));
+  ASSERT_EQ("/b",
+getPosixPath(NormalizedFS.getCurrentWorkingDirectory().get()));
 }
 
 #if !defined(_WIN32)
@@ -919,6 +925,39 @@
   ASSERT_TRUE(Stat->isRegularFile());
 }
 
+// Test that the name returned by status() is in the same form as the path that
+// was requested (to match the behavior of RealFileSystem).
+TEST_F(InMemoryFileSystemTest, StatusName) {
+  NormalizedFS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"),
+   /*User=*/None,
+   /*Group=*/None, sys::fs::file_type::regular_file);
+  NormalizedFS.setCurrentWorkingDirectory("/a/b");
+
+  // Access using InMemoryFileSystem::status.
+  auto Stat = NormalizedFS.status("../b/c");
+  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n"
+<< NormalizedFS.toString();
+  ASSERT_TRUE(Stat->isRegularFile());
+  ASSERT_EQ("../b/c", Stat->getName());
+
+  // Access using InMemoryFileAdaptor::status.
+  auto File = NormalizedFS.openFileForRead("../b/c");
+  ASSERT_FALSE(File.getError()) << File.getError() << "\n"
+<< NormalizedFS.toString();
+  Stat = (*File)->status();
+  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n"
+<< NormalizedFS.toString();
+  ASSERT_TRUE(Stat->isRegularFile());
+  ASSERT_EQ("../b/c", Stat->getName());
+
+  // Access using a directory iterator.
+  std::error_code EC;
+  clang::vfs::directory_iterator It = NormalizedFS.dir_begin("../b", EC);
+  // When on Windows, we end up with "../b\\c" as the name.  Convert to Posix
+  // path for the sake of the comparison.
+  ASSERT_EQ("../b/c", getPosixPath(It->getName()));
+}
+
 // NOTE: in the tests below, we use '//root/' as our root directory, since it is
 // a legal *absolute* path on Windows as well as *nix.
 class VFSFromYAMLTest : public ::testing::Test {
Index: lib/Basic/VirtualFileSystem.cpp
=

[PATCH] D49723: [OpenCL] Check for invalid kernel arguments in array types

2018-07-26 Thread Andrew Savonichev via Phabricator via cfe-commits
asavonic updated this revision to Diff 157470.
asavonic added a comment.

Moved another chunk from https://reviews.llvm.org/D49725


Repository:
  rC Clang

https://reviews.llvm.org/D49723

Files:
  lib/Sema/SemaDecl.cpp
  test/SemaOpenCL/invalid-kernel-parameters.cl


Index: test/SemaOpenCL/invalid-kernel-parameters.cl
===
--- test/SemaOpenCL/invalid-kernel-parameters.cl
+++ test/SemaOpenCL/invalid-kernel-parameters.cl
@@ -136,3 +136,16 @@
 };
 
 kernel void pointer_in_nested_struct_arg_2(struct Valid valid, struct 
NestedPointer arg, struct AlsoUser also) { } // expected-error 2 {{struct 
kernel parameters may not contain pointers}}
+
+struct ArrayOfPtr // expected-note{{within field of type 'ArrayOfPtr' declared 
here}}
+{
+  float *arr[3]; // expected-note{{field of illegal type 'float *[3]' declared 
here}}
+ // expected-note@-1{{field of illegal type 'float *[3]' 
declared here}}
+};
+kernel void array_of_ptr(struct ArrayOfPtr arr) {} // expected-error{{struct 
kernel parameters may not contain pointers}}
+
+struct ArrayOfStruct // expected-note{{within field of type 'ArrayOfStruct' 
declared here}}
+{
+  struct ArrayOfPtr arr[3]; // expected-note{{within field of type 'struct 
ArrayOfPtr [3]' declared here}}
+};
+kernel void array_of_struct(struct ArrayOfStruct arr) {} // 
expected-error{{struct kernel parameters may not contain pointers}}
Index: lib/Sema/SemaDecl.cpp
===
--- lib/Sema/SemaDecl.cpp
+++ lib/Sema/SemaDecl.cpp
@@ -8079,6 +8079,15 @@
   if (PT->isRecordType())
 return RecordKernelParam;
 
+  // Look into an array argument to check if it has a forbidden type.
+  if (PT->isArrayType()) {
+const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
+// Call ourself to check an underlying type of an array. Since the
+// getPointeeOrArrayElementType returns an innermost type which is not an
+// array, this recusive call only happens once.
+return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
+  }
+
   return ValidKernelParam;
 }
 
@@ -8146,9 +8155,14 @@
   SmallVector HistoryStack;
   HistoryStack.push_back(nullptr);
 
-  const RecordDecl *PD = PT->castAs()->getDecl();
-  VisitStack.push_back(PD);
+  // At this point we already handled everything except of a RecordType or
+  // an ArrayType of a RecordType.
+  assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
+  const RecordType *RecTy =
+  PT->getPointeeOrArrayElementType()->getAs();
+  const RecordDecl *OrigRecDecl = RecTy->getDecl();
 
+  VisitStack.push_back(RecTy->getDecl());
   assert(VisitStack.back() && "First decl null?");
 
   do {
@@ -8167,7 +8181,13 @@
 const RecordDecl *RD;
 if (const FieldDecl *Field = dyn_cast(Next)) {
   HistoryStack.push_back(Field);
-  RD = Field->getType()->castAs()->getDecl();
+
+  // Other field types (known to be valid or invalid) are handled while we
+  // walk around RecordDecl::fields().
+  assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
+  const Type *FieldRecTy = 
Field->getType()->getPointeeOrArrayElementType();
+
+  RD = FieldRecTy->castAs()->getDecl();
 } else {
   RD = cast(Next);
 }
@@ -8204,8 +8224,8 @@
 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
   }
 
-  S.Diag(PD->getLocation(), diag::note_within_field_of_type)
-<< PD->getDeclName();
+  S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
+  << OrigRecDecl->getDeclName();
 
   // We have an error, now let's go back up through history and show where
   // the offending field came from


Index: test/SemaOpenCL/invalid-kernel-parameters.cl
===
--- test/SemaOpenCL/invalid-kernel-parameters.cl
+++ test/SemaOpenCL/invalid-kernel-parameters.cl
@@ -136,3 +136,16 @@
 };
 
 kernel void pointer_in_nested_struct_arg_2(struct Valid valid, struct NestedPointer arg, struct AlsoUser also) { } // expected-error 2 {{struct kernel parameters may not contain pointers}}
+
+struct ArrayOfPtr // expected-note{{within field of type 'ArrayOfPtr' declared here}}
+{
+  float *arr[3]; // expected-note{{field of illegal type 'float *[3]' declared here}}
+ // expected-note@-1{{field of illegal type 'float *[3]' declared here}}
+};
+kernel void array_of_ptr(struct ArrayOfPtr arr) {} // expected-error{{struct kernel parameters may not contain pointers}}
+
+struct ArrayOfStruct // expected-note{{within field of type 'ArrayOfStruct' declared here}}
+{
+  struct ArrayOfPtr arr[3]; // expected-note{{within field of type 'struct ArrayOfPtr [3]' declared here}}
+};
+kernel void array_of_struct(struct ArrayOfStruct arr) {} // expected-error{{struct kernel parameters may not contain pointers}}
Index: lib/Sema/SemaDecl.cpp

[PATCH] D49725: [OpenCL] Forbid size dependent types used as kernel arguments

2018-07-26 Thread Andrew Savonichev via Phabricator via cfe-commits
asavonic updated this revision to Diff 157471.
asavonic added a comment.

Moved unrelated change to https://reviews.llvm.org/D49723.


Repository:
  rC Clang

https://reviews.llvm.org/D49725

Files:
  lib/Sema/SemaDecl.cpp
  test/SemaOpenCL/invalid-kernel-parameters.cl

Index: test/SemaOpenCL/invalid-kernel-parameters.cl
===
--- test/SemaOpenCL/invalid-kernel-parameters.cl
+++ test/SemaOpenCL/invalid-kernel-parameters.cl
@@ -9,7 +9,35 @@
 // bool, half, size_t, ptrdiff_t, intptr_t, and uintptr_t
 // or a struct / union with any of these types in them
 
-// TODO: Ban int types, size_t, ptrdiff_t ...
+typedef __SIZE_TYPE__ size_t; // expected-note{{'size_t' (aka 'unsigned int') declared here}}
+  // expected-note@-1{{'size_t' (aka 'unsigned int') declared here}}
+typedef __PTRDIFF_TYPE__ ptrdiff_t; // expected-note{{'ptrdiff_t' (aka 'int') declared here}}
+typedef __INTPTR_TYPE__ intptr_t; // expected-note{{'intptr_t' (aka 'int') declared here}}
+typedef __UINTPTR_TYPE__ uintptr_t; // expected-note{{'uintptr_t' (aka 'unsigned int') declared here}}
+
+kernel void size_t_arg(size_t x) {} // expected-error{{'size_t' (aka 'unsigned int') cannot be used as the type of a kernel parameter}}
+
+kernel void ptrdiff_t_arg(ptrdiff_t x) {} // expected-error{{'ptrdiff_t' (aka 'int') cannot be used as the type of a kernel parameter}}
+
+kernel void intptr_t_arg(intptr_t x) {} // expected-error{{'intptr_t' (aka 'int') cannot be used as the type of a kernel parameter}}
+
+kernel void uintptr_t_arg(uintptr_t x) {} // expected-error{{'uintptr_t' (aka 'unsigned int') cannot be used as the type of a kernel parameter}}
+
+typedef size_t size_ty;
+struct SizeTStruct { // expected-note{{within field of type 'SizeTStruct' declared here}}
+  size_ty s; // expected-note{{field of illegal type 'size_ty' (aka 'unsigned int') declared here}}
+};
+kernel void size_t_struct_arg(struct SizeTStruct x) {} // expected-error{{'struct SizeTStruct' cannot be used as the type of a kernel parameter}}
+
+union SizeTUnion { // expected-note{{within field of type 'SizeTUnion' declared here}}
+  size_t s; // expected-note{{field of illegal type 'size_t' (aka 'unsigned int') declared here}}
+  float f;
+};
+kernel void size_t_union_arg(union SizeTUnion x) {} // expected-error{{'union SizeTUnion' cannot be used as the type of a kernel parameter}}
+
+typedef size_t s_ty; // expected-note{{'s_ty' (aka 'unsigned int') declared here}}
+typedef s_ty ss_ty; // expected-note{{'ss_ty' (aka 'unsigned int') declared here}}
+kernel void typedef_to_size_t(ss_ty s) {} // expected-error{{'ss_ty' (aka 'unsigned int') cannot be used as the type of a kernel parameter}}
 
 kernel void bool_arg(bool x) { } // expected-error{{'bool' cannot be used as the type of a kernel parameter}}
 
Index: lib/Sema/SemaDecl.cpp
===
--- lib/Sema/SemaDecl.cpp
+++ lib/Sema/SemaDecl.cpp
@@ -8049,6 +8049,29 @@
   RecordKernelParam
 };
 
+static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
+  // Size dependent types are just typedefs to normal integer types
+  // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
+  // integers other than by their names.
+  StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
+
+  // Remove typedefs one by one until we reach a typedef
+  // for a size dependent type.
+  QualType DesugaredTy = Ty;
+  do {
+ArrayRef Names(SizeTypeNames);
+auto Match =
+std::find(Names.begin(), Names.end(), DesugaredTy.getAsString());
+if (Names.end() != Match)
+  return true;
+
+Ty = DesugaredTy;
+DesugaredTy = Ty.getSingleStepDesugaredType(C);
+  } while (DesugaredTy != Ty);
+
+  return false;
+}
+
 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
   if (PT->isPointerType()) {
 QualType PointeeType = PT->getPointeeType();
@@ -8061,8 +8084,13 @@
 return PtrKernelParam;
   }
 
-  // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
-  // be used as builtin types.
+  // OpenCL v1.2 s6.9.k:
+  // Arguments to kernel functions in a program cannot be declared with the
+  // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
+  // uintptr_t or a struct and/or union that contain fields declared to be one
+  // of these built-in scalar types.
+  if (isOpenCLSizeDependentType(S.getASTContext(), PT))
+return InvalidKernelParam;
 
   if (PT->isImageType())
 return PtrKernelParam;
@@ -8133,8 +8161,20 @@
 // of event_t type.
 // Do not diagnose half type since it is diagnosed as invalid argument
 // type for any function elsewhere.
-if (!PT->isHalfType())
+if (!PT->isHalfType()) {
   S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
+
+  // Explain what typedefs are involved.
+  const TypedefType *Typedef = null

[PATCH] D49850: [ASTMatchers] fix the missing documentation for new decltypeType matcher

2018-07-26 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth created this revision.
JonasToth added reviewers: alexfh, aaron.ballman.
Herald added a subscriber: cfe-commits.

Regenerate the Matchers documentation, forgotten in the original patch.


Repository:
  rC Clang

https://reviews.llvm.org/D49850

Files:
  docs/LibASTMatchersReference.html


Index: docs/LibASTMatchersReference.html
===
--- docs/LibASTMatchersReference.html
+++ docs/LibASTMatchersReference.html
@@ -1577,6 +1577,18 @@
 
 
 
+MatcherType>decltypeTypeMatcherDecltypeType>...
+Matches types nodes 
representing C++11 decltype() types.
+
+Given:
+  short i = 1;
+  int j = 42;
+  decltype(i + j) result = i + j;
+decltypeType() 
+  matches "decltype(i + j)"
+
+
+
 MatcherType>dependentSizedArrayTypeMatcherDependentSizedArrayType>...
 Matches C++ 
arrays whose size is a value-dependent expression.
 
@@ -5150,6 +5162,19 @@
 
 
 
+MatcherDecltypeType>hasUnderlyingTypeMatcherType>
+Matches 
DecltypeType nodes to find out the underlying type.
+
+Given
+  decltype(1) a = 1;
+  decltype(2.0) b = 2.0;
+decltypeType(hasUnderlyingType(isInteger()))
+  matches "auto a"
+
+Usable as: MatcherDecltypeType>
+
+
+
 MatcherDoStmt>hasBodyMatcherStmt> 
InnerMatcher
 Matches a 'for', 'while', 
'do while' statement or a function
 definition that has a given body.


Index: docs/LibASTMatchersReference.html
===
--- docs/LibASTMatchersReference.html
+++ docs/LibASTMatchersReference.html
@@ -1577,6 +1577,18 @@
 
 
 
+MatcherType>decltypeTypeMatcherDecltypeType>...
+Matches types nodes representing C++11 decltype() types.
+
+Given:
+  short i = 1;
+  int j = 42;
+  decltype(i + j) result = i + j;
+decltypeType() 
+  matches "decltype(i + j)"
+
+
+
 MatcherType>dependentSizedArrayTypeMatcherDependentSizedArrayType>...
 Matches C++ arrays whose size is a value-dependent expression.
 
@@ -5150,6 +5162,19 @@
 
 
 
+MatcherDecltypeType>hasUnderlyingTypeMatcherType>
+Matches DecltypeType nodes to find out the underlying type.
+
+Given
+  decltype(1) a = 1;
+  decltype(2.0) b = 2.0;
+decltypeType(hasUnderlyingType(isInteger()))
+  matches "auto a"
+
+Usable as: MatcherDecltypeType>
+
+
+
 MatcherDoStmt>hasBodyMatcherStmt> InnerMatcher
 Matches a 'for', 'while', 'do while' statement or a function
 definition that has a given body.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D49725: [OpenCL] Forbid size dependent types used as kernel arguments

2018-07-26 Thread Andrew Savonichev via Phabricator via cfe-commits
asavonic marked an inline comment as done.
asavonic added inline comments.



Comment at: lib/Sema/SemaDecl.cpp:8267
 
-  S.Diag(PD->getLocation(), diag::note_within_field_of_type)
-<< PD->getDeclName();
+  S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
+  << OrigRecDecl->getDeclName();

Anastasia wrote:
> Should this bit go into https://reviews.llvm.org/D49725?
Right, thank you!


Repository:
  rC Clang

https://reviews.llvm.org/D49725



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


[PATCH] D49850: [ASTMatchers] fix the missing documentation for new decltypeType matcher

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

LGTM -- this sort of change can have post-commit review, btw.


Repository:
  rC Clang

https://reviews.llvm.org/D49850



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


[PATCH] D49851: [clang-tidy] run-clang-tidy add synchronisation to the output

2018-07-26 Thread Andi via Phabricator via cfe-commits
Abpostelnicu created this revision.
Abpostelnicu added a project: clang-tools-extra.
Herald added subscribers: cfe-commits, xazax.hun.

The goal of this patch is to add synchronisation of the output of the tool with 
the actual files that are verified. Without it the output of clang-tidy will 
get mixed with the clang-tidy command that is also passed to stdout.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49851

Files:
  clang-tidy/tool/run-clang-tidy.py


Index: clang-tidy/tool/run-clang-tidy.py
===
--- clang-tidy/tool/run-clang-tidy.py
+++ clang-tidy/tool/run-clang-tidy.py
@@ -153,7 +153,7 @@
   subprocess.call(invocation)
 
 
-def run_tidy(args, tmpdir, build_path, queue, failed_files):
+def run_tidy(args, tmpdir, build_path, queue, lock, failed_files):
   """Takes filenames out of queue and runs clang-tidy on them."""
   while True:
 name = queue.get()
@@ -161,10 +161,15 @@
  tmpdir, build_path, args.header_filter,
  args.extra_arg, args.extra_arg_before,
  args.quiet, args.config)
-sys.stdout.write(' '.join(invocation) + '\n')
-return_code = subprocess.call(invocation)
-if return_code != 0:
+
+proc = subprocess.Popen(invocation, stdout=subprocess.PIPE, 
stderr=subprocess.PIPE)
+output, err = proc.communicate()
+if proc.returncode:
   failed_files.append(name)
+with lock:
+  sys.stdout.write(' '.join(invocation) + '\n' + output + '\n')
+  if len(err):
+sys.stderr.write(err + '\n')
 queue.task_done()
 
 
@@ -263,9 +268,10 @@
 task_queue = queue.Queue(max_task)
 # List of files with a non-zero return code.
 failed_files = []
+lock = threading.Lock()
 for _ in range(max_task):
   t = threading.Thread(target=run_tidy,
-   args=(args, tmpdir, build_path, task_queue, 
failed_files))
+   args=(args, tmpdir, build_path, task_queue, lock, 
failed_files))
   t.daemon = True
   t.start()
 


Index: clang-tidy/tool/run-clang-tidy.py
===
--- clang-tidy/tool/run-clang-tidy.py
+++ clang-tidy/tool/run-clang-tidy.py
@@ -153,7 +153,7 @@
   subprocess.call(invocation)
 
 
-def run_tidy(args, tmpdir, build_path, queue, failed_files):
+def run_tidy(args, tmpdir, build_path, queue, lock, failed_files):
   """Takes filenames out of queue and runs clang-tidy on them."""
   while True:
 name = queue.get()
@@ -161,10 +161,15 @@
  tmpdir, build_path, args.header_filter,
  args.extra_arg, args.extra_arg_before,
  args.quiet, args.config)
-sys.stdout.write(' '.join(invocation) + '\n')
-return_code = subprocess.call(invocation)
-if return_code != 0:
+
+proc = subprocess.Popen(invocation, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+output, err = proc.communicate()
+if proc.returncode:
   failed_files.append(name)
+with lock:
+  sys.stdout.write(' '.join(invocation) + '\n' + output + '\n')
+  if len(err):
+sys.stderr.write(err + '\n')
 queue.task_done()
 
 
@@ -263,9 +268,10 @@
 task_queue = queue.Queue(max_task)
 # List of files with a non-zero return code.
 failed_files = []
+lock = threading.Lock()
 for _ in range(max_task):
   t = threading.Thread(target=run_tidy,
-   args=(args, tmpdir, build_path, task_queue, failed_files))
+   args=(args, tmpdir, build_path, task_queue, lock, failed_files))
   t.daemon = True
   t.start()
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D49850: [ASTMatchers] fix the missing documentation for new decltypeType matcher

2018-07-26 Thread Jonas Toth via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC338022: [ASTMatchers] fix the missing documentation for new 
decltypeType matcher (authored by JonasToth, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D49850?vs=157474&id=157475#toc

Repository:
  rC Clang

https://reviews.llvm.org/D49850

Files:
  docs/LibASTMatchersReference.html


Index: docs/LibASTMatchersReference.html
===
--- docs/LibASTMatchersReference.html
+++ docs/LibASTMatchersReference.html
@@ -1577,6 +1577,18 @@
 
 
 
+MatcherType>decltypeTypeMatcherDecltypeType>...
+Matches types nodes 
representing C++11 decltype() types.
+
+Given:
+  short i = 1;
+  int j = 42;
+  decltype(i + j) result = i + j;
+decltypeType() 
+  matches "decltype(i + j)"
+
+
+
 MatcherType>dependentSizedArrayTypeMatcherDependentSizedArrayType>...
 Matches C++ 
arrays whose size is a value-dependent expression.
 
@@ -5156,6 +5168,19 @@
 
 
 
+MatcherDecltypeType>hasUnderlyingTypeMatcherType>
+Matches 
DecltypeType nodes to find out the underlying type.
+
+Given
+  decltype(1) a = 1;
+  decltype(2.0) b = 2.0;
+decltypeType(hasUnderlyingType(isInteger()))
+  matches "auto a"
+
+Usable as: MatcherDecltypeType>
+
+
+
 MatcherDoStmt>hasBodyMatcherStmt> 
InnerMatcher
 Matches a 'for', 'while', 
'do while' statement or a function
 definition that has a given body.


Index: docs/LibASTMatchersReference.html
===
--- docs/LibASTMatchersReference.html
+++ docs/LibASTMatchersReference.html
@@ -1577,6 +1577,18 @@
 
 
 
+MatcherType>decltypeTypeMatcherDecltypeType>...
+Matches types nodes representing C++11 decltype() types.
+
+Given:
+  short i = 1;
+  int j = 42;
+  decltype(i + j) result = i + j;
+decltypeType() 
+  matches "decltype(i + j)"
+
+
+
 MatcherType>dependentSizedArrayTypeMatcherDependentSizedArrayType>...
 Matches C++ arrays whose size is a value-dependent expression.
 
@@ -5156,6 +5168,19 @@
 
 
 
+MatcherDecltypeType>hasUnderlyingTypeMatcherType>
+Matches DecltypeType nodes to find out the underlying type.
+
+Given
+  decltype(1) a = 1;
+  decltype(2.0) b = 2.0;
+decltypeType(hasUnderlyingType(isInteger()))
+  matches "auto a"
+
+Usable as: MatcherDecltypeType>
+
+
+
 MatcherDoStmt>hasBodyMatcherStmt> InnerMatcher
 Matches a 'for', 'while', 'do while' statement or a function
 definition that has a given body.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D49850: [ASTMatchers] fix the missing documentation for new decltypeType matcher

2018-07-26 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 157474.
JonasToth added a comment.

rebase


Repository:
  rC Clang

https://reviews.llvm.org/D49850

Files:
  docs/LibASTMatchersReference.html


Index: docs/LibASTMatchersReference.html
===
--- docs/LibASTMatchersReference.html
+++ docs/LibASTMatchersReference.html
@@ -1577,6 +1577,18 @@
 
 
 
+MatcherType>decltypeTypeMatcherDecltypeType>...
+Matches types nodes 
representing C++11 decltype() types.
+
+Given:
+  short i = 1;
+  int j = 42;
+  decltype(i + j) result = i + j;
+decltypeType() 
+  matches "decltype(i + j)"
+
+
+
 MatcherType>dependentSizedArrayTypeMatcherDependentSizedArrayType>...
 Matches C++ 
arrays whose size is a value-dependent expression.
 
@@ -5156,6 +5168,19 @@
 
 
 
+MatcherDecltypeType>hasUnderlyingTypeMatcherType>
+Matches 
DecltypeType nodes to find out the underlying type.
+
+Given
+  decltype(1) a = 1;
+  decltype(2.0) b = 2.0;
+decltypeType(hasUnderlyingType(isInteger()))
+  matches "auto a"
+
+Usable as: MatcherDecltypeType>
+
+
+
 MatcherDoStmt>hasBodyMatcherStmt> 
InnerMatcher
 Matches a 'for', 'while', 
'do while' statement or a function
 definition that has a given body.


Index: docs/LibASTMatchersReference.html
===
--- docs/LibASTMatchersReference.html
+++ docs/LibASTMatchersReference.html
@@ -1577,6 +1577,18 @@
 
 
 
+MatcherType>decltypeTypeMatcherDecltypeType>...
+Matches types nodes representing C++11 decltype() types.
+
+Given:
+  short i = 1;
+  int j = 42;
+  decltype(i + j) result = i + j;
+decltypeType() 
+  matches "decltype(i + j)"
+
+
+
 MatcherType>dependentSizedArrayTypeMatcherDependentSizedArrayType>...
 Matches C++ arrays whose size is a value-dependent expression.
 
@@ -5156,6 +5168,19 @@
 
 
 
+MatcherDecltypeType>hasUnderlyingTypeMatcherType>
+Matches DecltypeType nodes to find out the underlying type.
+
+Given
+  decltype(1) a = 1;
+  decltype(2.0) b = 2.0;
+decltypeType(hasUnderlyingType(isInteger()))
+  matches "auto a"
+
+Usable as: MatcherDecltypeType>
+
+
+
 MatcherDoStmt>hasBodyMatcherStmt> InnerMatcher
 Matches a 'for', 'while', 'do while' statement or a function
 definition that has a given body.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r338022 - [ASTMatchers] fix the missing documentation for new decltypeType matcher

2018-07-26 Thread Jonas Toth via cfe-commits
Author: jonastoth
Date: Thu Jul 26 06:02:05 2018
New Revision: 338022

URL: http://llvm.org/viewvc/llvm-project?rev=338022&view=rev
Log:
[ASTMatchers] fix the missing documentation for new decltypeType matcher

Summary: Regenerate the Matchers documentation, forgotten in the original patch.

Reviewers: alexfh, aaron.ballman

Reviewed By: aaron.ballman

Subscribers: cfe-commits

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

Modified:
cfe/trunk/docs/LibASTMatchersReference.html

Modified: cfe/trunk/docs/LibASTMatchersReference.html
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/LibASTMatchersReference.html?rev=338022&r1=338021&r2=338022&view=diff
==
--- cfe/trunk/docs/LibASTMatchersReference.html (original)
+++ cfe/trunk/docs/LibASTMatchersReference.html Thu Jul 26 06:02:05 2018
@@ -1577,6 +1577,18 @@ Example matches i[1].
 
 
 
+MatcherType>decltypeTypeMatcherDecltypeType>...
+Matches types nodes 
representing C++11 decltype() types.
+
+Given:
+  short i = 1;
+  int j = 42;
+  decltype(i + j) result = i + j;
+decltypeType() 
+  matches "decltype(i + j)"
+
+
+
 MatcherType>dependentSizedArrayTypeMatcherDependentSizedArrayType>...
 Matches C++ 
arrays whose size is a value-dependent expression.
 
@@ -5156,6 +5168,19 @@ declaration of class D.
 
 
 
+MatcherDecltypeType>hasUnderlyingTypeMatcherType>
+Matches 
DecltypeType nodes to find out the underlying type.
+
+Given
+  decltype(1) a = 1;
+  decltype(2.0) b = 2.0;
+decltypeType(hasUnderlyingType(isInteger()))
+  matches "auto a"
+
+Usable as: MatcherDecltypeType>
+
+
+
 MatcherDoStmt>hasBodyMatcherStmt> 
InnerMatcher
 Matches a 'for', 'while', 
'do while' statement or a function
 definition that has a given body.


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


r338024 - Allow thread safety annotation lock upgrading and downgrading.

2018-07-26 Thread Aaron Ballman via cfe-commits
Author: aaronballman
Date: Thu Jul 26 06:03:16 2018
New Revision: 338024

URL: http://llvm.org/viewvc/llvm-project?rev=338024&view=rev
Log:
Allow thread safety annotation lock upgrading and downgrading.

Patch thanks to Aaron Puchert!

Modified:
cfe/trunk/lib/Analysis/ThreadSafety.cpp
cfe/trunk/test/SemaCXX/warn-thread-safety-analysis.cpp

Modified: cfe/trunk/lib/Analysis/ThreadSafety.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/ThreadSafety.cpp?rev=338024&r1=338023&r2=338024&view=diff
==
--- cfe/trunk/lib/Analysis/ThreadSafety.cpp (original)
+++ cfe/trunk/lib/Analysis/ThreadSafety.cpp Thu Jul 26 06:03:16 2018
@@ -109,9 +109,7 @@ class FactSet;
 /// along with additional information, such as where it was acquired, whether
 /// it is exclusive or shared, etc.
 ///
-/// FIXME: this analysis does not currently support either re-entrant
-/// locking or lock "upgrading" and "downgrading" between exclusive and
-/// shared.
+/// FIXME: this analysis does not currently support re-entrant locking.
 class FactEntry : public CapabilityExpr {
 private:
   /// Exclusive or shared.
@@ -1737,8 +1735,7 @@ void BuildLockset::handleCall(Expr *Exp,
 }
   }
 
-  for(Attr *Atconst : D->attrs()) {
-auto *At = const_cast(Atconst);
+  for(const Attr *At : D->attrs()) {
 switch (At->getKind()) {
   // When we encounter a lock function, we need to add the lock to our
   // lockset.
@@ -1838,6 +1835,16 @@ void BuildLockset::handleCall(Expr *Exp,
 }
   }
 
+  // Remove locks first to allow lock upgrading/downgrading.
+  // FIXME -- should only fully remove if the attribute refers to 'this'.
+  bool Dtor = isa(D);
+  for (const auto &M : ExclusiveLocksToRemove)
+Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
+  for (const auto &M : SharedLocksToRemove)
+Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
+  for (const auto &M : GenericLocksToRemove)
+Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
+
   // Add locks.
   for (const auto &M : ExclusiveLocksToAdd)
 Analyzer->addLock(FSet, llvm::make_unique(
@@ -1864,16 +1871,6 @@ void BuildLockset::handleCall(Expr *Exp,
   Scp, MLoc, ExclusiveLocksToAdd, SharedLocksToAdd),
   CapDiagKind);
   }
-
-  // Remove locks.
-  // FIXME -- should only fully remove if the attribute refers to 'this'.
-  bool Dtor = isa(D);
-  for (const auto &M : ExclusiveLocksToRemove)
-Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
-  for (const auto &M : SharedLocksToRemove)
-Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
-  for (const auto &M : GenericLocksToRemove)
-Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
 }
 
 /// For unary operations which read and write a variable, we need to

Modified: cfe/trunk/test/SemaCXX/warn-thread-safety-analysis.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/warn-thread-safety-analysis.cpp?rev=338024&r1=338023&r2=338024&view=diff
==
--- cfe/trunk/test/SemaCXX/warn-thread-safety-analysis.cpp (original)
+++ cfe/trunk/test/SemaCXX/warn-thread-safety-analysis.cpp Thu Jul 26 06:03:16 
2018
@@ -22,8 +22,6 @@
 #define SHARED_LOCK_FUNCTION(...)   
__attribute__((acquire_shared_capability(__VA_ARGS__)))
 #define EXCLUSIVE_TRYLOCK_FUNCTION(...) 
__attribute__((try_acquire_capability(__VA_ARGS__)))
 #define SHARED_TRYLOCK_FUNCTION(...)
__attribute__((try_acquire_shared_capability(__VA_ARGS__)))
-#define EXCLUSIVE_UNLOCK_FUNCTION(...)  
__attribute__((release_capability(__VA_ARGS__)))
-#define SHARED_UNLOCK_FUNCTION(...) 
__attribute__((release_shared_capability(__VA_ARGS__)))
 #define EXCLUSIVE_LOCKS_REQUIRED(...)   
__attribute__((requires_capability(__VA_ARGS__)))
 #define SHARED_LOCKS_REQUIRED(...)  
__attribute__((requires_shared_capability(__VA_ARGS__)))
 #else
@@ -34,11 +32,11 @@
 #define SHARED_LOCK_FUNCTION(...)   
__attribute__((shared_lock_function(__VA_ARGS__)))
 #define EXCLUSIVE_TRYLOCK_FUNCTION(...) 
__attribute__((exclusive_trylock_function(__VA_ARGS__)))
 #define SHARED_TRYLOCK_FUNCTION(...)
__attribute__((shared_trylock_function(__VA_ARGS__)))
-#define EXCLUSIVE_UNLOCK_FUNCTION(...)  
__attribute__((unlock_function(__VA_ARGS__)))
-#define SHARED_UNLOCK_FUNCTION(...) 
__attribute__((unlock_function(__VA_ARGS__)))
 #define EXCLUSIVE_LOCKS_REQUIRED(...)   
__attribute__((exclusive_locks_required(__VA_ARGS__)))
 #define SHARED_LOCKS_REQUIRED(...)  
__attribute__((shared_locks_required(__VA_ARGS__)))
 #endif
+#define EXCLUSIVE_UNLOCK_FUNCTION(...)  
__attribute__((release_capability(__VA_ARGS__)))
+#define SHARED_UNLOCK_FUNCTION(...) 
__attribute__((release_shared_capability(__VA_ARGS__)))
 #define UNLOCK_FUNCTION(...)

[PATCH] D49355: Thread safety analysis: Allow lock upgrading and downgrading

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

I've commit in r338024, thank you for the patch!


Repository:
  rC Clang

https://reviews.llvm.org/D49355



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


[PATCH] D49838: [AST] Sink 'part of explicit cast' down into ImplicitCastExpr

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

2 small items, otherwise looks good.




Comment at: include/clang/AST/Expr.h:2824
 CastExprBits.Kind = kind;
-CastExprBits.PartOfExplicitCast = false;
 setBasePathSize(BasePathSize);

So, I'd prefer that this line get left in.  Removing this makes it the single 
unused item in CastExprBitfields, so leaving it uninitialized is likely a bad 
idea.  



Comment at: lib/Sema/SemaCast.cpp:97
   while ((CE = dyn_cast(CE->getSubExpr(
-CE->setIsPartOfExplicitCast(true);
+dyn_cast(CE)->setIsPartOfExplicitCast(true);
 }

I think I'd prefer just using a different variable in the 'while' loop to avoid 
the cast.  something like while((auto ICE =

That said, either way this isn't a dyn_cast, this would be just a cast (since 
we KNOW the type).


Repository:
  rC Clang

https://reviews.llvm.org/D49838



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


[clang-tools-extra] r338025 - [clang-tidy] Fix llvm.org/PR38315 (support type aliases in modernize-shrink-to-fit)

2018-07-26 Thread Alexander Kornienko via cfe-commits
Author: alexfh
Date: Thu Jul 26 06:13:54 2018
New Revision: 338025

URL: http://llvm.org/viewvc/llvm-project?rev=338025&view=rev
Log:
[clang-tidy] Fix llvm.org/PR38315 (support type aliases in 
modernize-shrink-to-fit)

Modified:
clang-tools-extra/trunk/clang-tidy/modernize/ShrinkToFitCheck.cpp
clang-tools-extra/trunk/test/clang-tidy/modernize-shrink-to-fit.cpp

Modified: clang-tools-extra/trunk/clang-tidy/modernize/ShrinkToFitCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/ShrinkToFitCheck.cpp?rev=338025&r1=338024&r2=338025&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/modernize/ShrinkToFitCheck.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/modernize/ShrinkToFitCheck.cpp Thu Jul 
26 06:13:54 2018
@@ -43,8 +43,8 @@ void ShrinkToFitCheck::registerMatchers(
 
   Finder->addMatcher(
   cxxMemberCallExpr(
-  on(hasType(namedDecl(
-  hasAnyName("std::basic_string", "std::deque", "std::vector",
+  on(hasType(hasCanonicalType(hasDeclaration(namedDecl(
+  hasAnyName("std::basic_string", "std::deque", 
"std::vector")),
   callee(cxxMethodDecl(hasName("swap"))),
   has(ignoringParenImpCasts(memberExpr(hasDescendant(CopyCtorCall,
   hasArgument(0, SwapParam.bind("ContainerToShrink")),

Modified: clang-tools-extra/trunk/test/clang-tidy/modernize-shrink-to-fit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/modernize-shrink-to-fit.cpp?rev=338025&r1=338024&r2=338025&view=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/modernize-shrink-to-fit.cpp 
(original)
+++ clang-tools-extra/trunk/test/clang-tidy/modernize-shrink-to-fit.cpp Thu Jul 
26 06:13:54 2018
@@ -72,3 +72,16 @@ void h() {
   // CHECK-FIXES: {{^  }}COPY_AND_SWAP_INT_VEC(v);{{$}}
 }
 
+void PR38315() {
+  typedef std::vector Vector;
+  Vector v;
+  Vector(v).swap(v);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: the shrink_to_fit method should
+  // CHECK-FIXES: {{^  }}v.shrink_to_fit();{{$}}
+
+  using Vector2 = std::vector;
+  Vector2 v2;
+  Vector2(v2).swap(v2);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: the shrink_to_fit method should
+  // CHECK-FIXES: {{^  }}v2.shrink_to_fit();{{$}}
+}


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


[PATCH] D49838: [AST] Sink 'part of explicit cast' down into ImplicitCastExpr

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

In https://reviews.llvm.org/D49838#1176622, @erichkeane wrote:

> 2 small items, otherwise looks good.


Thank you for taking a look!




Comment at: include/clang/AST/Expr.h:2824
 CastExprBits.Kind = kind;
-CastExprBits.PartOfExplicitCast = false;
 setBasePathSize(BasePathSize);

erichkeane wrote:
> So, I'd prefer that this line get left in.  Removing this makes it the single 
> unused item in CastExprBitfields, so leaving it uninitialized is likely a bad 
> idea.  
Aha, ok.
That will result in less ` CastExprBits.PartOfExplicitCast = false;` lines 
scattered across different constructors, too.



Comment at: include/clang/AST/Expr.h:2832
 : Expr(SC, Empty) {
 setBasePathSize(BasePathSize);
   }

Oh, i forget to init it here.



Comment at: lib/Sema/SemaCast.cpp:97
   while ((CE = dyn_cast(CE->getSubExpr(
-CE->setIsPartOfExplicitCast(true);
+dyn_cast(CE)->setIsPartOfExplicitCast(true);
 }

erichkeane wrote:
> I think I'd prefer just using a different variable in the 'while' loop to 
> avoid the cast.  something like while((auto ICE =
> 
> That said, either way this isn't a dyn_cast, this would be just a cast (since 
> we KNOW the type).
I was trying to avoid having one extra variable, which may confuse things.
Let's see maybe it's not that ugly..


Repository:
  rC Clang

https://reviews.llvm.org/D49838



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


[PATCH] D49844: [AST] Add a isActuallyImplicitCast() helper to the CastExpr class.

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

I'm not sure that this logic requires a separate function.  Since you've fixed 
the getIsPartOfExplicitCast logic correctly, it is pretty simple...




Comment at: include/clang/AST/Expr.h:2854
+  /// There are two global types of casts - implicit and explicit.
+  /// The Explicit cast is something that was directly written in the source
+  /// code. And the implicit cast is expected to be the opposite.

These two sentences are both sentence fragments and should likely be joined.

A suggested alternative?
"An explicit cast corresponds to a cast written in the source code, while an 
implicit cast is materialized for the purposes of automatic conversions.



Comment at: include/clang/AST/Expr.h:3024
+inline bool CastExpr::isActuallyImplicitCast() const {
+  // If this is an Implicit cast, is it *NOT* a part of Explicit cast group?
+  if (auto *IC = dyn_cast(this))

Are you asking or telling?  I'd prefer this comment not be here, or explain the 
logic.


Repository:
  rC Clang

https://reviews.llvm.org/D49844



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


[PATCH] D49114: [clang-tidy] Add a check for "magic numbers"

2018-07-26 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

I did not find any major issue :)




Comment at: clang-tidy/readability/MagicNumbersCheck.cpp:20
+bool isUsedToInitializeAConstant(
+const clang::ast_matchers::MatchFinder::MatchResult &Result,
+const clang::ast_type_traits::DynTypedNode &Node) {

You move the `using namespace clang::ast_matchers;` up to shorten your 
signature.
Adding a using for `ast_type_traits` is possible, too .



Comment at: clang-tidy/readability/MagicNumbersCheck.cpp:79
+bool MagicNumbersCheck::isConstant(
+const clang::ast_matchers::MatchFinder::MatchResult &Result,
+const clang::Expr &ExprResult) const {

is the `clang::` necessary? The code should be in that namespace already. I 
think shortening the really long type qualifier helps with readability. Similar 
on other places.



Comment at: docs/clang-tidy/checks/readability-magic-numbers.rst:55
+
+By default only `0`, `1` and `-1` integer values are accepted without a 
warning.
+This can be overridden with the :option:`IgnoredIntegerValues` option.  In 
addition,

-1 is not in the default list anymore.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49114



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


[PATCH] D48958: [clang][ubsan] Implicit Cast Sanitizer - integer truncation - clang part

2018-07-26 Thread Erich Keane via Phabricator via cfe-commits
erichkeane accepted this revision.
erichkeane added a comment.

1 Nit, otherwise LGTM.




Comment at: docs/UndefinedBehaviorSanitizer.rst:95
+ of bigger bit width to smaller bit width, if that results in data loss.
+ That is, if the demoted value, after casting back to the original width,
+ is not equal to the original value before the downcast. This issue may

I think the last 2 commas in this sentence are unnecessary?  


Repository:
  rC Clang

https://reviews.llvm.org/D48958



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


[PATCH] D45444: [clang-tidy] implement new check for const-correctness

2018-07-26 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

@aaron.ballman Are you missing something in this check/tests? I think i will 
remove the big comment with my thoughts on what has to be done, or do you think 
it would help for reference?

I would probably be able to finalize this week if there is no major issue, so 
it could be committed for the release.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D45444



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


[PATCH] D49729: [AST][1/4] Move the bit-fields from TagDecl, EnumDecl and RecordDecl into DeclContext

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



Comment at: include/clang/AST/Decl.h:
+
+  /// True if this is a C++11 scoped enumeration.
+  void setScopedUsingClassTag(bool ScopedUCT = true) {

This is the same comment as 3330, perhaps a copy/paste error?



Comment at: lib/AST/Decl.cpp:3896
+  assert(Scoped || !ScopedUsingClassTag);
+  IntegerType = (const Type *)nullptr;
+  setNumPositiveBits(0);

This cast is jarring.  C-Style casts shouldn't be used (i realize it is in the 
source), and I'm not sure it is necessary here.  Can you try removing the cast 
entirely?


Repository:
  rC Clang

https://reviews.llvm.org/D49729



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


[clang-tools-extra] r338028 - [clangd] Fix unit tests for Dex

2018-07-26 Thread Kirill Bobyrev via cfe-commits
Author: omtcyfz
Date: Thu Jul 26 07:00:00 2018
New Revision: 338028

URL: http://llvm.org/viewvc/llvm-project?rev=338028&view=rev
Log:
[clangd] Fix unit tests for Dex

Iterators took temporary objects in constructors, objects were
invalidated when built with recent Clang which resulted in crashes.

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

Modified: clang-tools-extra/trunk/unittests/clangd/DexIndexTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/DexIndexTests.cpp?rev=338028&r1=338027&r2=338028&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/DexIndexTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/DexIndexTests.cpp Thu Jul 26 
07:00:00 2018
@@ -24,7 +24,8 @@ namespace dex {
 using ::testing::ElementsAre;
 
 TEST(DexIndexIterators, DocumentIterator) {
-  auto DocIterator = create({4, 7, 8, 20, 42, 100});
+  const PostingList L = {4, 7, 8, 20, 42, 100};
+  auto DocIterator = create(L);
 
   EXPECT_EQ(DocIterator->peek(), 4U);
   EXPECT_EQ(DocIterator->reachedEnd(), false);
@@ -194,12 +195,18 @@ TEST(DexIndexIterators, QueryTree) {
   //  |1, 3, 5, 8, 9| |1, 5, 7, 9|   |Empty||0, 5||0, 1, 5|
   //  +-+ +--+   +-++++---+
 
+  const PostingList L0 = {1, 3, 5, 8, 9};
+  const PostingList L1 = {1, 5, 7, 9};
+  const PostingList L2 = {0, 5};
+  const PostingList L3 = {0, 1, 5};
+  const PostingList L4;
+
   // Root of the query tree: [1, 5]
   auto Root = createAnd({
   // Lower And Iterator: [1, 5, 9]
-  createAnd({create({1, 3, 5, 8, 9}), create({1, 5, 7, 9})}),
+  createAnd({create(L0), create(L1)}),
   // Lower Or Iterator: [0, 1, 5]
-  createOr({create({0, 5}), create({0, 1, 5}), create({})}),
+  createOr({create(L2), create(L3), create(L4)}),
   });
 
   EXPECT_EQ(Root->reachedEnd(), false);
@@ -218,12 +225,18 @@ TEST(DexIndexIterators, QueryTree) {
 }
 
 TEST(DexIndexIterators, StringRepresentation) {
-  EXPECT_EQ(llvm::to_string(*(create({4, 7, 8, 20, 42, 100}))),
-"[4, 7, 8, 20, 42, 100]");
+  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};
+  const PostingList L5;
+
+  EXPECT_EQ(llvm::to_string(*(create(L0))), "[4, 7, 8, 20, 42, 100]");
 
   auto Nested = createAnd({
-  createAnd({create({1, 3, 5, 8, 9}), create({1, 5, 7, 9})}),
-  createOr({create({0, 5}), create({0, 1, 5}), create({})}),
+  createAnd({create(L1), create(L2)}),
+  createOr({create(L3), create(L4), create(L5)}),
   });
 
   EXPECT_EQ(llvm::to_string(*Nested),


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


[PATCH] D49800: [clang-tidy: modernize] modernize-redundant-void-arg crashes when a function body is in a macro

2018-07-26 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh requested changes to this revision.
alexfh added a comment.
This revision now requires changes to proceed.

Thank you for working on this!




Comment at: clang-tidy/modernize/RedundantVoidArgCheck.cpp:241
+SourceLocation End =
+Lambda->getBody()->getLocStart().isMacroID()
+? Result.SourceManager

Let's pull `Lambda->getBody()->getLocStart()` to a variable to avoid repetition.



Comment at: clang-tidy/modernize/RedundantVoidArgCheck.cpp:242-244
+? Result.SourceManager
+  
->getImmediateExpansionRange(Lambda->getBody()->getLocStart())
+  .getBegin()

The fix looks limited to the specific test case.  Let's try other cases (see 
the comment below).



Comment at: test/clang-tidy/modernize-redundant-void-arg.cpp:454
+ // CHECK-FIXES: []()BODY;
+}

I'd like to see more tests here with different macro-related cases. These come 
to mind, but if you come up with more distinct cases, that would be even better:

  #define LAMBDA1 [](void){}
  (void)LAMBDA1;
  #define LAMBDA2 [](void)BODY
  (void)LAMBDA2;
  #define LAMBDA3(captures, args, body) [captures](args){body}
  (void)LAMBDA3(=, void, BODY);
  #define LAMBDA4(captures, args, body) captures args body
  (void)LAMBDA4([], (void), BODY);
  #define LAMBDAS1 \
(void)LAMBDA1; \
(void)LAMBDA2; \
(void)LAMBDA3(=, void, BODY); \
(void)LAMBDA4([], (void), BODY)

  LAMBDAS1;
  #define WRAP(...) __VA_ARGS__
  WRAP((void)WRAP(WRAP(LAMBDA4(WRAP([]), WRAP((void)), WRAP(BODY);
  (void)WRAP([](void){});




Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49800



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


[PATCH] D49852: [Modules] Do not emit relocation error when -fno-validate-pch is set

2018-07-26 Thread Yuka Takahashi via Phabricator via cfe-commits
yamaguchi created this revision.
yamaguchi added reviewers: rsmith, dblaikie, v.g.vassilev.

Clang emits error when implicit modules was relocated from the
first build directory. However this was biting our usecase where we copy
the contents of build directory to another directory in order to
distribute.


https://reviews.llvm.org/D49852

Files:
  clang/lib/Serialization/ASTReader.cpp
  clang/test/Modules/resolution-change.m


Index: clang/test/Modules/resolution-change.m
===
--- clang/test/Modules/resolution-change.m
+++ clang/test/Modules/resolution-change.m
@@ -21,6 +21,8 @@
 // RUN: not %clang_cc1 -fmodules -fimplicit-module-maps 
-fmodules-cache-path=%t -I %S/Inputs/modules-with-same-name/DependsOnA -I 
%S/Inputs/modules-with-same-name/path2/A -include-pch %t-A.pch %s -fsyntax-only 
2>&1 | FileCheck -check-prefix=CHECK-WRONGA %s
 // CHECK-WRONGA: module 'A' was built in directory 
'{{.*Inputs.modules-with-same-name.path1.A}}' but now resides in directory 
'{{.*Inputs.modules-with-same-name.path2.A}}'
 
+// RUN: %clang_cc1 -fno-validate-pch -fmodules -fimplicit-module-maps 
-fmodules-cache-path=%t -I %S/Inputs/modules-with-same-name/DependsOnA -I 
%S/Inputs/modules-with-same-name/path2/A -include-pch %t-A.pch %s -fsyntax-only
+
 #ifndef HEADER
 #define HEADER
 @import DependsOnA;
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -2632,7 +2632,9 @@
   if (M && M->Directory) {
 // If we're implicitly loading a module, the base directory can't
 // change between the build and use.
-if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
+// Don't emit module relocation error if we have -fno-validate-pch
+if (!PP.getPreprocessorOpts().DisablePCHValidation &&
+F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
   const DirectoryEntry *BuildDir =
   PP.getFileManager().getDirectory(Blob);
   if (!BuildDir || BuildDir != M->Directory) {
@@ -3602,7 +3604,8 @@
 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
-if (!ModMap) {
+// Don't emit module relocation error if we have -fno-validate-pch
+if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) {
   assert(ImportedBy && "top-level import should be verified");
   if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
 if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
@@ -5039,7 +5042,9 @@
 
   if (!ParentModule) {
 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
-  if (CurFile != F.File) {
+  // Don't emit module relocation error if we have -fno-validate-pch
+  if (!PP.getPreprocessorOpts().DisablePCHValidation &&
+  CurFile != F.File) {
 if (!Diags.isDiagnosticInFlight()) {
   Diag(diag::err_module_file_conflict)
 << CurrentModule->getTopLevelModuleName()


Index: clang/test/Modules/resolution-change.m
===
--- clang/test/Modules/resolution-change.m
+++ clang/test/Modules/resolution-change.m
@@ -21,6 +21,8 @@
 // RUN: not %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I %S/Inputs/modules-with-same-name/DependsOnA -I %S/Inputs/modules-with-same-name/path2/A -include-pch %t-A.pch %s -fsyntax-only 2>&1 | FileCheck -check-prefix=CHECK-WRONGA %s
 // CHECK-WRONGA: module 'A' was built in directory '{{.*Inputs.modules-with-same-name.path1.A}}' but now resides in directory '{{.*Inputs.modules-with-same-name.path2.A}}'
 
+// RUN: %clang_cc1 -fno-validate-pch -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I %S/Inputs/modules-with-same-name/DependsOnA -I %S/Inputs/modules-with-same-name/path2/A -include-pch %t-A.pch %s -fsyntax-only
+
 #ifndef HEADER
 #define HEADER
 @import DependsOnA;
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -2632,7 +2632,9 @@
   if (M && M->Directory) {
 // If we're implicitly loading a module, the base directory can't
 // change between the build and use.
-if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
+// Don't emit module relocation error if we have -fno-validate-pch
+if (!PP.getPreprocessorOpts().DisablePCHValidation &&
+F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
   const DirectoryEntry *BuildDir =
   PP.getFileManager().getDirectory(Blob);
   if (!BuildDir || BuildDir != M

[PATCH] D46190: For a used declaration, mark any associated usings as referenced.

2018-07-26 Thread Carlos Alberto Enciso via Phabricator via cfe-commits
CarlosAlbertoEnciso added a comment.

@rsmith & @probinson,

Is there anything I can add to this patch in order to submit it?
This patch is blocking the review https://reviews.llvm.org/D44826 which is 
already approved.

Thanks very much.




Comment at: lib/Sema/SemaDeclCXX.cpp:15515
+
+// Mark the alias declaration and any associated chain as referenced.
+void Sema::MarkNamespaceAliasReferenced(NamedDecl *ND) {

probinson wrote:
> This should use `///` to be  picked up by doxygen.
Uploaded a new patch that contains that change.


https://reviews.llvm.org/D46190



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


[PATCH] D49838: [AST] Sink 'part of explicit cast' down into ImplicitCastExpr

2018-07-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added inline comments.



Comment at: lib/Sema/SemaCast.cpp:97
   while ((CE = dyn_cast(CE->getSubExpr(
-CE->setIsPartOfExplicitCast(true);
+dyn_cast(CE)->setIsPartOfExplicitCast(true);
 }

lebedev.ri wrote:
> erichkeane wrote:
> > I think I'd prefer just using a different variable in the 'while' loop to 
> > avoid the cast.  something like while((auto ICE =
> > 
> > That said, either way this isn't a dyn_cast, this would be just a cast 
> > (since we KNOW the type).
> I was trying to avoid having one extra variable, which may confuse things.
> Let's see maybe it's not that ugly..
Indeed, `cast<>` should be used.
But trying to avoid this cast at all results in uglier code, so let's not.
(I need to call `getSubExpr()` on this new `ImplicitCastExpr`, so i'd need to 
maintain two variables, etc...)


Repository:
  rC Clang

https://reviews.llvm.org/D49838



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


[PATCH] D49838: [AST] Sink 'part of explicit cast' down into ImplicitCastExpr

2018-07-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri updated this revision to Diff 157483.
lebedev.ri marked 5 inline comments as done.
lebedev.ri added a comment.

Address @erichkeane review notes.


Repository:
  rC Clang

https://reviews.llvm.org/D49838

Files:
  include/clang/AST/Expr.h
  include/clang/AST/Stmt.h
  lib/AST/ASTDumper.cpp
  lib/Sema/SemaCast.cpp
  lib/Serialization/ASTReaderStmt.cpp
  lib/Serialization/ASTWriterStmt.cpp

Index: lib/Serialization/ASTWriterStmt.cpp
===
--- lib/Serialization/ASTWriterStmt.cpp
+++ lib/Serialization/ASTWriterStmt.cpp
@@ -665,7 +665,6 @@
   Record.push_back(E->path_size());
   Record.AddStmt(E->getSubExpr());
   Record.push_back(E->getCastKind()); // FIXME: stable encoding
-  Record.push_back(E->getIsPartOfExplicitCast());
 
   for (CastExpr::path_iterator
  PI = E->path_begin(), PE = E->path_end(); PI != PE; ++PI)
@@ -714,6 +713,7 @@
 
 void ASTStmtWriter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
   VisitCastExpr(E);
+  Record.push_back(E->getIsPartOfExplicitCast());
 
   if (E->path_size() == 0)
 AbbrevToUse = Writer.getExprImplicitCastAbbrev();
Index: lib/Serialization/ASTReaderStmt.cpp
===
--- lib/Serialization/ASTReaderStmt.cpp
+++ lib/Serialization/ASTReaderStmt.cpp
@@ -723,7 +723,6 @@
   assert(NumBaseSpecs == E->path_size());
   E->setSubExpr(Record.readSubExpr());
   E->setCastKind((CastKind)Record.readInt());
-  E->setIsPartOfExplicitCast(Record.readInt());
   CastExpr::path_iterator BaseI = E->path_begin();
   while (NumBaseSpecs--) {
 auto *BaseSpec = new (Record.getContext()) CXXBaseSpecifier;
@@ -770,6 +769,7 @@
 
 void ASTStmtReader::VisitImplicitCastExpr(ImplicitCastExpr *E) {
   VisitCastExpr(E);
+  E->setIsPartOfExplicitCast(Record.readInt());
 }
 
 void ASTStmtReader::VisitExplicitCastExpr(ExplicitCastExpr *E) {
Index: lib/Sema/SemaCast.cpp
===
--- lib/Sema/SemaCast.cpp
+++ lib/Sema/SemaCast.cpp
@@ -94,7 +94,7 @@
   // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE
   // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched.
   while ((CE = dyn_cast(CE->getSubExpr(
-CE->setIsPartOfExplicitCast(true);
+cast(CE)->setIsPartOfExplicitCast(true);
 }
 
 /// Complete an apparently-successful cast operation that yields
Index: lib/AST/ASTDumper.cpp
===
--- lib/AST/ASTDumper.cpp
+++ lib/AST/ASTDumper.cpp
@@ -521,6 +521,7 @@
 // Exprs
 void VisitExpr(const Expr *Node);
 void VisitCastExpr(const CastExpr *Node);
+void VisitImplicitCastExpr(const ImplicitCastExpr *Node);
 void VisitDeclRefExpr(const DeclRefExpr *Node);
 void VisitPredefinedExpr(const PredefinedExpr *Node);
 void VisitCharacterLiteral(const CharacterLiteral *Node);
@@ -2117,7 +2118,10 @@
   }
   dumpBasePath(OS, Node);
   OS << ">";
+}
 
+void ASTDumper::VisitImplicitCastExpr(const ImplicitCastExpr *Node) {
+  VisitCastExpr(Node);
   if (Node->getIsPartOfExplicitCast())
 OS << " part_of_explicit_cast";
 }
Index: include/clang/AST/Stmt.h
===
--- include/clang/AST/Stmt.h
+++ include/clang/AST/Stmt.h
@@ -198,11 +198,12 @@
 
   class CastExprBitfields {
 friend class CastExpr;
+friend class ImplicitCastExpr;
 
 unsigned : NumExprBits;
 
 unsigned Kind : 6;
-unsigned PartOfExplicitCast : 1;
+unsigned PartOfExplicitCast : 1; // Only representable for ImplicitCastExpr.
 unsigned BasePathSize : 32 - 6 - 1 - NumExprBits;
   };
 
Index: include/clang/AST/Expr.h
===
--- include/clang/AST/Expr.h
+++ include/clang/AST/Expr.h
@@ -2829,20 +2829,14 @@
   /// Construct an empty cast.
   CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
 : Expr(SC, Empty) {
+CastExprBits.PartOfExplicitCast = false;
 setBasePathSize(BasePathSize);
   }
 
 public:
   CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
   void setCastKind(CastKind K) { CastExprBits.Kind = K; }
 
-  bool getIsPartOfExplicitCast() const {
-return CastExprBits.PartOfExplicitCast;
-  }
-  void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
-CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
-  }
-
   static const char *getCastKindName(CastKind CK);
   const char *getCastKindName() const { return getCastKindName(getCastKind()); }
 
@@ -2931,6 +2925,13 @@
 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
   }
 
+  bool getIsPartOfExplicitCast() const {
+return CastExprBits.PartOfExplicitCast;
+  }
+  void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
+CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
+  }
+
   static ImplicitCastExpr *Create(const ASTContext &Context, QualT

[PATCH] D49844: [AST] Add a isActuallyImplicitCast() helper to the CastExpr class.

2018-07-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri updated this revision to Diff 157484.
lebedev.ri marked 2 inline comments as done.
lebedev.ri added a comment.

Comment fine-tuning.

In https://reviews.llvm.org/D49844#1176639, @erichkeane wrote:

> I'm not sure that this logic requires a separate function.  Since you've 
> fixed the getIsPartOfExplicitCast logic correctly, it is pretty simple...


Certainly. I can **totally** inline it into the caller,
but i *think* @rsmith suggested that such functionality should be present, so 
i'll wait for him to comment.


Repository:
  rC Clang

https://reviews.llvm.org/D49844

Files:
  include/clang/AST/Expr.h


Index: include/clang/AST/Expr.h
===
--- include/clang/AST/Expr.h
+++ include/clang/AST/Expr.h
@@ -2852,6 +2852,15 @@
 return const_cast(this)->getSubExprAsWritten();
   }
 
+  /// There are two global types of casts - implicit and explicit. An explicit
+  /// cast corresponds to a cast written in the source code, while an implicit
+  /// cast is materialized for the purposes of automatic conversions.
+  /// But in AST, some explicit casts are represented as ExplicitCastExpr plus
+  /// one or more immediate ImplicitCastExpr (i.e. with nothing inbetween).
+  /// This function returns false if this cast is either an ExplicitCastExpr
+  /// itself, or it is a part of the ExplicitCastExpr group.
+  bool isActuallyImplicitCast() const;
+
   /// If this cast applies a user-defined conversion, retrieve the conversion
   /// function that it invokes.
   NamedDecl *getConversionFunction() const;
@@ -3009,6 +3018,13 @@
   }
 };
 
+inline bool CastExpr::isActuallyImplicitCast() const {
+  if (auto *IC = dyn_cast(this))
+return !IC->getIsPartOfExplicitCast();
+  assert(isa(this) && "it has to be Explicit cast then.");
+  return false; // Explicit cast is clearly not an Implicit cast.
+}
+
 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
 /// cast in C++ (C++ [expr.cast]), which uses the syntax
 /// (Type)expr. For example: @c (int)f.


Index: include/clang/AST/Expr.h
===
--- include/clang/AST/Expr.h
+++ include/clang/AST/Expr.h
@@ -2852,6 +2852,15 @@
 return const_cast(this)->getSubExprAsWritten();
   }
 
+  /// There are two global types of casts - implicit and explicit. An explicit
+  /// cast corresponds to a cast written in the source code, while an implicit
+  /// cast is materialized for the purposes of automatic conversions.
+  /// But in AST, some explicit casts are represented as ExplicitCastExpr plus
+  /// one or more immediate ImplicitCastExpr (i.e. with nothing inbetween).
+  /// This function returns false if this cast is either an ExplicitCastExpr
+  /// itself, or it is a part of the ExplicitCastExpr group.
+  bool isActuallyImplicitCast() const;
+
   /// If this cast applies a user-defined conversion, retrieve the conversion
   /// function that it invokes.
   NamedDecl *getConversionFunction() const;
@@ -3009,6 +3018,13 @@
   }
 };
 
+inline bool CastExpr::isActuallyImplicitCast() const {
+  if (auto *IC = dyn_cast(this))
+return !IC->getIsPartOfExplicitCast();
+  assert(isa(this) && "it has to be Explicit cast then.");
+  return false; // Explicit cast is clearly not an Implicit cast.
+}
+
 /// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
 /// cast in C++ (C++ [expr.cast]), which uses the syntax
 /// (Type)expr. For example: @c (int)f.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D49844: [AST] Add a isActuallyImplicitCast() helper to the CastExpr class.

2018-07-26 Thread Erich Keane via Phabricator via cfe-commits
erichkeane accepted this revision.
erichkeane added a comment.
This revision is now accepted and ready to land.

If @rsmith requested this, I'm fine with it then.


Repository:
  rC Clang

https://reviews.llvm.org/D49844



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


r338032 - [OPENMP] Force OpenMP 4.5 when compiling for offloading.

2018-07-26 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Thu Jul 26 08:17:38 2018
New Revision: 338032

URL: http://llvm.org/viewvc/llvm-project?rev=338032&view=rev
Log:
[OPENMP] Force OpenMP 4.5 when compiling for offloading.

If the user requested compilation for OpenMP with the offloading
support, force the version of the OpenMP standard to 4.5 by default.

Modified:
cfe/trunk/lib/Driver/ToolChains/Clang.cpp
cfe/trunk/lib/Frontend/CompilerInvocation.cpp
cfe/trunk/test/OpenMP/driver.c

Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=338032&r1=338031&r2=338032&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Thu Jul 26 08:17:38 2018
@@ -4698,7 +4698,7 @@ void Clang::ConstructJob(Compilation &C,
 
   // For all the host OpenMP offloading compile jobs we need to pass the 
targets
   // information using -fopenmp-targets= option.
-  if (isa(JA) && JA.isHostOffloading(Action::OFK_OpenMP)) {
+  if (JA.isHostOffloading(Action::OFK_OpenMP)) {
 SmallString<128> TargetInfo("-fopenmp-targets=");
 
 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);

Modified: cfe/trunk/lib/Frontend/CompilerInvocation.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/CompilerInvocation.cpp?rev=338032&r1=338031&r2=338032&view=diff
==
--- cfe/trunk/lib/Frontend/CompilerInvocation.cpp (original)
+++ cfe/trunk/lib/Frontend/CompilerInvocation.cpp Thu Jul 26 08:17:38 2018
@@ -2594,13 +2594,15 @@ static void ParseLangArgs(LangOptions &O
   Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
   Opts.OpenMPIsDevice =
   Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
+  bool IsTargetSpecified =
+  Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
 
   if (Opts.OpenMP || Opts.OpenMPSimd) {
-if (int Version =
-getLastArgIntValue(Args, OPT_fopenmp_version_EQ,
-   IsSimdSpecified ? 45 : Opts.OpenMP, Diags))
+if (int Version = getLastArgIntValue(
+Args, OPT_fopenmp_version_EQ,
+(IsSimdSpecified || IsTargetSpecified) ? 45 : Opts.OpenMP, Diags))
   Opts.OpenMP = Version;
-else if (IsSimdSpecified)
+else if (IsSimdSpecified || IsTargetSpecified)
   Opts.OpenMP = 45;
 // Provide diagnostic when a given target is not expected to be an OpenMP
 // device or host.

Modified: cfe/trunk/test/OpenMP/driver.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/OpenMP/driver.c?rev=338032&r1=338031&r2=338032&view=diff
==
--- cfe/trunk/test/OpenMP/driver.c (original)
+++ cfe/trunk/test/OpenMP/driver.c Thu Jul 26 08:17:38 2018
@@ -1,3 +1,4 @@
+// REQUIRES: x86-registered-target
 // Test that by default -fnoopenmp-use-tls is passed to frontend.
 //
 // RUN: %clang %s -### -o %t.o 2>&1 -fopenmp=libomp | FileCheck 
--check-prefix=CHECK-DEFAULT %s
@@ -23,7 +24,9 @@
 
 // RUN: %clang %s -c -E -dM -fopenmp=libomp -fopenmp-version=45 | FileCheck 
--check-prefix=CHECK-45-VERSION %s
 // RUN: %clang %s -c -E -dM -fopenmp=libomp -fopenmp-simd | FileCheck 
--check-prefix=CHECK-45-VERSION %s
+// RUN: %clang %s -c -E -dM -fopenmp=libomp 
-fopenmp-targets=x86_64-unknown-unknown -o - | FileCheck 
--check-prefix=CHECK-45-VERSION --check-prefix=CHECK-45-VERSION2 %s
 // CHECK-45-VERSION: #define _OPENMP 201511
+// CHECK-45-VERSION2: #define _OPENMP 201511
 
 // RUN: %clang %s -c -E -dM -fopenmp-version=1 | FileCheck 
--check-prefix=CHECK-VERSION %s
 // RUN: %clang %s -c -E -dM -fopenmp-version=31 | FileCheck 
--check-prefix=CHECK-VERSION %s


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


[PATCH] D49725: [OpenCL] Forbid size dependent types used as kernel arguments

2018-07-26 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl accepted this revision.
yaxunl added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks!


Repository:
  rC Clang

https://reviews.llvm.org/D49725



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


[PATCH] D48958: [clang][ubsan] Implicit Cast Sanitizer - integer truncation - clang part

2018-07-26 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: docs/UndefinedBehaviorSanitizer.rst:93-97
+  -  ``-fsanitize=implicit-integer-truncation``: Implicit cast from integer
+ of bigger bit width to smaller bit width, if that results in data loss.
+ That is, if the demoted value, after casting back to the original width,
+ is not equal to the original value before the downcast. This issue may
+ often be caused by an implicit integer conversions.

How about: `Implicit cast from a value of integral type which results in data 
loss where the demoted value, when cast back to the original type, would have a 
different value than the original. This issue may be caused by an implicit 
conversion.`


Repository:
  rC Clang

https://reviews.llvm.org/D48958



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


[PATCH] D48958: [clang][ubsan] Implicit Cast Sanitizer - integer truncation - clang part

2018-07-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri updated this revision to Diff 157498.
lebedev.ri marked 2 inline comments as done.
lebedev.ri added a comment.

Small rewording in `docs/UndefinedBehaviorSanitizer.rst` thanks to @erichkeane 
& @aaron.ballman!


Repository:
  rC Clang

https://reviews.llvm.org/D48958

Files:
  docs/ReleaseNotes.rst
  docs/UndefinedBehaviorSanitizer.rst
  include/clang/Basic/Sanitizers.def
  include/clang/Basic/Sanitizers.h
  lib/CodeGen/CGExprScalar.cpp
  lib/CodeGen/CodeGenFunction.h
  lib/Driver/SanitizerArgs.cpp
  lib/Driver/ToolChain.cpp
  test/CodeGen/catch-implicit-integer-truncations.c
  test/CodeGenCXX/catch-implicit-integer-truncations.cpp
  test/Driver/fsanitize.c

Index: test/Driver/fsanitize.c
===
--- test/Driver/fsanitize.c
+++ test/Driver/fsanitize.c
@@ -31,6 +31,21 @@
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=integer %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-INTEGER -implicit-check-not="-fsanitize-address-use-after-scope"
 // CHECK-INTEGER: "-fsanitize={{((signed-integer-overflow|unsigned-integer-overflow|integer-divide-by-zero|shift-base|shift-exponent),?){5}"}}
 
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=implicit-cast %s -### 2>&1 | FileCheck %s --check-prefixes=CHECK-IMPLICIT-CAST,CHECK-IMPLICIT-CAST-RECOVER
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=implicit-cast -fsanitize-recover=implicit-cast %s -### 2>&1 | FileCheck %s --check-prefixes=CHECK-IMPLICIT-CAST,CHECK-IMPLICIT-CAST-RECOVER
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=implicit-cast -fno-sanitize-recover=implicit-cast %s -### 2>&1 | FileCheck %s --check-prefixes=CHECK-IMPLICIT-CAST,CHECK-IMPLICIT-CAST-NORECOVER
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=implicit-cast -fsanitize-trap=implicit-cast %s -### 2>&1 | FileCheck %s --check-prefixes=CHECK-IMPLICIT-CAST,CHECK-IMPLICIT-CAST-TRAP
+// CHECK-IMPLICIT-CAST: "-fsanitize={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-RECOVER: "-fsanitize-recover={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-RECOVER-NOT: "-fno-sanitize-recover={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-RECOVER-NOT: "-fsanitize-trap={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-NORECOVER-NOT: "-fno-sanitize-recover={{((implicit-integer-truncation),?){1}"}} // ???
+// CHECK-IMPLICIT-CAST-NORECOVER-NOT: "-fsanitize-recover={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-NORECOVER-NOT: "-fsanitize-trap={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-TRAP: "-fsanitize-trap={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-TRAP-NOT: "-fsanitize-recover={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-TRAP-NOT: "-fno-sanitize-recover={{((implicit-integer-truncation),?){1}"}}
+
 // RUN: %clang -fsanitize=bounds -### -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix=CHECK-BOUNDS
 // CHECK-BOUNDS: "-fsanitize={{((array-bounds|local-bounds),?){2}"}}
 
Index: test/CodeGenCXX/catch-implicit-integer-truncations.cpp
===
--- /dev/null
+++ test/CodeGenCXX/catch-implicit-integer-truncations.cpp
@@ -0,0 +1,256 @@
+// RUN: %clang_cc1 -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefix=CHECK
+// RUN: %clang_cc1 -fsanitize=implicit-integer-truncation -fno-sanitize-recover=implicit-integer-truncation -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-ANYRECOVER,CHECK-SANITIZE-NORECOVER
+// RUN: %clang_cc1 -fsanitize=implicit-integer-truncation -fsanitize-recover=implicit-integer-truncation -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-ANYRECOVER,CHECK-SANITIZE-RECOVER
+// RUN: %clang_cc1 -fsanitize=implicit-integer-truncation -fsanitize-trap=implicit-integer-truncation -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-TRAP
+
+extern "C" { // Disable name mangling.
+
+// == //
+// Check that explicit cast does not interfere with implicit cast
+// == //
+// These contain one implicit truncating cast, and one explicit truncating cast.
+// We want to make sure that we still diagnose the implicit cast.
+
+// Implicit truncation after explicit truncation.
+// CHECK-LABEL: @explicit_cast_interference0
+unsigned char explicit_cast_interference0(unsigned int c) {
+  // CHECK-SANITIZE: %[[ANYEXT:.*]] = zext i8 %[[DST:.*]] to i16, !nosanitize
+  // CHECK-SANITIZE: call
+  // CHECK-SANITIZE-NOT: call
+  // CHECK: }
+  return (unsigned short)c;
+}
+
+// Implicit truncation before explicit truncation.
+// CHECK-LABEL: @explicit_cast_interference1
+unsigned char explicit_cast_in

[PATCH] D48958: [clang][ubsan] Implicit Cast Sanitizer - integer truncation - clang part

2018-07-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added inline comments.



Comment at: docs/UndefinedBehaviorSanitizer.rst:93-97
+  -  ``-fsanitize=implicit-integer-truncation``: Implicit cast from integer
+ of bigger bit width to smaller bit width, if that results in data loss.
+ That is, if the demoted value, after casting back to the original width,
+ is not equal to the original value before the downcast. This issue may
+ often be caused by an implicit integer conversions.

aaron.ballman wrote:
> How about: `Implicit cast from a value of integral type which results in data 
> loss where the demoted value, when cast back to the original type, would have 
> a different value than the original. This issue may be caused by an implicit 
> conversion.`
Thank you!


Repository:
  rC Clang

https://reviews.llvm.org/D48958



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


[PATCH] D49736: [Basic] Emit warning flag suggestion only in case there's existing flag *similar* to the unknown one

2018-07-26 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

Sounds good


Repository:
  rC Clang

https://reviews.llvm.org/D49736



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


[PATCH] D49523: [clangd] Add support for per-file override compilation command

2018-07-26 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

In https://reviews.llvm.org/D49523#1174627, @ilya-biryukov wrote:

> In https://reviews.llvm.org/D49523#1174086, @arphaman wrote:
>
> > We actually need both mechanisms. I posted the didChangeConfiguration 
> > extension to https://reviews.llvm.org/D49758.
>
>
> Why do we need both? Can we have only the one from 
> https://reviews.llvm.org/D49758 and send two requests (compile command 
> changed for file 'X' + didOpen('X')) whenever a new file gets added?


The didChangeConfiguration command would re-parse all the open documents, which 
is something we want to avoid. I guess one solution is to avoid reparsing 
anything when the updated file is not in the database in the first place. I'll 
work on that.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49523



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


[PATCH] D49523: [clangd] Add support for per-file override compilation command

2018-07-26 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman abandoned this revision.
arphaman added a comment.

Abandoned in favor of https://reviews.llvm.org/D49758 (will update it today).


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49523



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


[PATCH] D48903: [VirtualFileSystem] InMemoryFileSystem::status: Return a Status with the requested name

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

LGTM


Repository:
  rC Clang

https://reviews.llvm.org/D48903



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


[clang-tools-extra] r338037 - [clangd] Use 'const Twine&' instead of 'Twine'. NFC

2018-07-26 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Thu Jul 26 09:13:52 2018
New Revision: 338037

URL: http://llvm.org/viewvc/llvm-project?rev=338037&view=rev
Log:
[clangd] Use 'const Twine&' instead of 'Twine'. NFC

To fix clang-tidy warning

Modified:
clang-tools-extra/trunk/clangd/Threading.cpp
clang-tools-extra/trunk/clangd/Threading.h

Modified: clang-tools-extra/trunk/clangd/Threading.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Threading.cpp?rev=338037&r1=338036&r2=338037&view=diff
==
--- clang-tools-extra/trunk/clangd/Threading.cpp (original)
+++ clang-tools-extra/trunk/clangd/Threading.cpp Thu Jul 26 09:13:52 2018
@@ -50,7 +50,7 @@ bool AsyncTaskRunner::wait(Deadline D) c
   [&] { return InFlightTasks == 0; });
 }
 
-void AsyncTaskRunner::runAsync(llvm::Twine Name,
+void AsyncTaskRunner::runAsync(const llvm::Twine &Name,
llvm::unique_function Action) {
   {
 std::lock_guard Lock(Mutex);

Modified: clang-tools-extra/trunk/clangd/Threading.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Threading.h?rev=338037&r1=338036&r2=338037&view=diff
==
--- clang-tools-extra/trunk/clangd/Threading.h (original)
+++ clang-tools-extra/trunk/clangd/Threading.h Thu Jul 26 09:13:52 2018
@@ -108,7 +108,7 @@ public:
   void wait() const { (void)wait(Deadline::infinity()); }
   LLVM_NODISCARD bool wait(Deadline D) const;
   // The name is used for tracing and debugging (e.g. to name a spawned 
thread).
-  void runAsync(llvm::Twine Name, llvm::unique_function Action);
+  void runAsync(const llvm::Twine &Name, llvm::unique_function Action);
 
 private:
   mutable std::mutex Mutex;


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


[PATCH] D49862: [clang-tidy] Fix a crash in fuchsia-multiple-inheritance

2018-07-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added reviewers: juliehockett, ioeric, hokein, aaron.ballman.
Herald added a subscriber: xazax.hun.

See the test case for a repro.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49862

Files:
  clang-tidy/fuchsia/MultipleInheritanceCheck.cpp
  test/clang-tidy/fuchsia-multiple-inheritance-crash.cpp


Index: test/clang-tidy/fuchsia-multiple-inheritance-crash.cpp
===
--- /dev/null
+++ test/clang-tidy/fuchsia-multiple-inheritance-crash.cpp
@@ -0,0 +1,10 @@
+// RUN: clang-tidy -checks='fuchsia-multiple-inheritance' %s --
+template 
+struct X : T {
+  X();
+};
+
+int test() {
+  auto foo = []() {};
+  X();
+}
Index: clang-tidy/fuchsia/MultipleInheritanceCheck.cpp
===
--- clang-tidy/fuchsia/MultipleInheritanceCheck.cpp
+++ clang-tidy/fuchsia/MultipleInheritanceCheck.cpp
@@ -30,6 +30,7 @@
 // previously.
 void MultipleInheritanceCheck::addNodeToInterfaceMap(const CXXRecordDecl *Node,
  bool isInterface) {
+  assert(Node->getIdentifier());
   StringRef Name = Node->getIdentifier()->getName();
   InterfaceMap.insert(std::make_pair(Name, isInterface));
 }
@@ -39,6 +40,7 @@
 // interface status for the current node is not yet known.
 bool MultipleInheritanceCheck::getInterfaceStatus(const CXXRecordDecl *Node,
   bool &isInterface) const {
+  assert(Node->getIdentifier());
   StringRef Name = Node->getIdentifier()->getName();
   llvm::StringMapConstIterator Pair = InterfaceMap.find(Name);
   if (Pair == InterfaceMap.end())
@@ -59,6 +61,9 @@
 }
 
 bool MultipleInheritanceCheck::isInterface(const CXXRecordDecl *Node) {
+  if (!Node->getIdentifier())
+return false;
+
   // Short circuit the lookup if we have analyzed this record before.
   bool PreviousIsInterfaceResult;
   if (getInterfaceStatus(Node, PreviousIsInterfaceResult))


Index: test/clang-tidy/fuchsia-multiple-inheritance-crash.cpp
===
--- /dev/null
+++ test/clang-tidy/fuchsia-multiple-inheritance-crash.cpp
@@ -0,0 +1,10 @@
+// RUN: clang-tidy -checks='fuchsia-multiple-inheritance' %s --
+template 
+struct X : T {
+  X();
+};
+
+int test() {
+  auto foo = []() {};
+  X();
+}
Index: clang-tidy/fuchsia/MultipleInheritanceCheck.cpp
===
--- clang-tidy/fuchsia/MultipleInheritanceCheck.cpp
+++ clang-tidy/fuchsia/MultipleInheritanceCheck.cpp
@@ -30,6 +30,7 @@
 // previously.
 void MultipleInheritanceCheck::addNodeToInterfaceMap(const CXXRecordDecl *Node,
  bool isInterface) {
+  assert(Node->getIdentifier());
   StringRef Name = Node->getIdentifier()->getName();
   InterfaceMap.insert(std::make_pair(Name, isInterface));
 }
@@ -39,6 +40,7 @@
 // interface status for the current node is not yet known.
 bool MultipleInheritanceCheck::getInterfaceStatus(const CXXRecordDecl *Node,
   bool &isInterface) const {
+  assert(Node->getIdentifier());
   StringRef Name = Node->getIdentifier()->getName();
   llvm::StringMapConstIterator Pair = InterfaceMap.find(Name);
   if (Pair == InterfaceMap.end())
@@ -59,6 +61,9 @@
 }
 
 bool MultipleInheritanceCheck::isInterface(const CXXRecordDecl *Node) {
+  if (!Node->getIdentifier())
+return false;
+
   // Short circuit the lookup if we have analyzed this record before.
   bool PreviousIsInterfaceResult;
   if (getInterfaceStatus(Node, PreviousIsInterfaceResult))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D49526: Updated llvm-proto-fuzzer to execute the compiled code

2018-07-26 Thread Matt Morehouse via Phabricator via cfe-commits
morehouse added inline comments.



Comment at: clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp:115
+  make_unique(M.get());
+  FPasses->add(createTargetTransformInfoWrapperPass(TargetIRAnalysis()));
+

emmettneyman wrote:
> morehouse wrote:
> > morehouse wrote:
> > > Why do we add a `TargetTransformInfoWrapperPass` to both `Passes` and 
> > > `FPasses`?
> > Do we need both `Passes` and `FPasses`?
> I think because we're just adding a loop vectorize pass, we don't need 
> `FPasses`. The loop vectorize pass lives within the regular 
> `ModulePassManager`, not the `FunctionPassManager`. I decided to put it in 
> the code so, in the future, it would be easier to add different kinds of 
> passes to the fuzz target. Should I remove it?
Let's remove it since it's currently unnecessary.



Comment at: clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp:135
+  std::unique_ptr M = parseIR(MemoryBufferRef(IR, "IR"), Err,
+   Context);
+  if (!M)

The indentation looks off.  Please fix.



Comment at: clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp:147
+  builder.setUseOrcMCJITReplacement(false);
+  builder.setMCJITMemoryManager(make_unique());
+  builder.setOptLevel(OLvl);

This uses `llvm:make_unique`, which was written when LLVM used C++11.  But 
since LLVM now uses C++14, I think we should use `std::make_unique` instead.



Comment at: clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp:169
+  int c[] = {1};
+  
+  f(a, b, c, 1);

Remove whitespace on empty lines.

Actually, you could probably remove this line altogether since the call to 
`f()` can be grouped with the parameter setup above.



Comment at: clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp:184
+  CodeGenOpt::Level OLvl;
+  getOptLevel(ExtraArgs, OLvl);
+  

We're allowing the JIT opt-level to be specified on the command line, but we're 
hard-coding OptLevel=3 for the optimization passes.

Do we need to allow the opt-level to be specified on the command line?


Repository:
  rC Clang

https://reviews.llvm.org/D49526



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


[PATCH] D48027: [analyzer] Improve `CallDescription` to handle c++ method.

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

@xazax.hun Thanks for your tips! After some investigation, `MatchFinder::match` 
just traverse one ASTNode, that means `match(namedDecl(HasNameMatcher()))` and 
`match(namedDecl(matchesName()))` both not traverse children. So there are 
three ways to match the specified AST node.

1. `match(namedDecl(HasNameMatcher()))` matches the full qualified name that 
contains template parameter and that's not what we want to see.
2. `match(namedDecl(matchesName()))` uses llvm regex to  match the full 
qualified name.
3. Unwrap the declaration and match each layer, similar to 
`HasNameMatcher::matchesNodeFullFast()`.

In this update, I use the third way to match the specified AST node. This is 
simpler than I thought.

In addition, add a redundant constructor that is only used to construct a 
`CallDescription` with one name, this avoids the modification of the existing 
checker, like `BlockInCriticalSectionChecker.cpp`. Any suggestions?


Repository:
  rC Clang

https://reviews.llvm.org/D48027

Files:
  include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
  lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
  lib/StaticAnalyzer/Core/CallEvent.cpp

Index: lib/StaticAnalyzer/Core/CallEvent.cpp
===
--- lib/StaticAnalyzer/Core/CallEvent.cpp
+++ lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -256,11 +256,38 @@
 return false;
   if (!CD.IsLookupDone) {
 CD.IsLookupDone = true;
-CD.II = &getState()->getStateManager().getContext().Idents.get(CD.FuncName);
+CD.II = &getState()->getStateManager().getContext().Idents.get(
+CD.getFunctionName());
   }
   const IdentifierInfo *II = getCalleeIdentifier();
   if (!II || II != CD.II)
 return false;
+
+  const Decl *D = getDecl();
+  // If CallDescription provides prefix names, use them to improve matching
+  // accuracy.
+  if (CD.QualifiedName.size() > 1 && D) {
+const DeclContext *Ctx = D->getDeclContext();
+std::vector QualifiedName = CD.QualifiedName;
+QualifiedName.pop_back();
+for (; Ctx && isa(Ctx); Ctx = Ctx->getParent()) {
+  if (const auto *ND = dyn_cast(Ctx)) {
+if (!QualifiedName.empty() && ND->getName() == QualifiedName.back())
+  QualifiedName.pop_back();
+continue;
+  }
+
+  if (const auto *RD = dyn_cast(Ctx)) {
+if (!QualifiedName.empty() && RD->getName() == QualifiedName.back())
+  QualifiedName.pop_back();
+continue;
+  }
+}
+
+if (!QualifiedName.empty())
+  return false;
+  }
+
   return (CD.RequiredArgs == CallDescription::NoArgRequirement ||
   CD.RequiredArgs == getNumArgs());
 }
Index: lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
+++ lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
@@ -85,11 +85,20 @@
   };
 
   InnerPointerChecker()
-  : AppendFn("append"), AssignFn("assign"), ClearFn("clear"),
-CStrFn("c_str"), DataFn("data"), EraseFn("erase"), InsertFn("insert"),
-PopBackFn("pop_back"), PushBackFn("push_back"), ReplaceFn("replace"),
-ReserveFn("reserve"), ResizeFn("resize"),
-ShrinkToFitFn("shrink_to_fit"), SwapFn("swap") {}
+  : AppendFn({"std", "basic_string", "append"}),
+AssignFn({"std", "basic_string", "assign"}),
+ClearFn({"std", "basic_string", "clear"}),
+CStrFn({"std", "basic_string", "c_str"}),
+DataFn({"std", "basic_string", "data"}),
+EraseFn({"std", "basic_string", "erase"}),
+InsertFn({"std", "basic_string", "insert"}),
+PopBackFn({"std", "basic_string", "pop_back"}),
+PushBackFn({"std", "basic_string", "push_back"}),
+ReplaceFn({"std", "basic_string", "replace"}),
+ReserveFn({"std", "basic_string", "reserve"}),
+ResizeFn({"std", "basic_string", "resize"}),
+ShrinkToFitFn({"std", "basic_string", "shrink_to_fit"}),
+SwapFn({"std", "basic_string", "swap"}) {}
 
   /// Check whether the function called on the container object is a
   /// member function that potentially invalidates pointers referring
@@ -148,10 +157,6 @@
   if (!ObjRegion)
 return;
 
-  auto *TypeDecl = ObjRegion->getValueType()->getAsCXXRecordDecl();
-  if (TypeDecl->getName() != "basic_string")
-return;
-
   ProgramStateRef State = C.getState();
 
   if (Call.isCalled(CStrFn) || Call.isCalled(DataFn)) {
Index: include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
===
--- include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
+++ include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
@@ -79,24 +79,41 @@
 
   mutable IdentifierInfo *II = nullptr;
   mutable bool IsLookupDone = false;
-  StringRef FuncName;
+  // The list of the qualified names used to identify the spe

[PATCH] D49863: [istream] Fix error flags and exceptions propagated from input stream operations

2018-07-26 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a comment.

This is a very tricky change since it touches all the input stream operations, 
both formatted and unformatted. However, I think it's an important change as it 
fixes extremely broken behavior. The paper I'm working on to fix this in the 
Standard is 
https://github.com/ldionne/wg21/blob/4d963b488182b96479636c252695542671fd5e41/generated/dr.pdf.
 Perhaps we should wait for the paper to make its way through the Standard 
before committing this, but in any case the new behavior of libc++ should now 
match that of libstdc++ and MSVC (couldn't test with those libraries, though).


Repository:
  rCXX libc++

https://reviews.llvm.org/D49863



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


Re: r338032 - [OPENMP] Force OpenMP 4.5 when compiling for offloading.

2018-07-26 Thread Jonas Hahnfeld via cfe-commits

Hi Alexey,

maybe we can now raise the version generally? Is that something that we 
want to do before branching for 7.0?
According to http://clang.llvm.org/docs/OpenMPSupport.html, all 
directives of OpenMP 4.5 are supported (even if Clang may not generate 
optimal code).


Cheers,
Jonas

On 2018-07-26 17:17, Alexey Bataev via cfe-commits wrote:

Author: abataev
Date: Thu Jul 26 08:17:38 2018
New Revision: 338032

URL: http://llvm.org/viewvc/llvm-project?rev=338032&view=rev
Log:
[OPENMP] Force OpenMP 4.5 when compiling for offloading.

If the user requested compilation for OpenMP with the offloading
support, force the version of the OpenMP standard to 4.5 by default.

Modified:
cfe/trunk/lib/Driver/ToolChains/Clang.cpp
cfe/trunk/lib/Frontend/CompilerInvocation.cpp
cfe/trunk/test/OpenMP/driver.c

Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
URL:
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=338032&r1=338031&r2=338032&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Thu Jul 26 08:17:38 2018
@@ -4698,7 +4698,7 @@ void Clang::ConstructJob(Compilation &C,

   // For all the host OpenMP offloading compile jobs we need to pass
the targets
   // information using -fopenmp-targets= option.
-  if (isa(JA) && 
JA.isHostOffloading(Action::OFK_OpenMP)) {

+  if (JA.isHostOffloading(Action::OFK_OpenMP)) {
 SmallString<128> TargetInfo("-fopenmp-targets=");

 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);

Modified: cfe/trunk/lib/Frontend/CompilerInvocation.cpp
URL:
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/CompilerInvocation.cpp?rev=338032&r1=338031&r2=338032&view=diff
==
--- cfe/trunk/lib/Frontend/CompilerInvocation.cpp (original)
+++ cfe/trunk/lib/Frontend/CompilerInvocation.cpp Thu Jul 26 08:17:38 
2018

@@ -2594,13 +2594,15 @@ static void ParseLangArgs(LangOptions &O
   Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
   Opts.OpenMPIsDevice =
   Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
+  bool IsTargetSpecified =
+  Opts.OpenMPIsDevice || 
Args.hasArg(options::OPT_fopenmp_targets_EQ);


   if (Opts.OpenMP || Opts.OpenMPSimd) {
-if (int Version =
-getLastArgIntValue(Args, OPT_fopenmp_version_EQ,
-   IsSimdSpecified ? 45 : Opts.OpenMP, 
Diags))

+if (int Version = getLastArgIntValue(
+Args, OPT_fopenmp_version_EQ,
+(IsSimdSpecified || IsTargetSpecified) ? 45 : Opts.OpenMP, 
Diags))

   Opts.OpenMP = Version;
-else if (IsSimdSpecified)
+else if (IsSimdSpecified || IsTargetSpecified)
   Opts.OpenMP = 45;
 // Provide diagnostic when a given target is not expected to be an 
OpenMP

 // device or host.

Modified: cfe/trunk/test/OpenMP/driver.c
URL:
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/OpenMP/driver.c?rev=338032&r1=338031&r2=338032&view=diff
==
--- cfe/trunk/test/OpenMP/driver.c (original)
+++ cfe/trunk/test/OpenMP/driver.c Thu Jul 26 08:17:38 2018
@@ -1,3 +1,4 @@
+// REQUIRES: x86-registered-target
 // Test that by default -fnoopenmp-use-tls is passed to frontend.
 //
 // RUN: %clang %s -### -o %t.o 2>&1 -fopenmp=libomp | FileCheck
--check-prefix=CHECK-DEFAULT %s
@@ -23,7 +24,9 @@

 // RUN: %clang %s -c -E -dM -fopenmp=libomp -fopenmp-version=45 |
FileCheck --check-prefix=CHECK-45-VERSION %s
 // RUN: %clang %s -c -E -dM -fopenmp=libomp -fopenmp-simd | FileCheck
--check-prefix=CHECK-45-VERSION %s
+// RUN: %clang %s -c -E -dM -fopenmp=libomp
-fopenmp-targets=x86_64-unknown-unknown -o - | FileCheck
--check-prefix=CHECK-45-VERSION --check-prefix=CHECK-45-VERSION2 %s
 // CHECK-45-VERSION: #define _OPENMP 201511
+// CHECK-45-VERSION2: #define _OPENMP 201511

 // RUN: %clang %s -c -E -dM -fopenmp-version=1 | FileCheck
--check-prefix=CHECK-VERSION %s
 // RUN: %clang %s -c -E -dM -fopenmp-version=31 | FileCheck
--check-prefix=CHECK-VERSION %s


___
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] D49790: [AST] Small doc update for DeclContext

2018-07-26 Thread Bruno Ricci via Phabricator via cfe-commits
bricci updated this revision to Diff 157505.
bricci edited the summary of this revision.
bricci added a comment.

Re-added the "friend class ASTWriter" after making
hasNeedToReconcileExternalVisibleStorage, hasLazyLocalLexicalLookups
and hasLazyExternalLexicalLookups in DeclContext private.

This match the original situation where 
HasNeedToReconcileExternalVisibleStorage,
HasLazyLocalLexicalLookups and HasLazyLocalLexicalLookups in DeclContext
were private. This now depends on https://reviews.llvm.org/D49729


Repository:
  rC Clang

https://reviews.llvm.org/D49790

Files:
  include/clang/AST/DeclBase.h


Index: include/clang/AST/DeclBase.h
===
--- include/clang/AST/DeclBase.h
+++ include/clang/AST/DeclBase.h
@@ -1250,16 +1250,29 @@
 /// that directly derive from DeclContext are mentioned, not their subclasses):
 ///
 ///   TranslationUnitDecl
+///   ExternCContext
 ///   NamespaceDecl
-///   FunctionDecl
 ///   TagDecl
+///   OMPDeclareReductionDecl
+///   FunctionDecl
 ///   ObjCMethodDecl
 ///   ObjCContainerDecl
 ///   LinkageSpecDecl
 ///   ExportDecl
 ///   BlockDecl
-///   OMPDeclareReductionDecl
+///   CapturedDecl
 class DeclContext {
+  /// For makeDeclVisibleInContextImpl
+  friend class ASTDeclReader;
+  /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap,
+  /// hasNeedToReconcileExternalVisibleStorage
+  friend class ExternalASTSource;
+  /// For CreateStoredDeclsMap
+  friend class DependentDiagnostic;
+  /// For hasNeedToReconcileExternalVisibleStorage,
+  /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups
+  friend class ASTWriter;
+
   // We use uint64_t in the bit-fields below since some bit-fields
   // cross the unsigned boundary and this breaks the packing.
 
@@ -1716,10 +1729,6 @@
   "BlockDeclBitfields is larger than 8 bytes!");
   };
 
-  friend class ASTDeclReader;
-  friend class ASTWriter;
-  friend class ExternalASTSource;
-
   /// FirstDecl - The first declaration stored within this declaration
   /// context.
   mutable Decl *FirstDecl = nullptr;
@@ -2398,8 +2407,6 @@
 DeclContextBits.HasLazyExternalLexicalLookups = HasLELL;
   }
 
-  friend class DependentDiagnostic;
-
   void reconcileExternalVisibleStorage() const;
   bool LoadLexicalDeclsFromExternalStorage() const;
 


Index: include/clang/AST/DeclBase.h
===
--- include/clang/AST/DeclBase.h
+++ include/clang/AST/DeclBase.h
@@ -1250,16 +1250,29 @@
 /// that directly derive from DeclContext are mentioned, not their subclasses):
 ///
 ///   TranslationUnitDecl
+///   ExternCContext
 ///   NamespaceDecl
-///   FunctionDecl
 ///   TagDecl
+///   OMPDeclareReductionDecl
+///   FunctionDecl
 ///   ObjCMethodDecl
 ///   ObjCContainerDecl
 ///   LinkageSpecDecl
 ///   ExportDecl
 ///   BlockDecl
-///   OMPDeclareReductionDecl
+///   CapturedDecl
 class DeclContext {
+  /// For makeDeclVisibleInContextImpl
+  friend class ASTDeclReader;
+  /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap,
+  /// hasNeedToReconcileExternalVisibleStorage
+  friend class ExternalASTSource;
+  /// For CreateStoredDeclsMap
+  friend class DependentDiagnostic;
+  /// For hasNeedToReconcileExternalVisibleStorage,
+  /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups
+  friend class ASTWriter;
+
   // We use uint64_t in the bit-fields below since some bit-fields
   // cross the unsigned boundary and this breaks the packing.
 
@@ -1716,10 +1729,6 @@
   "BlockDeclBitfields is larger than 8 bytes!");
   };
 
-  friend class ASTDeclReader;
-  friend class ASTWriter;
-  friend class ExternalASTSource;
-
   /// FirstDecl - The first declaration stored within this declaration
   /// context.
   mutable Decl *FirstDecl = nullptr;
@@ -2398,8 +2407,6 @@
 DeclContextBits.HasLazyExternalLexicalLookups = HasLELL;
   }
 
-  friend class DependentDiagnostic;
-
   void reconcileExternalVisibleStorage() const;
   bool LoadLexicalDeclsFromExternalStorage() const;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r338041 - [CodeGen][ObjC] Make block copy/dispose helper functions exception-safe.

2018-07-26 Thread Akira Hatanaka via cfe-commits
Author: ahatanak
Date: Thu Jul 26 09:51:21 2018
New Revision: 338041

URL: http://llvm.org/viewvc/llvm-project?rev=338041&view=rev
Log:
[CodeGen][ObjC] Make block copy/dispose helper functions exception-safe.

When an exception is thrown in a block copy helper function, captured
objects that have previously been copied should be destructed or
released. Similarly, captured objects that are yet to be released should
be released when an exception is thrown in a dispose helper function.

rdar://problem/42410255

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

Modified:
cfe/trunk/lib/CodeGen/CGBlocks.cpp
cfe/trunk/lib/CodeGen/CGDecl.cpp
cfe/trunk/lib/CodeGen/CodeGenFunction.h
cfe/trunk/test/CodeGenObjC/blocks.m
cfe/trunk/test/CodeGenObjCXX/arc-blocks.mm

Modified: cfe/trunk/lib/CodeGen/CGBlocks.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBlocks.cpp?rev=338041&r1=338040&r2=338041&view=diff
==
--- cfe/trunk/lib/CodeGen/CGBlocks.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBlocks.cpp Thu Jul 26 09:51:21 2018
@@ -1585,6 +1585,64 @@ static void findBlockCapturedManagedEnti
   }
 }
 
+namespace {
+/// Release a __block variable.
+struct CallBlockRelease final : EHScopeStack::Cleanup {
+  Address Addr;
+  BlockFieldFlags FieldFlags;
+  bool LoadBlockVarAddr;
+
+  CallBlockRelease(Address Addr, BlockFieldFlags Flags, bool LoadValue)
+  : Addr(Addr), FieldFlags(Flags), LoadBlockVarAddr(LoadValue) {}
+
+  void Emit(CodeGenFunction &CGF, Flags flags) override {
+llvm::Value *BlockVarAddr;
+if (LoadBlockVarAddr) {
+  BlockVarAddr = CGF.Builder.CreateLoad(Addr);
+  BlockVarAddr = CGF.Builder.CreateBitCast(BlockVarAddr, CGF.VoidPtrTy);
+} else {
+  BlockVarAddr = Addr.getPointer();
+}
+
+CGF.BuildBlockRelease(BlockVarAddr, FieldFlags);
+  }
+};
+} // end anonymous namespace
+
+static void pushCaptureCleanup(BlockCaptureEntityKind CaptureKind,
+   Address Field, QualType CaptureType,
+   BlockFieldFlags Flags, bool EHOnly,
+   CodeGenFunction &CGF) {
+  switch (CaptureKind) {
+  case BlockCaptureEntityKind::CXXRecord:
+  case BlockCaptureEntityKind::ARCWeak:
+  case BlockCaptureEntityKind::NonTrivialCStruct:
+  case BlockCaptureEntityKind::ARCStrong: {
+if (CaptureType.isDestructedType() &&
+(!EHOnly || CGF.needsEHCleanup(CaptureType.isDestructedType( {
+  CodeGenFunction::Destroyer *Destroyer =
+  CaptureKind == BlockCaptureEntityKind::ARCStrong
+  ? CodeGenFunction::destroyARCStrongImprecise
+  : CGF.getDestroyer(CaptureType.isDestructedType());
+  CleanupKind Kind =
+  EHOnly ? EHCleanup
+ : CGF.getCleanupKind(CaptureType.isDestructedType());
+  CGF.pushDestroy(Kind, Field, CaptureType, Destroyer, Kind & EHCleanup);
+}
+break;
+  }
+  case BlockCaptureEntityKind::BlockObject: {
+if (!EHOnly || CGF.getLangOpts().Exceptions) {
+  CleanupKind Kind = EHOnly ? EHCleanup : NormalAndEHCleanup;
+  CGF.enterByrefCleanup(Kind, Field, Flags, /*LoadBlockVarAddr*/ true);
+}
+break;
+  }
+  case BlockCaptureEntityKind::None:
+llvm_unreachable("unexpected BlockCaptureEntityKind");
+  }
+}
+
 /// Generate the copy-helper function for a block closure object:
 ///   static void block_copy_helper(block_t *dst, block_t *src);
 /// The runtime will have previously initialized 'dst' by doing a
@@ -1648,6 +1706,7 @@ CodeGenFunction::GenerateCopyHelperFunct
   for (const auto &CopiedCapture : CopiedCaptures) {
 const BlockDecl::Capture &CI = CopiedCapture.CI;
 const CGBlockInfo::Capture &capture = CopiedCapture.Capture;
+QualType captureType = CI.getVariable()->getType();
 BlockFieldFlags flags = CopiedCapture.Flags;
 
 unsigned index = capture.getIndex();
@@ -1685,9 +1744,11 @@ CodeGenFunction::GenerateCopyHelperFunct
 } else {
   EmitARCRetainNonBlock(srcValue);
 
-  // We don't need this anymore, so kill it.  It's not quite
-  // worth the annoyance to avoid creating it in the first place.
-  cast(dstField.getPointer())->eraseFromParent();
+  // Unless EH cleanup is required, we don't need this anymore, so kill
+  // it. It's not quite worth the annoyance to avoid creating it in the
+  // first place.
+  if (!needsEHCleanup(captureType.isDestructedType()))
+cast(dstField.getPointer())->eraseFromParent();
 }
   } else {
 assert(CopiedCapture.Kind == BlockCaptureEntityKind::BlockObject);
@@ -1715,6 +1776,11 @@ CodeGenFunction::GenerateCopyHelperFunct
 }
   }
 }
+
+// Ensure that we destroy the copied object if an exception is thrown later
+// in the helper function.
+pushCaptureCleanup(CopiedCapture.Kind, dstField, captureType, flags, 
/*E

[PATCH] D49718: [CodeGen][ObjC] Make block copy/dispose helper function exception-safe.

2018-07-26 Thread Akira Hatanaka via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC338041: [CodeGen][ObjC] Make block copy/dispose helper 
functions exception-safe. (authored by ahatanak, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D49718?vs=157395&id=157514#toc

Repository:
  rC Clang

https://reviews.llvm.org/D49718

Files:
  lib/CodeGen/CGBlocks.cpp
  lib/CodeGen/CGDecl.cpp
  lib/CodeGen/CodeGenFunction.h
  test/CodeGenObjC/blocks.m
  test/CodeGenObjCXX/arc-blocks.mm

Index: test/CodeGenObjC/blocks.m
===
--- test/CodeGenObjC/blocks.m
+++ test/CodeGenObjC/blocks.m
@@ -79,10 +79,9 @@
   // Then we initialize the block, blah blah blah.
   // CHECK:  call void @test2_helper(
 
-  // Finally, kill the variable with BLOCK_FIELD_IS_BYREF.  We're not
-  // supposed to pass BLOCK_FIELD_IS_WEAK here.
+  // Finally, kill the variable with BLOCK_FIELD_IS_BYREF.
   // CHECK:  [[T0:%.*]] = bitcast [[WEAK_T]]* [[WEAKX]] to i8*
-  // CHECK:  call void @_Block_object_dispose(i8* [[T0]], i32 8)
+  // CHECK:  call void @_Block_object_dispose(i8* [[T0]], i32 24)
 
   __attribute__((objc_gc(weak))) __block Test2 *weakX = x;
   test2_helper(^{ [weakX destroy]; });
Index: test/CodeGenObjCXX/arc-blocks.mm
===
--- test/CodeGenObjCXX/arc-blocks.mm
+++ test/CodeGenObjCXX/arc-blocks.mm
@@ -1,6 +1,9 @@
-// RUN: %clang_cc1 -std=gnu++98 -triple x86_64-apple-darwin10 -emit-llvm -fobjc-runtime-has-weak -fblocks -fobjc-arc -o - %s | FileCheck %s
+// RUN: %clang_cc1 -std=gnu++98 -triple x86_64-apple-darwin10 -emit-llvm -fobjc-runtime-has-weak -fblocks -fobjc-arc -fexceptions -fobjc-arc-exceptions -o - %s | FileCheck -check-prefix CHECK %s
+// RUN: %clang_cc1 -std=gnu++98 -triple x86_64-apple-darwin10 -emit-llvm -fobjc-runtime-has-weak -fblocks -fobjc-arc -fexceptions -fobjc-arc-exceptions -O1 -o - %s | FileCheck -check-prefix CHECK-O1 %s
 
 // CHECK: [[A:.*]] = type { i64, [10 x i8*] }
+// CHECK: %[[STRUCT_TEST1_S0:.*]] = type { i32 }
+// CHECK: %[[STRUCT_BLOCK_DESCRIPTOR:.*]] = type { i64, i64 }
 
 // CHECK: [[LAYOUT0:@.*]] = private unnamed_addr constant [3 x i8] c" 9\00"
 
@@ -47,3 +50,133 @@
   // CHECK-NEXT: call void @_ZN5test01AD1Ev([[A]]* [[T1]])
   // CHECK-NEXT: ret void
 }
+
+namespace test1 {
+
+// Check that copy/dispose helper functions are exception safe.
+
+// CHECK-LABEL: define internal void @__copy_helper_block_(
+// CHECK: %[[BLOCK_SOURCE:.*]] = bitcast i8* %{{.*}} to <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8*, %[[STRUCT_TEST1_S0]], %[[STRUCT_TEST1_S0]] }>*
+// CHECK: %[[BLOCK_DEST:.*]] = bitcast i8* %{{.*}} to <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8*, %[[STRUCT_TEST1_S0]], %[[STRUCT_TEST1_S0]] }>*
+
+// CHECK: %[[V4:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8*, %[[STRUCT_TEST1_S0]], %[[STRUCT_TEST1_S0]] }>, <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8*, %[[STRUCT_TEST1_S0]], %[[STRUCT_TEST1_S0]] }>* %[[BLOCK_SOURCE]], i32 0, i32 6
+// CHECK: %[[V5:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8*, %[[STRUCT_TEST1_S0]], %[[STRUCT_TEST1_S0]] }>, <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8*, %[[STRUCT_TEST1_S0]], %[[STRUCT_TEST1_S0]] }>* %[[BLOCK_DEST]], i32 0, i32 6
+// CHECK: %[[BLOCKCOPY_SRC:.*]] = load i8*, i8** %[[V4]], align 8
+// CHECK: %[[V6:.*]] = bitcast i8** %[[V5]] to i8*
+// CHECK: call void @_Block_object_assign(i8* %[[V6]], i8* %[[BLOCKCOPY_SRC]], i32 8)
+
+// CHECK: %[[V7:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8*, %[[STRUCT_TEST1_S0]], %[[STRUCT_TEST1_S0]] }>, <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8*, %[[STRUCT_TEST1_S0]], %[[STRUCT_TEST1_S0]] }>* %[[BLOCK_SOURCE]], i32 0, i32 7
+// CHECK: %[[V8:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8*, %[[STRUCT_TEST1_S0]], %[[STRUCT_TEST1_S0]] }>, <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8*, %[[STRUCT_TEST1_S0]], %[[STRUCT_TEST1_S0]] }>* %[[BLOCK_DEST]], i32 0, i32 7
+// CHECK: call void @objc_copyWeak(i8** %[[V8]], i8** %[[V7]])
+
+// CHECK: %[[V9:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8*, %[[STRUCT_TEST1_S0]], %[[STRUCT_TEST1_S0]] }>, <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8*, %[[STRUCT_TEST1_S0]], %[[STRUCT_TEST1_S0]] }>* %[[BLOCK_SOURCE]], i32 0, i32 5
+// CHECK: %[[V10:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8*, %[[STRUCT_TEST1_S0]], %[[STRUCT_TEST1_S0]] }>, <{ i8*, i32, i32, i8*, %[[STRUCT_BLOCK_DESCRIPTOR]]*, i8*, i8*, i8*, %[[STRUCT_TEST1_S0]], %[[STRUCT_TEST1_S0]] }>* %[[BLOCK_DEST]], i32 0, i32

[PATCH] D49864: The script clang-tidy-diff.py doesn't accept 'pass by' options (--)

2018-07-26 Thread Jano Simas via Phabricator via cfe-commits
janosimas created this revision.
janosimas added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

When the argument -- is passed to clang-tidy-diff.py it should pass the 
following arguments to clang-tidy.
It does that but also includes -- as an argument,
there should be a +1 in the '--' index.

So only the following arguments as passed to clang-tidy.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49864

Files:
  clang-tidy/tool/clang-tidy-diff.py


Index: clang-tidy/tool/clang-tidy-diff.py
===
--- clang-tidy/tool/clang-tidy-diff.py
+++ clang-tidy/tool/clang-tidy-diff.py
@@ -70,7 +70,7 @@
   clang_tidy_args = []
   argv = sys.argv[1:]
   if '--' in argv:
-clang_tidy_args.extend(argv[argv.index('--'):])
+clang_tidy_args.extend(argv[argv.index('--')+1:])
 argv = argv[:argv.index('--')]
 
   args = parser.parse_args(argv)


Index: clang-tidy/tool/clang-tidy-diff.py
===
--- clang-tidy/tool/clang-tidy-diff.py
+++ clang-tidy/tool/clang-tidy-diff.py
@@ -70,7 +70,7 @@
   clang_tidy_args = []
   argv = sys.argv[1:]
   if '--' in argv:
-clang_tidy_args.extend(argv[argv.index('--'):])
+clang_tidy_args.extend(argv[argv.index('--')+1:])
 argv = argv[:argv.index('--')]
 
   args = parser.parse_args(argv)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D49589: [UBSan] Strengthen pointer checks in 'new' expressions

2018-07-26 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff updated this revision to Diff 157519.
sepavloff added a comment.

Updated patch

Now information, if sanitizer checks are generated while processing 'new'
expression, is passed through function call arguments.


Repository:
  rC Clang

https://reviews.llvm.org/D49589

Files:
  lib/CodeGen/CGClass.cpp
  lib/CodeGen/CGExprCXX.cpp
  lib/CodeGen/CGValue.h
  lib/CodeGen/CodeGenFunction.h
  test/CodeGenCXX/ubsan-new-checks.cpp

Index: test/CodeGenCXX/ubsan-new-checks.cpp
===
--- /dev/null
+++ test/CodeGenCXX/ubsan-new-checks.cpp
@@ -0,0 +1,146 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -std=c++11 -S -emit-llvm -fsanitize=alignment %s -o - | FileCheck %s
+
+struct alignas(32) S1 {
+  int x;
+  S1();
+};
+
+struct alignas(32) S2 {
+  int x;
+};
+
+struct alignas(32) S3 {
+  int x;
+  S3(int *p = new int[4]);
+};
+
+struct S4 : public S3 {
+  S4() : S3() {}
+};
+
+typedef __attribute__((ext_vector_type(2), aligned(32))) float float32x2_t;
+
+struct S5 {
+  float32x2_t x;
+};
+
+void *operator new (unsigned long, void *p) { return p; }
+void *operator new[] (unsigned long, void *p) { return p; }
+
+S1 *func_01() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_01v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   call void @_ZN2S1C1Ev(
+  // CHECK-NOT:   and i64 %{{.*}}, 31
+  // CHECK:   ret %struct.S1*
+  return new S1[20];
+}
+
+S2 *func_02() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_02v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   ret %struct.S2*
+  return new S2;
+}
+
+S2 *func_03() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_03v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK-NOT:   and i64 %{{.*}}, 31
+  // CHECK:   ret %struct.S2*
+  return new S2[20];
+}
+
+float32x2_t *func_04() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_04v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   ret <2 x float>*
+  return new float32x2_t;
+}
+
+float32x2_t *func_05() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_05v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK-NOT:   and i64 %{{.*}}, 31
+  // CHECK:   ret <2 x float>*
+  return new float32x2_t[20];
+}
+
+S3 *func_07() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_07v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   and i64 %{{.*}}, 3, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   ret %struct.S3*
+  return new S3;
+}
+
+S3 *func_08() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_08v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   and i64 %{{.*}}, 3, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   ret %struct.S3*
+  return new S3[10];
+}
+
+
+S2 *func_10(void *p) {
+  // CHECK-LABEL: define {{.*}} @_Z7func_10Pv
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   ret %struct.S2*
+  return new(p) S2;
+}
+
+S2 *func_11(void *p) {
+  // CHECK-LABEL: define {{.*}} @_Z7func_11Pv
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK-NOT:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK-NOT:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   ret %struct.S2*
+  return new(p) S2[10];
+}
+
+float32x2_t *func_12() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_12v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   ret <2 x float>*
+  return new float32x2_t;
+}
+
+float32x2_t *func_13() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_13v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK-NOT:   and i64 %{{.*}}, 31
+  // CHECK:   ret <2 x float>*
+  return new float32x2_t[20];
+}
+
+S4 *func_14() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_14v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK-NOT:   and i64 %{{.*}}, 31
+  // CHECK:   ret %struct.S4*
+  return new S4;
+}
+
+S5 *func_15(const S5 *ptr) {
+  // CHECK-LABEL: define {{.*}} @_Z7func_15PK2S5
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK-NOT:   and i64
+  // CHECK:   ret %struct.S5*
+  return new S5(*ptr);
+}
Index: lib/CodeGen/CodeGenFunction.h
===
--- lib/CodeGen/Co

[PATCH] D49701: [ASTMatchers] Introduce a matcher for `ObjCIvarExpr`, support getting it's declaration

2018-07-26 Thread George Karpenkov via Phabricator via cfe-commits
george.karpenkov added inline comments.



Comment at: clang/include/clang/ASTMatchers/ASTMatchersInternal.h:44
 #include "clang/AST/Expr.h"
+#include "clang/AST/ExprObjC.h"
 #include "clang/AST/ExprCXX.h"

aaron.ballman wrote:
> This list should remain sorted alphabetically.
but it is?


https://reviews.llvm.org/D49701



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


[PATCH] D49701: [ASTMatchers] Introduce a matcher for `ObjCIvarExpr`, support getting it's declaration

2018-07-26 Thread George Karpenkov via Phabricator via cfe-commits
george.karpenkov updated this revision to Diff 157520.

https://reviews.llvm.org/D49701

Files:
  clang/docs/LibASTMatchersReference.html
  clang/include/clang/ASTMatchers/ASTMatchers.h
  clang/include/clang/ASTMatchers/ASTMatchersInternal.h
  clang/lib/ASTMatchers/ASTMatchersInternal.cpp
  clang/lib/ASTMatchers/Dynamic/Registry.cpp
  clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -1354,6 +1354,16 @@
   ));
 }
 
+TEST(ObjCIvarRefExprMatcher, IvarExpr) {
+  std::string ObjCString =
+"@interface A @end "
+"@implementation A { A *x; } - (void) func { x = 0; } @end";
+  EXPECT_TRUE(matchesObjC(ObjCString, objcIvarRefExpr()));
+  EXPECT_TRUE(matchesObjC(ObjCString, objcIvarRefExpr(
+hasDeclaration(namedDecl(hasName("x"));
+  EXPECT_FALSE(matchesObjC(ObjCString, objcIvarRefExpr(
+hasDeclaration(namedDecl(hasName("y"));
+}
 
 TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
   EXPECT_TRUE(matches("void f() { }",
Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -410,6 +410,7 @@
   REGISTER_MATCHER(objcImplementationDecl);
   REGISTER_MATCHER(objcInterfaceDecl);
   REGISTER_MATCHER(objcIvarDecl);
+  REGISTER_MATCHER(objcIvarRefExpr);
   REGISTER_MATCHER(objcMessageExpr);
   REGISTER_MATCHER(objcMethodDecl);
   REGISTER_MATCHER(objcObjectPointerType);
Index: clang/lib/ASTMatchers/ASTMatchersInternal.cpp
===
--- clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -679,6 +679,7 @@
 cxxOperatorCallExpr;
 const internal::VariadicDynCastAllOfMatcher expr;
 const internal::VariadicDynCastAllOfMatcher declRefExpr;
+const internal::VariadicDynCastAllOfMatcher objcIvarRefExpr;
 const internal::VariadicDynCastAllOfMatcher ifStmt;
 const internal::VariadicDynCastAllOfMatcher forStmt;
 const internal::VariadicDynCastAllOfMatcher
Index: clang/include/clang/ASTMatchers/ASTMatchersInternal.h
===
--- clang/include/clang/ASTMatchers/ASTMatchersInternal.h
+++ clang/include/clang/ASTMatchers/ASTMatchersInternal.h
@@ -42,6 +42,7 @@
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
+#include "clang/AST/ExprObjC.h"
 #include "clang/AST/NestedNameSpecifier.h"
 #include "clang/AST/Stmt.h"
 #include "clang/AST/TemplateName.h"
@@ -865,6 +866,12 @@
 return matchesDecl(Node.getConstructor(), Finder, Builder);
   }
 
+  bool matchesSpecialized(const ObjCIvarRefExpr &Node,
+  ASTMatchFinder *Finder,
+  BoundNodesTreeBuilder *Builder) const {
+return matchesDecl(Node.getDecl(), Finder, Builder);
+  }
+
   /// Extracts the operator new of the new call and returns whether the
   /// inner matcher matches on it.
   bool matchesSpecialized(const CXXNewExpr &Node,
@@ -1110,7 +1117,7 @@
  ElaboratedType, InjectedClassNameType, LabelStmt, AddrLabelExpr,
  MemberExpr, QualType, RecordType, TagType,
  TemplateSpecializationType, TemplateTypeParmType, TypedefType,
- UnresolvedUsingType>;
+ UnresolvedUsingType, ObjCIvarRefExpr>;
 
 /// Converts a \c Matcher to a matcher of desired type \c To by
 /// "adapting" a \c To into a \c T.
Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -1644,6 +1644,21 @@
 extern const internal::VariadicDynCastAllOfMatcher
 declRefExpr;
 
+/// Matches a reference to an ObjCIvar.
+///
+/// Example: matches "a" in "init" method:
+/// \code
+/// @implementation A {
+///   NSString *a;
+/// }
+/// - (void) init {
+///   a = @"hello";
+/// }
+//}
+/// \endcode
+extern const internal::VariadicDynCastAllOfMatcher
+objcIvarRefExpr;
+
 /// Matches if statements.
 ///
 /// Example matches 'if (x) {}'
@@ -2655,6 +2670,7 @@
 /// - for MemberExpr, the declaration of the referenced member
 /// - for CXXConstructExpr, the declaration of the constructor
 /// - for CXXNewExpr, the declaration of the operator new
+/// - for ObjCIvarExpr, the declaration of the ivar
 ///
 /// For type nodes, hasDeclaration will generally match the declaration of the
 /// sugared type. Given
Index: clang/docs/LibASTMatchersReference.html
===
--- clang/docs/LibASTMatchersReference.html
+++ clang/docs/Lib

[PATCH] D49865: Inform the AST of #pragma FENV_ACCESS use

2018-07-26 Thread Kevin P. Neal via Phabricator via cfe-commits
kpn created this revision.
kpn added reviewers: rsmith, craig.topper, hfinkel.
Herald added a subscriber: cfe-commits.

We have in place support for parsing #pragma FENV_ACCESS, but that information 
is then discarded with a warning to the user that we don't support it.

This patch gets us one step closer by getting the info down into the AST.


Repository:
  rC Clang

https://reviews.llvm.org/D49865

Files:
  include/clang/AST/Expr.h
  include/clang/Basic/LangOptions.h
  include/clang/Basic/TokenKinds.def
  include/clang/Parse/Parser.h
  include/clang/Sema/Sema.h
  lib/Parse/ParsePragma.cpp
  lib/Parse/ParseStmt.cpp
  lib/Parse/Parser.cpp
  lib/Sema/SemaAttr.cpp

Index: lib/Sema/SemaAttr.cpp
===
--- lib/Sema/SemaAttr.cpp
+++ lib/Sema/SemaAttr.cpp
@@ -773,6 +773,18 @@
   }
 }
 
+void Sema::ActOnPragmaFENVAccess(LangOptions::FENVAccessModeKind FPC) {
+  switch (FPC) {
+  case LangOptions::FEA_On:
+FPFeatures.setAllowFENVAccess();
+break;
+  case LangOptions::FEA_Off:
+FPFeatures.setDisallowFENVAccess();
+break;
+  }
+}
+
+
 void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
SourceLocation Loc) {
   // Visibility calculations will consider the namespace's visibility.
Index: lib/Parse/Parser.cpp
===
--- lib/Parse/Parser.cpp
+++ lib/Parse/Parser.cpp
@@ -674,6 +674,9 @@
   case tok::annot_pragma_fp_contract:
 HandlePragmaFPContract();
 return nullptr;
+  case tok::annot_pragma_fenv_access:
+HandlePragmaFENVAccess();
+return nullptr;
   case tok::annot_pragma_fp:
 HandlePragmaFP();
 break;
Index: lib/Parse/ParseStmt.cpp
===
--- lib/Parse/ParseStmt.cpp
+++ lib/Parse/ParseStmt.cpp
@@ -348,6 +348,12 @@
 ConsumeAnnotationToken();
 return StmtError();
 
+  case tok::annot_pragma_fenv_access:
+ProhibitAttributes(Attrs);
+//Diag(Tok, diag::err_pragma_fp_scope);
+HandlePragmaFENVAccess();
+return StmtEmpty();
+
   case tok::annot_pragma_opencl_extension:
 ProhibitAttributes(Attrs);
 HandlePragmaOpenCLExtension();
@@ -914,6 +920,9 @@
 case tok::annot_pragma_fp:
   HandlePragmaFP();
   break;
+case tok::annot_pragma_fenv_access:
+  HandlePragmaFENVAccess();
+  break;
 case tok::annot_pragma_ms_pointers_to_members:
   HandlePragmaMSPointersToMembers();
   break;
Index: lib/Parse/ParsePragma.cpp
===
--- lib/Parse/ParsePragma.cpp
+++ lib/Parse/ParsePragma.cpp
@@ -106,8 +106,19 @@
 tok::OnOffSwitch OOS;
 if (PP.LexOnOffSwitch(OOS))
  return;
-if (OOS == tok::OOS_ON)
+if (OOS == tok::OOS_ON) {
   PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
+
+  MutableArrayRef Toks(PP.getPreprocessorAllocator().Allocate(1),
+1);
+  Toks[0].startToken();
+  Toks[0].setKind(tok::annot_pragma_fenv_access);
+  Toks[0].setLocation(Tok.getLocation());
+  Toks[0].setAnnotationEndLoc(Tok.getLocation());
+  Toks[0].setAnnotationValue(reinterpret_cast(
+   static_cast(OOS)));
+  PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
+}
   }
 };
 
@@ -591,6 +602,32 @@
   ConsumeAnnotationToken();
 }
 
+void Parser::HandlePragmaFENVAccess() {
+  assert(Tok.is(tok::annot_pragma_fenv_access));
+  tok::OnOffSwitch OOS =
+static_cast(
+reinterpret_cast(Tok.getAnnotationValue()));
+
+  LangOptions::FENVAccessModeKind FPC;
+  switch (OOS) {
+  case tok::OOS_ON:
+FPC = LangOptions::FEA_On;
+break;
+  case tok::OOS_OFF:
+FPC = LangOptions::FEA_Off;
+break;
+#if NOTYET // FIXME: Add this cli option when it makes sense.
+  case tok::OOS_DEFAULT:
+FPC = getLangOpts().getDefaultFENVAccessMode();
+break;
+#endif
+  }
+
+  Actions.ActOnPragmaFENVAccess(FPC);
+  ConsumeAnnotationToken();
+}
+
+
 StmtResult Parser::HandlePragmaCaptured()
 {
   assert(Tok.is(tok::annot_pragma_captured));
Index: include/clang/Sema/Sema.h
===
--- include/clang/Sema/Sema.h
+++ include/clang/Sema/Sema.h
@@ -8433,6 +8433,10 @@
   /// \#pragma clang fp contract
   void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
 
+  /// ActOnPragmaFENVAccess - Called on well formed
+  /// \#pragma STDC FENV_ACCESS
+  void ActOnPragmaFENVAccess(LangOptions::FENVAccessModeKind FPC);
+
   /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
   /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
   void AddAlignmentAttributesForRecord(RecordDecl *RD);
Index: include/clang/Parse/Parser.h
===
--- include/clang/Parse/Parser.h
+++ include/clang/Parse/P

[PATCH] D49589: [UBSan] Strengthen pointer checks in 'new' expressions

2018-07-26 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff added a comment.

> Also, please remember that your analysis is not the only thing happening in 
> the compiler.  isChecked is not a meaningful name taken out of context.

`Address` is not modified in the current patch version. As for `AggValueSlot`, 
this method name is leaved, as there is no other meaning for this class. Please 
let me know if it is inappropriate.


Repository:
  rC Clang

https://reviews.llvm.org/D49589



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


Re: [clang-tools-extra] r338017 - [clangd] Proof-of-concept query iterators for Dex symbol index

2018-07-26 Thread Jeremy Morse via cfe-commits
 [Resending with cfe-commits@, whoops]

Hi Kirill,

We believe this patch might be breaking one of the buildbots:

http://lab.llvm.org:8011/builders/clang-x86_64-linux-
abi-test/builds/29719

Which is complaining about the std::unique_ptr copy constructor being
called in DexIndexTests.cpp. It seems likely that returning a unique_ptr:

> std::unique_ptr
> createAnd(std::vector> Children) {
>   return llvm::make_unique(move(Children));
> }

And sites such as:

>  auto AndEmpty = createAnd({create(L0)});

Are triggering a bug in clang 3.7 and 3.8 where the move constructor isn't
correctly inferred:

https://godbolt.org/g/Aquug4

Wrapping everything in std::move will likely fix that, those two versions
of clang are still officially supported by LLVM/Clang.

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


[PATCH] D49729: [AST][1/4] Move the bit-fields from TagDecl, EnumDecl and RecordDecl into DeclContext

2018-07-26 Thread Bruno Ricci via Phabricator via cfe-commits
bricci updated this revision to Diff 157522.
bricci marked 2 inline comments as done.
bricci added a comment.

- Re-based: r337978 [ODRHash] Support hashing enums added an ODRHash to 
EnumDecl which conflicts with these changes. The corresponding flag HasODRHash 
has been put into EnumDeclBitfields.
- The ugly IntegerType = (const Type *)nullptr; has been cleaned to IntegerType 
= nullptr; I guess the intent was to disambiguate between the two possible 
operator= but there is a special case for nullptr so this is not needed since 
const Type * is the first element of the pair.
- Made hasNeedToReconcileExternalVisibleStorage, hasLazyLocalLexicalLookups and 
hasLazyExternalLexicalLookups private. This match what was originally the case 
with the private bit-fields. This also requires making ASTWriter a friend of 
DeclContext (as was the case before).
- Fixed some comments in EnumDecl.


Repository:
  rC Clang

https://reviews.llvm.org/D49729

Files:
  include/clang/AST/Decl.h
  include/clang/AST/DeclBase.h
  lib/AST/Decl.cpp
  lib/AST/DeclBase.cpp
  lib/AST/DeclCXX.cpp
  lib/AST/DeclTemplate.cpp
  lib/Serialization/ASTReaderDecl.cpp
  lib/Serialization/ASTWriter.cpp
  lib/Serialization/ASTWriterDecl.cpp

Index: lib/Serialization/ASTWriterDecl.cpp
===
--- lib/Serialization/ASTWriterDecl.cpp
+++ lib/Serialization/ASTWriterDecl.cpp
@@ -1275,7 +1275,7 @@
 
   // Store (what we currently believe to be) the key function to avoid
   // deserializing every method so we can compute it.
-  if (D->IsCompleteDefinition)
+  if (D->isCompleteDefinition())
 Record.AddDeclRef(Context.getCurrentKeyFunction(D));
 
   Code = serialization::DECL_CXX_RECORD;
Index: lib/Serialization/ASTWriter.cpp
===
--- lib/Serialization/ASTWriter.cpp
+++ lib/Serialization/ASTWriter.cpp
@@ -3960,7 +3960,8 @@
 
 bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
DeclContext *DC) {
-  return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage;
+  return Result.hasExternalDecls() &&
+ DC->hasNeedToReconcileExternalVisibleStorage();
 }
 
 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
@@ -3975,8 +3976,8 @@
 void
 ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
llvm::SmallVectorImpl &LookupTable) {
-  assert(!ConstDC->HasLazyLocalLexicalLookups &&
- !ConstDC->HasLazyExternalLexicalLookups &&
+  assert(!ConstDC->hasLazyLocalLexicalLookups() &&
+ !ConstDC->hasLazyExternalLexicalLookups() &&
  "must call buildLookups first");
 
   // FIXME: We need to build the lookups table, which is logically const.
Index: lib/Serialization/ASTReaderDecl.cpp
===
--- lib/Serialization/ASTReaderDecl.cpp
+++ lib/Serialization/ASTReaderDecl.cpp
@@ -742,16 +742,16 @@
   ED->setPromotionType(Record.readType());
   ED->setNumPositiveBits(Record.readInt());
   ED->setNumNegativeBits(Record.readInt());
-  ED->IsScoped = Record.readInt();
-  ED->IsScopedUsingClassTag = Record.readInt();
-  ED->IsFixed = Record.readInt();
+  ED->setScoped(Record.readInt());
+  ED->setScopedUsingClassTag(Record.readInt());
+  ED->setFixed(Record.readInt());
 
-  ED->HasODRHash = true;
+  ED->setHasODRHash(true);
   ED->ODRHash = Record.readInt();
 
   // If this is a definition subject to the ODR, and we already have a
   // definition, merge this one into it.
-  if (ED->IsCompleteDefinition &&
+  if (ED->isCompleteDefinition() &&
   Reader.getContext().getLangOpts().Modules &&
   Reader.getContext().getLangOpts().CPlusPlus) {
 EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()];
@@ -767,7 +767,7 @@
 }
 if (OldDef) {
   Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));
-  ED->IsCompleteDefinition = false;
+  ED->setCompleteDefinition(false);
   Reader.mergeDefinitionVisibility(OldDef, ED);
   if (OldDef->getODRHash() != ED->getODRHash())
 Reader.PendingEnumOdrMergeFailures[OldDef].push_back(ED);
@@ -1744,7 +1744,7 @@
 Reader.MergedDeclContexts.insert(std::make_pair(MergeDD.Definition,
 DD.Definition));
 Reader.PendingDefinitions.erase(MergeDD.Definition);
-MergeDD.Definition->IsCompleteDefinition = false;
+MergeDD.Definition->setCompleteDefinition(false);
 Reader.mergeDefinitionVisibility(DD.Definition, MergeDD.Definition);
 assert(Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() &&
"already loaded pending lookups for merged definition");
@@ -1884,7 +1884,7 @@
   }
 
   // Mark this declaration as being a definition.
-  D->IsCompleteDefinition = true;
+  D->setCompleteDefinition(true);
 
   // If this is not the first declaration or is an update record

[PATCH] D49770: [ARM64] [Windows] Follow MS X86_64 C++ ABI when passing structs

2018-07-26 Thread Reid Kleckner via Phabricator via cfe-commits
rnk accepted this revision.
rnk added a comment.

Please avoid the extra enum case, and commit.




Comment at: include/clang/Basic/TargetInfo.h:1223
   enum CallingConvKind {
 CCK_Default,

This is poorly named. I'll try to send a patch to rename it after this lands.



Comment at: include/clang/Basic/TargetInfo.h:1226-1227
 CCK_ClangABI4OrPS4,
-CCK_MicrosoftX86_64
+CCK_MicrosoftX86_64,
+CCK_MicrosoftARM64
   };

IMO it'd be better to collapse these into something like `CCK_MicrosoftWin64`, 
since we don't treat them differently.


Repository:
  rC Clang

https://reviews.llvm.org/D49770



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


r338045 - [RISCV] Add support for interrupt attribute

2018-07-26 Thread Ana Pazos via cfe-commits
Author: apazos
Date: Thu Jul 26 10:37:45 2018
New Revision: 338045

URL: http://llvm.org/viewvc/llvm-project?rev=338045&view=rev
Log:
 [RISCV] Add support for interrupt attribute

Summary:
Clang supports the GNU style ``__attribute__((interrupt))`` attribute  on RISCV 
targets.
Permissible values for this parameter are user, supervisor, and machine.
If there is no parameter, then it defaults to machine.
Reference: https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html
Based on initial patch by Zhaoshi Zheng.

Reviewers: asb, aaron.ballman

Reviewed By: asb, aaron.ballman

Subscribers: rkruppe, the_o, aaron.ballman, MartinMosbeck, brucehoult, rbar, 
johnrusso, simoncook, sabuasal, niosHD, kito-cheng, shiva0217, zzheng, 
edward-jones, mgrang, rogfer01, cfe-commits

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

Added:
cfe/trunk/test/Sema/riscv-interrupt-attr.c
cfe/trunk/test/Sema/riscv-interrupt-attr.cpp
Modified:
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/include/clang/Basic/AttrDocs.td
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/lib/CodeGen/TargetInfo.cpp
cfe/trunk/lib/Sema/SemaDeclAttr.cpp

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=338045&r1=338044&r2=338045&view=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Thu Jul 26 10:37:45 2018
@@ -308,6 +308,7 @@ def TargetAVR : TargetArch<["avr"]>;
 def TargetMips32 : TargetArch<["mips", "mipsel"]>;
 def TargetAnyMips : TargetArch<["mips", "mipsel", "mips64", "mips64el"]>;
 def TargetMSP430 : TargetArch<["msp430"]>;
+def TargetRISCV : TargetArch<["riscv32", "riscv64"]>;
 def TargetX86 : TargetArch<["x86"]>;
 def TargetAnyX86 : TargetArch<["x86", "x86_64"]>;
 def TargetWindows : TargetArch<["x86", "x86_64", "arm", "thumb", "aarch64"]> {
@@ -1374,6 +1375,17 @@ def NoMicroMips : InheritableAttr, Targe
   let Documentation = [MicroMipsDocs];
 }
 
+def RISCVInterrupt : InheritableAttr, TargetSpecificAttr {
+  let Spellings = [GCC<"interrupt">];
+  let Subjects = SubjectList<[Function]>;
+  let Args = [EnumArgument<"Interrupt", "InterruptType",
+   ["user", "supervisor", "machine"],
+   ["user", "supervisor", "machine"],
+   1>];
+  let ParseKind = "Interrupt";
+  let Documentation = [RISCVInterruptDocs];
+}
+
 // This is not a TargetSpecificAttr so that is silently accepted and
 // ignored on other targets as encouraged by the OpenCL spec.
 //

Modified: cfe/trunk/include/clang/Basic/AttrDocs.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AttrDocs.td?rev=338045&r1=338044&r2=338045&view=diff
==
--- cfe/trunk/include/clang/Basic/AttrDocs.td (original)
+++ cfe/trunk/include/clang/Basic/AttrDocs.td Thu Jul 26 10:37:45 2018
@@ -1501,6 +1501,29 @@ as ``-mlong-calls`` and ``-mno-long-call
   }];
 }
 
+def RISCVInterruptDocs : Documentation {
+  let Category = DocCatFunction;
+  let Heading = "interrupt (RISCV)";
+  let Content = [{
+Clang supports the GNU style ``__attribute__((interrupt))`` attribute on RISCV
+targets. This attribute may be attached to a function definition and instructs
+the backend to generate appropriate function entry/exit code so that it can be
+used directly as an interrupt service routine.
+
+Permissible values for this parameter are ``user``, ``supervisor``,
+and ``machine``. If there is no parameter, then it defaults to machine.
+
+Repeated interrupt attribute on the same declaration will cause a warning
+to be emitted. In case of repeated declarations, the last one prevails.
+
+Refer to:
+https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html
+https://riscv.org/specifications/privileged-isa/
+The RISC-V Instruction Set Manual Volume II: Privileged Architecture
+Version 1.10.
+  }];
+}
+
 def AVRInterruptDocs : Documentation {
   let Category = DocCatFunction;
   let Heading = "interrupt (AVR)";

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=338045&r1=338044&r2=338045&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Thu Jul 26 10:37:45 
2018
@@ -274,6 +274,14 @@ def warn_mips_interrupt_attribute : Warn
"MIPS 'interrupt' attribute only applies to functions that have "
"%select{no parameters|a 'void' return type}0">,
InGroup;
+def warn_riscv_repeated_interrupt_attribute : Warning<
+  "repeated RISC-V 'interrupt' attribute">, InGroup;
+def note_riscv_repeated_interrupt_attribute : Note<
+  "

[PATCH] D48412: [RISCV] Add support for interrupt attribute

2018-07-26 Thread Ana Pazos via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC338045:  [RISCV] Add support for interrupt attribute 
(authored by apazos, committed by ).
Herald added a subscriber: jrtc27.

Repository:
  rC Clang

https://reviews.llvm.org/D48412

Files:
  include/clang/Basic/Attr.td
  include/clang/Basic/AttrDocs.td
  include/clang/Basic/DiagnosticSemaKinds.td
  lib/CodeGen/TargetInfo.cpp
  lib/Sema/SemaDeclAttr.cpp
  test/Sema/riscv-interrupt-attr.c
  test/Sema/riscv-interrupt-attr.cpp

Index: include/clang/Basic/AttrDocs.td
===
--- include/clang/Basic/AttrDocs.td
+++ include/clang/Basic/AttrDocs.td
@@ -1501,6 +1501,29 @@
   }];
 }
 
+def RISCVInterruptDocs : Documentation {
+  let Category = DocCatFunction;
+  let Heading = "interrupt (RISCV)";
+  let Content = [{
+Clang supports the GNU style ``__attribute__((interrupt))`` attribute on RISCV
+targets. This attribute may be attached to a function definition and instructs
+the backend to generate appropriate function entry/exit code so that it can be
+used directly as an interrupt service routine.
+
+Permissible values for this parameter are ``user``, ``supervisor``,
+and ``machine``. If there is no parameter, then it defaults to machine.
+
+Repeated interrupt attribute on the same declaration will cause a warning
+to be emitted. In case of repeated declarations, the last one prevails.
+
+Refer to:
+https://gcc.gnu.org/onlinedocs/gcc/RISC-V-Function-Attributes.html
+https://riscv.org/specifications/privileged-isa/
+The RISC-V Instruction Set Manual Volume II: Privileged Architecture
+Version 1.10.
+  }];
+}
+
 def AVRInterruptDocs : Documentation {
   let Category = DocCatFunction;
   let Heading = "interrupt (AVR)";
Index: include/clang/Basic/DiagnosticSemaKinds.td
===
--- include/clang/Basic/DiagnosticSemaKinds.td
+++ include/clang/Basic/DiagnosticSemaKinds.td
@@ -274,14 +274,22 @@
"MIPS 'interrupt' attribute only applies to functions that have "
"%select{no parameters|a 'void' return type}0">,
InGroup;
+def warn_riscv_repeated_interrupt_attribute : Warning<
+  "repeated RISC-V 'interrupt' attribute">, InGroup;
+def note_riscv_repeated_interrupt_attribute : Note<
+  "repeated RISC-V 'interrupt' attribute is here">;
+def warn_riscv_interrupt_attribute : Warning<
+   "RISC-V 'interrupt' attribute only applies to functions that have "
+   "%select{no parameters|a 'void' return type}0">,
+   InGroup;
 def warn_unused_parameter : Warning<"unused parameter %0">,
   InGroup, DefaultIgnore;
 def warn_unused_variable : Warning<"unused variable %0">,
   InGroup, DefaultIgnore;
 def warn_unused_local_typedef : Warning<
   "unused %select{typedef|type alias}0 %1">,
   InGroup, DefaultIgnore;
-def warn_unused_property_backing_ivar : 
+def warn_unused_property_backing_ivar :
   Warning<"ivar %0 which backs the property is not "
   "referenced in this property's accessor">,
   InGroup, DefaultIgnore;
Index: include/clang/Basic/Attr.td
===
--- include/clang/Basic/Attr.td
+++ include/clang/Basic/Attr.td
@@ -308,6 +308,7 @@
 def TargetMips32 : TargetArch<["mips", "mipsel"]>;
 def TargetAnyMips : TargetArch<["mips", "mipsel", "mips64", "mips64el"]>;
 def TargetMSP430 : TargetArch<["msp430"]>;
+def TargetRISCV : TargetArch<["riscv32", "riscv64"]>;
 def TargetX86 : TargetArch<["x86"]>;
 def TargetAnyX86 : TargetArch<["x86", "x86_64"]>;
 def TargetWindows : TargetArch<["x86", "x86_64", "arm", "thumb", "aarch64"]> {
@@ -1374,6 +1375,17 @@
   let Documentation = [MicroMipsDocs];
 }
 
+def RISCVInterrupt : InheritableAttr, TargetSpecificAttr {
+  let Spellings = [GCC<"interrupt">];
+  let Subjects = SubjectList<[Function]>;
+  let Args = [EnumArgument<"Interrupt", "InterruptType",
+   ["user", "supervisor", "machine"],
+   ["user", "supervisor", "machine"],
+   1>];
+  let ParseKind = "Interrupt";
+  let Documentation = [RISCVInterruptDocs];
+}
+
 // This is not a TargetSpecificAttr so that is silently accepted and
 // ignored on other targets as encouraged by the OpenCL spec.
 //
Index: test/Sema/riscv-interrupt-attr.c
===
--- test/Sema/riscv-interrupt-attr.c
+++ test/Sema/riscv-interrupt-attr.c
@@ -0,0 +1,62 @@
+// RUN: %clang_cc1 -triple riscv32-unknown-elf -emit-llvm -DCHECK_IR < %s| FileCheck %s
+// RUN: %clang_cc1 -triple riscv64-unknown-elf -emit-llvm -DCHECK_IR < %s| FileCheck %s
+// RUN: %clang_cc1 %s -triple riscv32-unknown-elf -verify -fsyntax-only
+// RUN: %clang_cc1 %s -triple riscv64-unknown-elf -verify -fsyntax-only
+
+#if defined(CHECK_IR)
+// CHECK-LABEL:  @foo_user() #0
+// CHECK: ret void
+__attribute__((interrupt("user"))) void foo_user(void) {}
+// CHECK-LABEL:  @foo_supervisor() #1
+// CHECK: 

r338048 - [Sema][ObjC] Do not propagate the nullability specifier on the receiver

2018-07-26 Thread Akira Hatanaka via cfe-commits
Author: ahatanak
Date: Thu Jul 26 10:51:13 2018
New Revision: 338048

URL: http://llvm.org/viewvc/llvm-project?rev=338048&view=rev
Log:
[Sema][ObjC] Do not propagate the nullability specifier on the receiver
to the result type of a message send if the result type cannot have a
nullability specifier.

Previously, clang would print the following message when the code in
nullability.m was compiled:

"incompatible integer to pointer conversion initializing 'int *' with
an expression of type 'int _Nullable'"

This is wrong as 'int' isn't supposed to have any nullability
specifiers.

rdar://problem/40830514

Modified:
cfe/trunk/lib/Sema/SemaExprObjC.cpp
cfe/trunk/test/SemaObjC/nullability.m

Modified: cfe/trunk/lib/Sema/SemaExprObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExprObjC.cpp?rev=338048&r1=338047&r2=338048&view=diff
==
--- cfe/trunk/lib/Sema/SemaExprObjC.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExprObjC.cpp Thu Jul 26 10:51:13 2018
@@ -1357,6 +1357,11 @@ QualType Sema::getMessageSendResultType(
   if (isClassMessage)
 return resultType;
 
+  // There is nothing left to do if the result type cannot have a nullability
+  // specifier.
+  if (!resultType->canHaveNullability())
+return resultType;
+
   // Map the nullability of the result into a table index.
   unsigned receiverNullabilityIdx = 0;
   if (auto nullability = ReceiverType->getNullability(Context))

Modified: cfe/trunk/test/SemaObjC/nullability.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaObjC/nullability.m?rev=338048&r1=338047&r2=338048&view=diff
==
--- cfe/trunk/test/SemaObjC/nullability.m (original)
+++ cfe/trunk/test/SemaObjC/nullability.m Thu Jul 26 10:51:13 2018
@@ -279,3 +279,14 @@ void test(ArraysInMethods *obj) {
   [obj simpleSugar:0]; // expected-warning {{null passed to a callee that 
requires a non-null argument}}
   [obj sugarWithTypedef:0]; // expected-warning {{null passed to a callee that 
requires a non-null argument}}
 }
+
+// Check that we don't propagate the nullability specifier on the receiver to
+// the result type of a message send if the result type cannot have a
+// nullability specifier.
+@interface C0
+-(int) count;
+@end
+
+void testMessageSendResultType(C0 * _Nullable c0) {
+  int *p = [c0 count]; // expected-warning {{incompatible integer to pointer 
conversion initializing 'int *' with an expression of type 'int'}}
+}


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


r338049 - [OPENMP] What's new for OpenMP in clang.

2018-07-26 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Thu Jul 26 10:53:45 2018
New Revision: 338049

URL: http://llvm.org/viewvc/llvm-project?rev=338049&view=rev
Log:
[OPENMP] What's new for OpenMP in clang.

Updated ReleaseNotes + Status of the OpenMP support in clang.

Modified:
cfe/trunk/docs/OpenMPSupport.rst
cfe/trunk/docs/ReleaseNotes.rst

Modified: cfe/trunk/docs/OpenMPSupport.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/OpenMPSupport.rst?rev=338049&r1=338048&r2=338049&view=diff
==
--- cfe/trunk/docs/OpenMPSupport.rst (original)
+++ cfe/trunk/docs/OpenMPSupport.rst Thu Jul 26 10:53:45 2018
@@ -10,13 +10,15 @@
 .. role:: partial
 .. role:: good
 
+.. contents::
+   :local:
+
 ==
 OpenMP Support
 ==
 
-Clang fully supports OpenMP 3.1 + some elements of OpenMP 4.5. Clang supports 
offloading to X86_64, AArch64 and PPC64[LE] devices.
-Support for Cuda devices is not ready yet.
-The status of major OpenMP 4.5 features support in Clang.
+Clang fully supports OpenMP 4.5. Clang supports offloading to X86_64, AArch64,
+PPC64[LE] and has `basic support for Cuda devices`_.
 
 Standalone directives
 =
@@ -35,7 +37,7 @@ Standalone directives
 
 * #pragma omp target: :good:`Complete`.
 
-* #pragma omp declare target: :partial:`Partial`.  No full codegen support.
+* #pragma omp declare target: :good:`Complete`.
 
 * #pragma omp teams: :good:`Complete`.
 
@@ -64,5 +66,66 @@ Combined directives
 
 * #pragma omp target teams distribute parallel for [simd]: :good:`Complete`.
 
-Clang does not support any constructs/updates from upcoming OpenMP 5.0 except 
for `reduction`-based clauses in the `task` and `target`-based directives.
-In addition, the LLVM OpenMP runtime `libomp` supports the OpenMP Tools 
Interface (OMPT) on x86, x86_64, AArch64, and PPC64 on Linux, Windows, and mac 
OS.
+Clang does not support any constructs/updates from upcoming OpenMP 5.0 except
+for `reduction`-based clauses in the `task` and `target`-based directives.
+
+In addition, the LLVM OpenMP runtime `libomp` supports the OpenMP Tools
+Interface (OMPT) on x86, x86_64, AArch64, and PPC64 on Linux, Windows, and mac 
OS.
+ows, and mac OS.
+
+.. _basic support for Cuda devices:
+
+Cuda devices support
+
+
+Directives execution modes
+--
+
+Clang code generation for target regions supports two modes: the SPMD and
+non-SPMD modes. Clang chooses one of these two modes automatically based on the
+way directives and clauses on those directives are used. The SPMD mode uses a
+simplified set of runtime functions thus increasing performance at the cost of
+supporting some OpenMP features. The non-SPMD mode is the most generic mode and
+supports all currently available OpenMP features. The compiler will always
+attempt to use the SPMD mode wherever possible. SPMD mode will not be used if:
+
+   - The target region contains an `if()` clause that refers to a `parallel`
+ directive.
+
+   - The target region contains a `parallel` directive with a `num_threads()`
+ clause.
+
+   - The target region contains user code (other than OpenMP-specific
+ directives) in between the `target` and the `parallel` directives.
+
+Data-sharing modes
+--
+
+Clang supports two data-sharing models for Cuda devices: `Generic` and `Cuda`
+modes. The default mode is `Generic`. `Cuda` mode can give an additional
+performance and can be activated using the `-fopenmp-cuda-mode` flag. In
+`Generic` mode all local variables that can be shared in the parallel regions
+are stored in the global memory. In `Cuda` mode local variables are not shared
+between the threads and it is user responsibility to share the required data
+between the threads in the parallel regions.
+
+Features not supported or with limited support for Cuda devices
+---
+
+- Reductions across the teams are not supported yet.
+
+- Cancellation constructs are not supported.
+
+- Doacross loop nest is not supported.
+
+- User-defined reductions are supported only for trivial types.
+
+- Nested parallelism: inner parallel regions are executed sequentially.
+
+- Static linking of libraries containing device code is not supported yet.
+
+- Automatic translation of math functions in target regions to device-specific
+  math functions is not implemented yet.
+
+- Debug information for OpenMP target regions is not supported yet.
+

Modified: cfe/trunk/docs/ReleaseNotes.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ReleaseNotes.rst?rev=338049&r1=338048&r2=338049&view=diff
==
--- cfe/trunk/docs/ReleaseNotes.rst (original)
+++ cfe/trunk/docs/ReleaseNotes.rst Thu Jul 26 10:53:45 2018
@@ -216,7 +216,21 @@ OpenCL C Language Changes in Clang
 OpenMP Support in Clang
 

[PATCH] D49848: Parse a possible trailing postfix expression suffix after a fold expression

2018-07-26 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

Shouldn't the caller of ParseParenExpression already be doing this?


Repository:
  rC Clang

https://reviews.llvm.org/D49848



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


Re: r338049 - [OPENMP] What's new for OpenMP in clang.

2018-07-26 Thread Jonas Hahnfeld via cfe-commits

Hi Alexey,

On 2018-07-26 19:53, Alexey Bataev via cfe-commits wrote:

Author: abataev
Date: Thu Jul 26 10:53:45 2018
New Revision: 338049

URL: http://llvm.org/viewvc/llvm-project?rev=338049&view=rev
Log:
[OPENMP] What's new for OpenMP in clang.

Updated ReleaseNotes + Status of the OpenMP support in clang.

Modified:
cfe/trunk/docs/OpenMPSupport.rst
cfe/trunk/docs/ReleaseNotes.rst

Modified: cfe/trunk/docs/OpenMPSupport.rst
[...]

Modified: cfe/trunk/docs/ReleaseNotes.rst
URL:
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ReleaseNotes.rst?rev=338049&r1=338048&r2=338049&view=diff
==
--- cfe/trunk/docs/ReleaseNotes.rst (original)
+++ cfe/trunk/docs/ReleaseNotes.rst Thu Jul 26 10:53:45 2018
@@ -216,7 +216,21 @@ OpenCL C Language Changes in Clang
 OpenMP Support in Clang
 --

-- ...
+- Clang gained basic support for OpenMP 4.5 offloading for NVPTX 
target.

+   To compile your program for NVPTX target use the following options:
+   `-fopenmp -fopenmp-targets=nvptx64-nvidia-cuda` for 64 bit 
platforms or

+   `-fopenmp -fopenmp-targets=nvptx-nvidia-cuda` for 32 bit platform.
+
+- Passing options to the OpenMP device offloading toolchain can be 
done using
+  the `-Xopenmp-target= -opt=val` flag. In this way the 
`-opt=val`
+  option will be forwarded to the respective OpenMP device offloading 
toolchain
+  described by the triple. For example passing the compute capability 
to

+  the OpenMP NVPTX offloading toolchain can be done as follows:
+  `-Xopenmp-target=nvptx62-nvidia-cuda -march=sm_60`.


Is that a typo and should say "nvptx64"?
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r338050 - [COFF, ARM64] Decide when to mark struct returns as SRet

2018-07-26 Thread Mandeep Singh Grang via cfe-commits
Author: mgrang
Date: Thu Jul 26 11:07:59 2018
New Revision: 338050

URL: http://llvm.org/viewvc/llvm-project?rev=338050&view=rev
Log:
[COFF, ARM64] Decide when to mark struct returns as SRet

Summary:
Refer the MS ARM64 ABI Convention for the behavior for struct returns:
https://docs.microsoft.com/en-us/cpp/build/arm64-windows-abi-conventions#return-values

Reviewers: mstorsjo, compnerd, rnk, javed.absar, yinma, efriedma

Reviewed By: rnk, efriedma

Subscribers: haripul, TomTan, yinma, efriedma, kristof.beyls, chrib, 
llvm-commits

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

Added:
cfe/trunk/test/CodeGen/arm64-microsoft-arguments.cpp
Modified:
cfe/trunk/include/clang/CodeGen/CGFunctionInfo.h
cfe/trunk/lib/CodeGen/CGCall.cpp
cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp

Modified: cfe/trunk/include/clang/CodeGen/CGFunctionInfo.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/CodeGen/CGFunctionInfo.h?rev=338050&r1=338049&r2=338050&view=diff
==
--- cfe/trunk/include/clang/CodeGen/CGFunctionInfo.h (original)
+++ cfe/trunk/include/clang/CodeGen/CGFunctionInfo.h Thu Jul 26 11:07:59 2018
@@ -96,6 +96,7 @@ private:
   bool InReg : 1;   // isDirect() || isExtend() || isIndirect()
   bool CanBeFlattened: 1;   // isDirect()
   bool SignExt : 1; // isExtend()
+  bool SuppressSRet : 1;// isIndirect()
 
   bool canHavePaddingType() const {
 return isDirect() || isExtend() || isIndirect() || isExpand();
@@ -111,13 +112,14 @@ private:
   }
 
   ABIArgInfo(Kind K)
-  : TheKind(K), PaddingInReg(false), InReg(false) {
+  : TheKind(K), PaddingInReg(false), InReg(false), SuppressSRet(false) {
   }
 
 public:
   ABIArgInfo()
   : TypeData(nullptr), PaddingType(nullptr), DirectOffset(0),
-TheKind(Direct), PaddingInReg(false), InReg(false) {}
+TheKind(Direct), PaddingInReg(false), InReg(false),
+SuppressSRet(false) {}
 
   static ABIArgInfo getDirect(llvm::Type *T = nullptr, unsigned Offset = 0,
   llvm::Type *Padding = nullptr,
@@ -406,6 +408,16 @@ public:
 CanBeFlattened = Flatten;
   }
 
+  bool getSuppressSRet() const {
+assert(isIndirect() && "Invalid kind!");
+return SuppressSRet;
+  }
+
+  void setSuppressSRet(bool Suppress) {
+assert(isIndirect() && "Invalid kind!");
+SuppressSRet = Suppress;
+  }
+
   void dump() const;
 };
 

Modified: cfe/trunk/lib/CodeGen/CGCall.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=338050&r1=338049&r2=338050&view=diff
==
--- cfe/trunk/lib/CodeGen/CGCall.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGCall.cpp Thu Jul 26 11:07:59 2018
@@ -1988,7 +1988,8 @@ void CodeGenModule::ConstructAttributeLi
   // Attach attributes to sret.
   if (IRFunctionArgs.hasSRetArg()) {
 llvm::AttrBuilder SRETAttrs;
-SRETAttrs.addAttribute(llvm::Attribute::StructRet);
+if (!RetAI.getSuppressSRet())
+  SRETAttrs.addAttribute(llvm::Attribute::StructRet);
 hasUsedSRet = true;
 if (RetAI.getInReg())
   SRETAttrs.addAttribute(llvm::Attribute::InReg);

Modified: cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp?rev=338050&r1=338049&r2=338050&view=diff
==
--- cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp (original)
+++ cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp Thu Jul 26 11:07:59 2018
@@ -1060,10 +1060,22 @@ bool MicrosoftCXXABI::classifyReturnType
 // the second parameter.
 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
+
+// aarch64-windows requires that instance methods use X1 for the return
+// address. So for aarch64-windows we do not mark the
+// return as SRet.
+FI.getReturnInfo().setSuppressSRet(CGM.getTarget().getTriple().getArch() ==
+   llvm::Triple::aarch64);
 return true;
   } else if (!RD->isPOD()) {
 // If it's a free function, non-POD types are returned indirectly.
 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
+
+// aarch64-windows requires that non-POD, non-instance returns use X0 for
+// the return address. So for aarch64-windows we do not mark the return as
+// SRet.
+FI.getReturnInfo().setSuppressSRet(CGM.getTarget().getTriple().getArch() ==
+   llvm::Triple::aarch64);
 return true;
   }
 

Added: cfe/trunk/test/CodeGen/arm64-microsoft-arguments.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/arm64-microsoft-arguments.cpp?rev=338050&view=auto
==
--- cfe/trunk/test/Code

  1   2   >