[PATCH] D48961: [Index] Add indexing support for MACROs.

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



Comment at: include/clang/Index/IndexDataConsumer.h:48
   /// \returns true to continue indexing, or false to abort.
-  virtual bool handleMacroOccurence(const IdentifierInfo *Name,
-const MacroInfo *MI, SymbolRoleSet Roles,
+  virtual bool handleMacroOccurence(const IdentifierInfo &Name,
+const MacroInfo &MI, SymbolRoleSet Roles,

the change from pointer->reference seems maybe unneccesary, and inconsistent 
with other callbacks? up to you though, doesn't seem like a big deal either way.



Comment at: include/clang/Index/IndexSymbol.h:105
+  Implicit = 1 << 8,
+  // FIXME: this is not mirrored in CXSymbolRole.
+  Undefinition = 1 << 9, // macro #undef

maybe mention that macro occurrences aren't currently reported by libclang? as 
it's related.



Comment at: lib/Index/IndexingContext.cpp:422
+   const MacroInfo &MI) {
+  SymbolRoleSet Roles = (unsigned)SymbolRole::Reference;
+  DataConsumer.handleMacroOccurence(Name, MI, Roles, Loc, /*Undefined=*/true);

this should be Undefinition (and drop the Undefined flag).


Repository:
  rC Clang

https://reviews.llvm.org/D48961



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


r336521 - [clang-format/ObjC] Put ObjC method arguments into one line when they fit

2018-07-09 Thread Jacek Olesiak via cfe-commits
Author: jolesiak
Date: Mon Jul  9 00:08:45 2018
New Revision: 336521

URL: http://llvm.org/viewvc/llvm-project?rev=336521&view=rev
Log:
[clang-format/ObjC] Put ObjC method arguments into one line when they fit

Reapply D47195:
Currently BreakBeforeParameter is set to true everytime message receiver spans 
multiple lines, e.g.:
```
[[object block:^{
  return 42;
}] aa:42 bb:42];
```
will be formatted:
```
[[object block:^{
  return 42;
}] aa:42
   bb:42];
```
even though arguments could fit into one line. This change fixes this behavior.

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=336521&r1=336520&r2=336521&view=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Mon Jul  9 00:08:45 2018
@@ -1398,6 +1398,30 @@ void ContinuationIndenter::moveStatePast
(Current.is(tok::greater) && Current.is(TT_DictLiteral
 State.Stack.pop_back();
 
+  // Reevaluate whether ObjC message arguments fit into one line.
+  // If a receiver spans multiple lines, e.g.:
+  //   [[object block:^{
+  // return 42;
+  //   }] a:42 b:42];
+  // BreakBeforeParameter is calculated based on an incorrect assumption
+  // (it is checked whether the whole expression fits into one line without
+  // considering a line break inside a message receiver).
+  // We check whether arguements fit after receiver scope closer (into the same
+  // line).
+  if (State.Stack.back().BreakBeforeParameter && Current.MatchingParen &&
+  Current.MatchingParen->Previous) {
+const FormatToken &CurrentScopeOpener = *Current.MatchingParen->Previous;
+if (CurrentScopeOpener.is(TT_ObjCMethodExpr) &&
+CurrentScopeOpener.MatchingParen) {
+  int NecessarySpaceInLine =
+  getLengthToMatchingParen(CurrentScopeOpener, State.Stack) +
+  CurrentScopeOpener.TotalLength - Current.TotalLength - 1;
+  if (State.Column + Current.ColumnWidth + NecessarySpaceInLine <=
+  Style.ColumnLimit)
+State.Stack.back().BreakBeforeParameter = false;
+}
+  }
+
   if (Current.is(tok::r_square)) {
 // If this ends the array subscript expr, reset the corresponding value.
 const FormatToken *NextNonComment = Current.getNextNonComment();

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=336521&r1=336520&r2=336521&view=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Mon Jul  9 00:08:45 2018
@@ -820,6 +820,48 @@ TEST_F(FormatTestObjC, FormatObjCMethodE
   verifyFormat("aa = [aa aa:aa\n"
" aa:aa];");
 
+  // Message receiver taking multiple lines.
+  // Non-corner case.
+  verifyFormat("[[object block:^{\n"
+   "  return 42;\n"
+   "}] a:42 b:42];");
+  // Arguments just fit into one line.
+  verifyFormat("[[object block:^{\n"
+   "  return 42;\n"
+   "}] aaa:42 b:42];");
+  // Arguments just over a column limit.
+  verifyFormat("[[object block:^{\n"
+   "  return 42;\n"
+   "}] aaa:42\n"
+   "bb:42];");
+  // Arguments just fit into one line.
+  Style.ColumnLimit = 23;
+  verifyFormat("[[obj a:42\n"
+   "  b:42\n"
+   "  c:42\n"
+   "  d:42] e:42 f:42];");
+
+  // Arguments do not fit into one line with a receiver.
+  Style.ColumnLimit = 20;
+  verifyFormat("[[obj a:42] a:42\n"
+   "b:42];");
+  verifyFormat("[[obj a:42] a:42\n"
+   "b:42\n"
+   "c:42];");
+  verifyFormat("[[obj aa:42\n"
+   "   b:42]\n"
+   "cc:42\n"
+   " d:42];");
+
+  // Avoid breaking receiver expression.
+  Style.ColumnLimit = 30;
+  verifyFormat("fooo =\n"
+   "[[obj fooo] aaa:42\n"
+   "aaa:42];");
+  verifyFormat("[[[obj foo] bar] aa:42\n"
+   " bb:42\n"
+   " cc:42];");
+
   Style.ColumnLimit = 70;
   verifyFormat(
   "void f() {\n"


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


[PATCH] D49028: [clangd] Support indexing MACROs.

2018-07-09 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clangd/index/SymbolCollector.cpp:309
 
+  llvm::SmallString<128> USR;
+  if (index::generateUSRForDecl(ND, USR))

why this change? I think this makes us run generateUSR much more often (once 
per non-unique reference in *any* file, vs unique refeneces in main file), 
keeping track of a few extra referenced symbols by pointer should be much 
cheaper



Comment at: clangd/index/SymbolCollector.cpp:349
+   SourceLocation Loc) {
+  assert(PP.get() && "Preprocessor must be set.");
+  if (!Opts.CollectMacro)

drop the message unless it has something new to say



Comment at: clangd/index/SymbolCollector.cpp:349
+   SourceLocation Loc) {
+  assert(PP.get() && "Preprocessor must be set.");
+  if (!Opts.CollectMacro)

sammccall wrote:
> drop the message unless it has something new to say
(why) do we require PP to be set if CollectMacro is false?



Comment at: clangd/index/SymbolCollector.cpp:356
+return true;
+  // Builtin macro should already be available in sema.
+  if (MI.isUsedForHeaderGuard() || MI.isBuiltinMacro())

not sure what this means. Are you talking about code completion? This isn't 
CodeComplete :-)

Header guard macros are clearly not useful in the index, but are probably worth 
a comment. Builtin macros don't have useful locations, and also aren't needed 
for code completion as you say.



Comment at: clangd/index/SymbolCollector.cpp:360
+
+  llvm::SmallString<128> USR;
+  if (index::generateUSRForMacro(Name.getName(), MI.getDefinitionLoc(), SM,

as above, can we avoid generating the USR for every reference?
The macro name or hash thereof should be enough to identify it, right?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49028



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


[PATCH] D48266: [Driver] Add -fno-digraphs

2018-07-09 Thread Jacob Bandes-Storch via Phabricator via cfe-commits
jtbandes added a comment.

Friendly ping!


Repository:
  rC Clang

https://reviews.llvm.org/D48266



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


[PATCH] D49063: [libclang] Add support for ObjCObjectType

2018-07-09 Thread Michael Wu via Phabricator via cfe-commits
michaelwu created this revision.

This patch adds support to the clang-c API for identifying ObjCObjects in 
CXTypes, enumerating type args and protocols on ObjCObjectTypes, and retrieving 
the base type of ObjCObjectTypes. Currently only ObjCInterfaceTypes are 
exposed, which do not have type args or protocols.


Repository:
  rC Clang

https://reviews.llvm.org/D49063

Files:
  include/clang-c/Index.h
  test/Index/objc-typeargs-protocols.m
  test/Index/print-type.m
  tools/c-index-test/c-index-test.c
  tools/libclang/CXType.cpp
  tools/libclang/libclang.exports

Index: tools/libclang/libclang.exports
===
--- tools/libclang/libclang.exports
+++ tools/libclang/libclang.exports
@@ -98,6 +98,11 @@
 clang_Type_visitFields
 clang_Type_getNamedType
 clang_Type_isTransparentTagTypedef
+clang_Type_getObjCObjectBaseType
+clang_Type_getNumObjCProtocolRefs
+clang_Type_getObjCProtocolDecl
+clang_Type_getNumObjCTypeArgs
+clang_Type_getObjCTypeArg
 clang_VerbatimBlockLineComment_getText
 clang_VerbatimLineComment_getText
 clang_HTMLTagComment_getAsString
Index: tools/libclang/CXType.cpp
===
--- tools/libclang/CXType.cpp
+++ tools/libclang/CXType.cpp
@@ -98,6 +98,7 @@
 TKCASE(Enum);
 TKCASE(Typedef);
 TKCASE(ObjCInterface);
+TKCASE(ObjCObject);
 TKCASE(ObjCObjectPointer);
 TKCASE(FunctionNoProto);
 TKCASE(FunctionProto);
@@ -575,6 +576,7 @@
 TKIND(Enum);
 TKIND(Typedef);
 TKIND(ObjCInterface);
+TKIND(ObjCObject);
 TKIND(ObjCObjectPointer);
 TKIND(FunctionNoProto);
 TKIND(FunctionProto);
@@ -1098,6 +1100,74 @@
   return MakeCXType(QT.getValueOr(QualType()), GetTU(CT));
 }
 
+CXType clang_Type_getObjCObjectBaseType(CXType CT) {
+  QualType T = GetQualType(CT);
+  if (T.isNull())
+return MakeCXType(QualType(), GetTU(CT));
+
+  const ObjCObjectType *OT = dyn_cast(T);
+  if (!OT)
+return MakeCXType(QualType(), GetTU(CT));
+
+  return MakeCXType(OT->getBaseType(), GetTU(CT));
+}
+
+int clang_Type_getNumObjCProtocolRefs(CXType CT) {
+  QualType T = GetQualType(CT);
+  if (T.isNull())
+return -1;
+
+  const ObjCObjectType *OT = dyn_cast(T);
+  if (!OT)
+return -1;
+
+  return OT->getNumProtocols();
+}
+
+CXCursor clang_Type_getObjCProtocolDecl(CXType CT, unsigned i) {
+  QualType T = GetQualType(CT);
+  if (T.isNull())
+return cxcursor::MakeCXCursorInvalid(CXCursor_NoDeclFound);
+
+  const ObjCObjectType *OT = dyn_cast(T);
+  if (!OT)
+return cxcursor::MakeCXCursorInvalid(CXCursor_NoDeclFound);
+
+  const ObjCProtocolDecl *PD = OT->getProtocol(i);
+  if (!PD)
+return cxcursor::MakeCXCursorInvalid(CXCursor_NoDeclFound);
+
+  return cxcursor::MakeCXCursor(PD, GetTU(CT));
+}
+
+int clang_Type_getNumObjCTypeArgs(CXType CT) {
+  QualType T = GetQualType(CT);
+  if (T.isNull())
+return -1;
+
+  const ObjCObjectType *OT = dyn_cast(T);
+  if (!OT)
+return -1;
+
+  return OT->getTypeArgs().size();
+}
+
+CXType clang_Type_getObjCTypeArg(CXType CT, unsigned i) {
+  QualType T = GetQualType(CT);
+  if (T.isNull())
+return MakeCXType(QualType(), GetTU(CT));
+
+  const ObjCObjectType *OT = dyn_cast(T);
+  if (!OT)
+return MakeCXType(QualType(), GetTU(CT));
+
+  const ArrayRef TA = OT->getTypeArgs();
+  if ((size_t)i >= TA.size())
+return MakeCXType(QualType(), GetTU(CT));
+
+  return MakeCXType(TA[i], GetTU(CT));
+}
+
 unsigned clang_Type_visitFields(CXType PT,
 CXFieldVisitor visitor,
 CXClientData client_data){
Index: tools/c-index-test/c-index-test.c
===
--- tools/c-index-test/c-index-test.c
+++ tools/c-index-test/c-index-test.c
@@ -1500,6 +1500,7 @@
  CXClientData d) {
   if (!clang_isInvalid(clang_getCursorKind(cursor))) {
 CXType T = clang_getCursorType(cursor);
+CXType PT = clang_getPointeeType(T);
 enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
 PrintCursor(cursor, NULL);
 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
@@ -1545,11 +1546,45 @@
 printf("]");
   }
 }
+/* Print ObjC base types, type arguments, and protocol list if available. */
+{
+  CXType BT = clang_Type_getObjCObjectBaseType(PT);
+  if (BT.kind != CXType_Invalid) {
+PrintTypeAndTypeKind(BT, " [basetype=%s] [basekind=%s]");
+  }
+}
+{
+  int NumTypeArgs = clang_Type_getNumObjCTypeArgs(PT);
+  if (NumTypeArgs > 0) {
+int i;
+	printf(" [typeargs=");
+	for (i = 0; i < NumTypeArgs; ++i) {
+	  CXType TA = clang_Type_getObjCTypeArg(PT, i);
+	  if (TA.kind != CXType_Invalid) {
+PrintTypeAndTypeKind(TA, " [%s] [%s]");
+	  }
+	}
+	printf("]");
+  }
+}
+{
+  int NumProtocols = clang_Type_getNumObjCProtocolRefs(PT);
+  if (NumProtocols > 0) {
+ 

[PATCH] D49063: [libclang] Add support for ObjCObjectType

2018-07-09 Thread Michael Wu via Phabricator via cfe-commits
michaelwu updated this revision to Diff 154540.
michaelwu added a comment.

Replaced tabs with spaces.


https://reviews.llvm.org/D49063

Files:
  include/clang-c/Index.h
  test/Index/objc-typeargs-protocols.m
  test/Index/print-type.m
  tools/c-index-test/c-index-test.c
  tools/libclang/CXType.cpp
  tools/libclang/libclang.exports

Index: tools/libclang/libclang.exports
===
--- tools/libclang/libclang.exports
+++ tools/libclang/libclang.exports
@@ -98,6 +98,11 @@
 clang_Type_visitFields
 clang_Type_getNamedType
 clang_Type_isTransparentTagTypedef
+clang_Type_getObjCObjectBaseType
+clang_Type_getNumObjCProtocolRefs
+clang_Type_getObjCProtocolDecl
+clang_Type_getNumObjCTypeArgs
+clang_Type_getObjCTypeArg
 clang_VerbatimBlockLineComment_getText
 clang_VerbatimLineComment_getText
 clang_HTMLTagComment_getAsString
Index: tools/libclang/CXType.cpp
===
--- tools/libclang/CXType.cpp
+++ tools/libclang/CXType.cpp
@@ -98,6 +98,7 @@
 TKCASE(Enum);
 TKCASE(Typedef);
 TKCASE(ObjCInterface);
+TKCASE(ObjCObject);
 TKCASE(ObjCObjectPointer);
 TKCASE(FunctionNoProto);
 TKCASE(FunctionProto);
@@ -575,6 +576,7 @@
 TKIND(Enum);
 TKIND(Typedef);
 TKIND(ObjCInterface);
+TKIND(ObjCObject);
 TKIND(ObjCObjectPointer);
 TKIND(FunctionNoProto);
 TKIND(FunctionProto);
@@ -1098,6 +1100,74 @@
   return MakeCXType(QT.getValueOr(QualType()), GetTU(CT));
 }
 
+CXType clang_Type_getObjCObjectBaseType(CXType CT) {
+  QualType T = GetQualType(CT);
+  if (T.isNull())
+return MakeCXType(QualType(), GetTU(CT));
+
+  const ObjCObjectType *OT = dyn_cast(T);
+  if (!OT)
+return MakeCXType(QualType(), GetTU(CT));
+
+  return MakeCXType(OT->getBaseType(), GetTU(CT));
+}
+
+int clang_Type_getNumObjCProtocolRefs(CXType CT) {
+  QualType T = GetQualType(CT);
+  if (T.isNull())
+return -1;
+
+  const ObjCObjectType *OT = dyn_cast(T);
+  if (!OT)
+return -1;
+
+  return OT->getNumProtocols();
+}
+
+CXCursor clang_Type_getObjCProtocolDecl(CXType CT, unsigned i) {
+  QualType T = GetQualType(CT);
+  if (T.isNull())
+return cxcursor::MakeCXCursorInvalid(CXCursor_NoDeclFound);
+
+  const ObjCObjectType *OT = dyn_cast(T);
+  if (!OT)
+return cxcursor::MakeCXCursorInvalid(CXCursor_NoDeclFound);
+
+  const ObjCProtocolDecl *PD = OT->getProtocol(i);
+  if (!PD)
+return cxcursor::MakeCXCursorInvalid(CXCursor_NoDeclFound);
+
+  return cxcursor::MakeCXCursor(PD, GetTU(CT));
+}
+
+int clang_Type_getNumObjCTypeArgs(CXType CT) {
+  QualType T = GetQualType(CT);
+  if (T.isNull())
+return -1;
+
+  const ObjCObjectType *OT = dyn_cast(T);
+  if (!OT)
+return -1;
+
+  return OT->getTypeArgs().size();
+}
+
+CXType clang_Type_getObjCTypeArg(CXType CT, unsigned i) {
+  QualType T = GetQualType(CT);
+  if (T.isNull())
+return MakeCXType(QualType(), GetTU(CT));
+
+  const ObjCObjectType *OT = dyn_cast(T);
+  if (!OT)
+return MakeCXType(QualType(), GetTU(CT));
+
+  const ArrayRef TA = OT->getTypeArgs();
+  if ((size_t)i >= TA.size())
+return MakeCXType(QualType(), GetTU(CT));
+
+  return MakeCXType(TA[i], GetTU(CT));
+}
+
 unsigned clang_Type_visitFields(CXType PT,
 CXFieldVisitor visitor,
 CXClientData client_data){
Index: tools/c-index-test/c-index-test.c
===
--- tools/c-index-test/c-index-test.c
+++ tools/c-index-test/c-index-test.c
@@ -1500,6 +1500,7 @@
  CXClientData d) {
   if (!clang_isInvalid(clang_getCursorKind(cursor))) {
 CXType T = clang_getCursorType(cursor);
+CXType PT = clang_getPointeeType(T);
 enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
 PrintCursor(cursor, NULL);
 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
@@ -1545,11 +1546,45 @@
 printf("]");
   }
 }
+/* Print ObjC base types, type arguments, and protocol list if available. */
+{
+  CXType BT = clang_Type_getObjCObjectBaseType(PT);
+  if (BT.kind != CXType_Invalid) {
+PrintTypeAndTypeKind(BT, " [basetype=%s] [basekind=%s]");
+  }
+}
+{
+  int NumTypeArgs = clang_Type_getNumObjCTypeArgs(PT);
+  if (NumTypeArgs > 0) {
+int i;
+printf(" [typeargs=");
+for (i = 0; i < NumTypeArgs; ++i) {
+  CXType TA = clang_Type_getObjCTypeArg(PT, i);
+  if (TA.kind != CXType_Invalid) {
+PrintTypeAndTypeKind(TA, " [%s] [%s]");
+  }
+}
+printf("]");
+  }
+}
+{
+  int NumProtocols = clang_Type_getNumObjCProtocolRefs(PT);
+  if (NumProtocols > 0) {
+int i;
+printf(" [protocols=");
+for (i = 0; i < NumProtocols; ++i) {
+  CXCursor P = clang_Type_getObjCProtocolDecl(PT, i);
+  if (!clang_isInvalid(cl

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

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

In https://reviews.llvm.org/D48903#1154846, @simark wrote:

> With the `InMemoryFileSystem`, this now returns a non-real path.  The result 
> is that we fill `RealPathName` with that non-real path.  I see two options 
> here:
>
> 1. Either the FileManager is wrong to assume that `File::getName` returns a 
> real path, and should call `FS->getRealPath` to do the job.
> 2. If the contract is that the ` File::getName` interface should return a 
> real path, then we should fix the `File::getName` implementation to do that 
> somehow.
>
>   I would opt for 1.  This way, we could compute the `RealPathName` field 
> even if we don't open the file (unlike currently).


I'd also say `FileManager` should use `FileSystem::getRealPath`. The code that 
does it differently was there before `FileSystem::getRealPath` was added.
And `RealFile` should probably not do any magic in `getName`, we could add a 
separate method for (`getRealName`?) if that's absolutely needed.

Refactorings in that area would probably break stuff and won't be trivial and I 
don't think this change should be blocked by those. So I'd be happy if this 
landed right away with a FIXME in `FileManager` mentioning that 
`InMemoryFileSystem` might give surprising results there.
@ioeric added `FileSystem::getRealPath`, he may more ideas on how we should 
proceed.




Comment at: lib/Basic/VirtualFileSystem.cpp:516
+  explicit InMemoryFileAdaptor(InMemoryFile &Node, std::string RequestedName)
+  : Node(Node), RequestedName (std::move (RequestedName))
+  {}

simark wrote:
> ilya-biryukov wrote:
> > NIT: The formatting is broken here.
> Hmm this is what git-clang-format does (unless this comment refers to a 
> previous version where I had not run clang-format).
This LG now, it was unindented in the original version.



Comment at: lib/Basic/VirtualFileSystem.cpp:724
+  Status St = (*Node)->getStatus();
+  return Status::copyWithNewName(St, Path.str());
+}

simark wrote:
> ilya-biryukov wrote:
> > NIT: we don't need `str()` here
> Otherwise I'm getting this:
> 
> ```
> /home/emaisin/src/llvm/tools/clang/lib/Basic/VirtualFileSystem.cpp:1673:9: 
> error: no matching function for call to 'copyWithNewName'
> S = Status::copyWithNewName(S, Path);
> ^~~
> /home/emaisin/src/llvm/tools/clang/lib/Basic/VirtualFileSystem.cpp:76:16: 
> note: candidate function not viable: no known conversion from 'const 
> llvm::Twine' to 'llvm::StringRef' for 2nd argument
> Status Status::copyWithNewName(const Status &In, StringRef NewName) {
>^
> /home/emaisin/src/llvm/tools/clang/lib/Basic/VirtualFileSystem.cpp:82:16: 
> note: candidate function not viable: no known conversion from 
> 'clang::vfs::Status' to 'const llvm::sys::fs::file_status' for 1st argument
> Status Status::copyWithNewName(const file_status &In, StringRef NewName) {
>^
> ```
Sorry, I thought Path is `StringRef`, but it's actually `Twine`, so we do need 
the str() call.


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-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: lib/Basic/VirtualFileSystem.cpp:488
+  }
+  StringRef getName() const { return Stat.getName(); }
   InMemoryNodeKind getKind() const { return Kind; }

Given that this method is inconsistent with `getStatus()` and seems to be only 
used in `toString` methods, maybe we could make it `protected`? Otherwise it's 
really easy to write code that gets the wrong path.


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] D48961: [Index] Add indexing support for MACROs.

2018-07-09 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 154543.
ioeric marked 2 inline comments as done.
ioeric added a comment.

- addressed review comments.


Repository:
  rC Clang

https://reviews.llvm.org/D48961

Files:
  include/clang/Index/IndexSymbol.h
  include/clang/Index/IndexingAction.h
  lib/Index/IndexSymbol.cpp
  lib/Index/IndexingAction.cpp
  lib/Index/IndexingContext.cpp
  lib/Index/IndexingContext.h
  test/Index/Core/index-macros.c
  tools/c-index-test/core_main.cpp

Index: tools/c-index-test/core_main.cpp
===
--- tools/c-index-test/core_main.cpp
+++ tools/c-index-test/core_main.cpp
@@ -7,6 +7,7 @@
 //
 //===--===//
 
+#include "clang/Basic/LangOptions.h"
 #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
 #include "clang/Frontend/ASTUnit.h"
 #include "clang/Frontend/CompilerInstance.h"
@@ -16,6 +17,7 @@
 #include "clang/Index/IndexDataConsumer.h"
 #include "clang/Index/USRGeneration.h"
 #include "clang/Index/CodegenNameGenerator.h"
+#include "clang/Lex/Preprocessor.h"
 #include "clang/Serialization/ASTReader.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Signals.h"
@@ -77,6 +79,7 @@
 class PrintIndexDataConsumer : public IndexDataConsumer {
   raw_ostream &OS;
   std::unique_ptr CGNameGen;
+  std::shared_ptr PP;
 
 public:
   PrintIndexDataConsumer(raw_ostream &OS) : OS(OS) {
@@ -86,6 +89,10 @@
 CGNameGen.reset(new CodegenNameGenerator(Ctx));
   }
 
+  void setPreprocessor(std::shared_ptr PP) override {
+this->PP = std::move(PP);
+  }
+
   bool handleDeclOccurence(const Decl *D, SymbolRoleSet Roles,
ArrayRef Relations,
SourceLocation Loc, ASTNodeInfo ASTNode) override {
@@ -145,6 +152,37 @@
 
 return true;
   }
+
+  bool handleMacroOccurence(const IdentifierInfo *Name, const MacroInfo *MI,
+SymbolRoleSet Roles, SourceLocation Loc) override {
+assert(PP);
+SourceManager &SM = PP->getSourceManager();
+
+Loc = SM.getFileLoc(Loc);
+FileID FID = SM.getFileID(Loc);
+unsigned Line = SM.getLineNumber(FID, SM.getFileOffset(Loc));
+unsigned Col = SM.getColumnNumber(FID, SM.getFileOffset(Loc));
+OS << Line << ':' << Col << " | ";
+
+printSymbolInfo(getSymbolInfoForMacro(*MI), OS);
+OS << " | ";
+
+OS << Name->getName();
+OS << " | ";
+
+SmallString<256> USRBuf;
+if (generateUSRForMacro(Name->getName(), MI->getDefinitionLoc(), SM,
+USRBuf)) {
+  OS << "";
+} else {
+  OS << USRBuf;
+}
+OS << " | ";
+
+printSymbolRoles(Roles, OS);
+OS << " |\n";
+return true;
+  }
 };
 
 } // anonymous namespace
Index: test/Index/Core/index-macros.c
===
--- /dev/null
+++ test/Index/Core/index-macros.c
@@ -0,0 +1,12 @@
+// RUN: c-index-test core -print-source-symbols -- %s | FileCheck %s
+
+// CHECK: [[@LINE+1]]:9 | macro/C | X1 | c:index-macros.c@157@macro@X1 | Def |
+#define X1 1
+// CHECK: [[@LINE+1]]:9 | macro/C | DEF | c:index-macros.c@251@macro@DEF | Def |
+#define DEF(x) int x
+// CHECK: [[@LINE+1]]:8 | macro/C | X1 | c:index-macros.c@157@macro@X1 | Undef |
+#undef X1
+
+// CHECK: [[@LINE+2]]:1 | macro/C | DEF | c:index-macros.c@251@macro@DEF | Ref |
+// CHECK: [[@LINE+1]]:5 | variable/C | i | c:@i | i | Def | rel: 0
+DEF(i);
Index: lib/Index/IndexingContext.h
===
--- lib/Index/IndexingContext.h
+++ lib/Index/IndexingContext.h
@@ -10,9 +10,11 @@
 #ifndef LLVM_CLANG_LIB_INDEX_INDEXINGCONTEXT_H
 #define LLVM_CLANG_LIB_INDEX_INDEXINGCONTEXT_H
 
+#include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Index/IndexSymbol.h"
 #include "clang/Index/IndexingAction.h"
+#include "clang/Lex/MacroInfo.h"
 #include "llvm/ADT/ArrayRef.h"
 
 namespace clang {
@@ -80,6 +82,15 @@
const Expr *RefE = nullptr,
const Decl *RefD = nullptr);
 
+  void handleMacroDefined(const IdentifierInfo &Name, SourceLocation Loc,
+  const MacroInfo &MI);
+
+  void handleMacroUndefined(const IdentifierInfo &Name, SourceLocation Loc,
+const MacroInfo &MI);
+
+  void handleMacroReference(const IdentifierInfo &Name, SourceLocation Loc,
+const MacroInfo &MD);
+
   bool importedModule(const ImportDecl *ImportD);
 
   bool indexDecl(const Decl *D);
Index: lib/Index/IndexingContext.cpp
===
--- lib/Index/IndexingContext.cpp
+++ lib/Index/IndexingContext.cpp
@@ -8,6 +8,7 @@
 //===--===//
 
 #include "IndexingContext.h"
+#include "clang/Basic/SourceLocation.h"
 #include "clang/Index/IndexDataConsumer.h

r336523 - [ASTImporter] import FunctionDecl end locations

2018-07-09 Thread Rafael Stahl via cfe-commits
Author: r.stahl
Date: Mon Jul  9 01:40:17 2018
New Revision: 336523

URL: http://llvm.org/viewvc/llvm-project?rev=336523&view=rev
Log:
[ASTImporter] import FunctionDecl end locations

Summary: On constructors that do not take the end source location, it was not 
imported. Fixes test from D47698 / rC336269.

Reviewers: martong, a.sidorin, balazske, xazax.hun, a_sidorin

Reviewed By: martong, a_sidorin

Subscribers: a_sidorin, rnkovacs, cfe-commits

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

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

Modified: cfe/trunk/lib/AST/ASTImporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTImporter.cpp?rev=336523&r1=336522&r2=336523&view=diff
==
--- cfe/trunk/lib/AST/ASTImporter.cpp (original)
+++ cfe/trunk/lib/AST/ASTImporter.cpp Mon Jul  9 01:40:17 2018
@@ -2554,7 +2554,7 @@ Decl *ASTNodeImporter::VisitFunctionDecl
D->isInlineSpecified(),
FromConversion->isExplicit(),
D->isConstexpr(),
-   Importer.Import(D->getLocEnd()));
+   SourceLocation());
   } else if (auto *Method = dyn_cast(D)) {
 ToFunction = CXXMethodDecl::Create(Importer.getToContext(), 
cast(DC),
@@ -2563,7 +2563,7 @@ Decl *ASTNodeImporter::VisitFunctionDecl
Method->getStorageClass(),
Method->isInlineSpecified(),
D->isConstexpr(),
-   Importer.Import(D->getLocEnd()));
+   SourceLocation());
   } else {
 ToFunction = FunctionDecl::Create(Importer.getToContext(), DC,
   InnerLocStart,
@@ -2580,6 +2580,7 @@ Decl *ASTNodeImporter::VisitFunctionDecl
   ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
   ToFunction->setTrivial(D->isTrivial());
   ToFunction->setPure(D->isPure());
+  ToFunction->setRangeEnd(Importer.Import(D->getLocEnd()));
   Importer.Imported(D, ToFunction);
 
   // Set the parameters.

Modified: cfe/trunk/unittests/AST/ASTImporterTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/AST/ASTImporterTest.cpp?rev=336523&r1=336522&r2=336523&view=diff
==
--- cfe/trunk/unittests/AST/ASTImporterTest.cpp (original)
+++ cfe/trunk/unittests/AST/ASTImporterTest.cpp Mon Jul  9 01:40:17 2018
@@ -1620,7 +1620,7 @@ TEST_P(ASTImporterTestBase, ImportSource
   FromSM);
 }
 
-TEST_P(ASTImporterTestBase, DISABLED_ImportNestedMacro) {
+TEST_P(ASTImporterTestBase, ImportNestedMacro) {
   Decl *FromTU = getTuDecl(
   R"(
   #define FUNC_INT void declToImport


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


[PATCH] D48941: [ASTImporter] import FunctionDecl end locations

2018-07-09 Thread Rafael Stahl via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC336523: [ASTImporter] import FunctionDecl end locations 
(authored by r.stahl, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D48941?vs=154215&id=154549#toc

Repository:
  rC Clang

https://reviews.llvm.org/D48941

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


Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -2554,16 +2554,16 @@
D->isInlineSpecified(),
FromConversion->isExplicit(),
D->isConstexpr(),
-   Importer.Import(D->getLocEnd()));
+   SourceLocation());
   } else if (auto *Method = dyn_cast(D)) {
 ToFunction = CXXMethodDecl::Create(Importer.getToContext(), 
cast(DC),
InnerLocStart,
NameInfo, T, TInfo,
Method->getStorageClass(),
Method->isInlineSpecified(),
D->isConstexpr(),
-   Importer.Import(D->getLocEnd()));
+   SourceLocation());
   } else {
 ToFunction = FunctionDecl::Create(Importer.getToContext(), DC,
   InnerLocStart,
@@ -2580,6 +2580,7 @@
   ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
   ToFunction->setTrivial(D->isTrivial());
   ToFunction->setPure(D->isPure());
+  ToFunction->setRangeEnd(Importer.Import(D->getLocEnd()));
   Importer.Imported(D, ToFunction);
 
   // Set the parameters.
Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -1620,7 +1620,7 @@
   FromSM);
 }
 
-TEST_P(ASTImporterTestBase, DISABLED_ImportNestedMacro) {
+TEST_P(ASTImporterTestBase, ImportNestedMacro) {
   Decl *FromTU = getTuDecl(
   R"(
   #define FUNC_INT void declToImport


Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -2554,16 +2554,16 @@
D->isInlineSpecified(),
FromConversion->isExplicit(),
D->isConstexpr(),
-   Importer.Import(D->getLocEnd()));
+   SourceLocation());
   } else if (auto *Method = dyn_cast(D)) {
 ToFunction = CXXMethodDecl::Create(Importer.getToContext(), 
cast(DC),
InnerLocStart,
NameInfo, T, TInfo,
Method->getStorageClass(),
Method->isInlineSpecified(),
D->isConstexpr(),
-   Importer.Import(D->getLocEnd()));
+   SourceLocation());
   } else {
 ToFunction = FunctionDecl::Create(Importer.getToContext(), DC,
   InnerLocStart,
@@ -2580,6 +2580,7 @@
   ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
   ToFunction->setTrivial(D->isTrivial());
   ToFunction->setPure(D->isPure());
+  ToFunction->setRangeEnd(Importer.Import(D->getLocEnd()));
   Importer.Imported(D, ToFunction);
 
   // Set the parameters.
Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -1620,7 +1620,7 @@
   FromSM);
 }
 
-TEST_P(ASTImporterTestBase, DISABLED_ImportNestedMacro) {
+TEST_P(ASTImporterTestBase, ImportNestedMacro) {
   Decl *FromTU = getTuDecl(
   R"(
   #define FUNC_INT void declToImport
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D49066: [libclang] Add support for ObjCTypeParam

2018-07-09 Thread Michael Wu via Phabricator via cfe-commits
michaelwu created this revision.

This patch adds support to the libclang API for identifying ObjCTypeParams in 
CXTypes.

This patch depends on https://reviews.llvm.org/D49063 since both patches add 
new values to CXTypeKind.


Repository:
  rC Clang

https://reviews.llvm.org/D49066

Files:
  include/clang-c/Index.h
  test/Index/print-type.m
  tools/libclang/CXType.cpp


Index: tools/libclang/CXType.cpp
===
--- tools/libclang/CXType.cpp
+++ tools/libclang/CXType.cpp
@@ -100,6 +100,7 @@
 TKCASE(ObjCInterface);
 TKCASE(ObjCObject);
 TKCASE(ObjCObjectPointer);
+TKCASE(ObjCTypeParam);
 TKCASE(FunctionNoProto);
 TKCASE(FunctionProto);
 TKCASE(ConstantArray);
@@ -578,6 +579,7 @@
 TKIND(ObjCInterface);
 TKIND(ObjCObject);
 TKIND(ObjCObjectPointer);
+TKIND(ObjCTypeParam);
 TKIND(FunctionNoProto);
 TKIND(FunctionProto);
 TKIND(ConstantArray);
Index: test/Index/print-type.m
===
--- test/Index/print-type.m
+++ test/Index/print-type.m
@@ -7,6 +7,10 @@
 @property (class) int classProp;
 @end
 
+@interface Bar : Foo
+-(SomeType)generic;
+@end
+
 // RUN: c-index-test -test-print-type %s | FileCheck %s
 // CHECK: ObjCPropertyDecl=x:2:25 [readonly,] [type=id] [typekind=ObjCId] 
[canonicaltype=id] [canonicaltypekind=ObjCObjectPointer] [isPOD=1]
 // CHECK: ObjCInstanceMethodDecl=mymethod:3:8 [type=] [typekind=Invalid] 
[resulttype=int] [resulttypekind=Int] [isPOD=0]
@@ -17,3 +21,4 @@
 // CHECK: ParmDecl=j:5:49 (Definition) [Out,] [type=short *] 
[typekind=Pointer] [isPOD=1] [pointeetype=short] [pointeekind=Short]
 // CHECK: ParmDecl=p:6:36 (Definition) [type=__kindof Foo *] 
[typekind=ObjCObjectPointer] [canonicaltype=__kindof Foo *] 
[canonicaltypekind=ObjCObjectPointer] [basetype=Foo] [basekind=ObjCInterface] 
[isPOD=1] [pointeetype=Foo] [pointeekind=ObjCInterface]
 // CHECK: ObjCPropertyDecl=classProp:7:23 [class,] [type=int] [typekind=Int] 
[isPOD=1]
+// CHECK: ObjCInstanceMethodDecl=generic:11:12 [type=] [typekind=Invalid] 
[resulttype=SomeType] [resulttypekind=ObjCTypeParam] [isPOD=0]
Index: include/clang-c/Index.h
===
--- include/clang-c/Index.h
+++ include/clang-c/Index.h
@@ -3268,7 +3268,8 @@
   CXType_OCLQueue = 159,
   CXType_OCLReserveID = 160,
 
-  CXType_ObjCObject = 161
+  CXType_ObjCObject = 161,
+  CXType_ObjCTypeParam = 162
 };
 
 /**


Index: tools/libclang/CXType.cpp
===
--- tools/libclang/CXType.cpp
+++ tools/libclang/CXType.cpp
@@ -100,6 +100,7 @@
 TKCASE(ObjCInterface);
 TKCASE(ObjCObject);
 TKCASE(ObjCObjectPointer);
+TKCASE(ObjCTypeParam);
 TKCASE(FunctionNoProto);
 TKCASE(FunctionProto);
 TKCASE(ConstantArray);
@@ -578,6 +579,7 @@
 TKIND(ObjCInterface);
 TKIND(ObjCObject);
 TKIND(ObjCObjectPointer);
+TKIND(ObjCTypeParam);
 TKIND(FunctionNoProto);
 TKIND(FunctionProto);
 TKIND(ConstantArray);
Index: test/Index/print-type.m
===
--- test/Index/print-type.m
+++ test/Index/print-type.m
@@ -7,6 +7,10 @@
 @property (class) int classProp;
 @end
 
+@interface Bar : Foo
+-(SomeType)generic;
+@end
+
 // RUN: c-index-test -test-print-type %s | FileCheck %s
 // CHECK: ObjCPropertyDecl=x:2:25 [readonly,] [type=id] [typekind=ObjCId] [canonicaltype=id] [canonicaltypekind=ObjCObjectPointer] [isPOD=1]
 // CHECK: ObjCInstanceMethodDecl=mymethod:3:8 [type=] [typekind=Invalid] [resulttype=int] [resulttypekind=Int] [isPOD=0]
@@ -17,3 +21,4 @@
 // CHECK: ParmDecl=j:5:49 (Definition) [Out,] [type=short *] [typekind=Pointer] [isPOD=1] [pointeetype=short] [pointeekind=Short]
 // CHECK: ParmDecl=p:6:36 (Definition) [type=__kindof Foo *] [typekind=ObjCObjectPointer] [canonicaltype=__kindof Foo *] [canonicaltypekind=ObjCObjectPointer] [basetype=Foo] [basekind=ObjCInterface] [isPOD=1] [pointeetype=Foo] [pointeekind=ObjCInterface]
 // CHECK: ObjCPropertyDecl=classProp:7:23 [class,] [type=int] [typekind=Int] [isPOD=1]
+// CHECK: ObjCInstanceMethodDecl=generic:11:12 [type=] [typekind=Invalid] [resulttype=SomeType] [resulttypekind=ObjCTypeParam] [isPOD=0]
Index: include/clang-c/Index.h
===
--- include/clang-c/Index.h
+++ include/clang-c/Index.h
@@ -3268,7 +3268,8 @@
   CXType_OCLQueue = 159,
   CXType_OCLReserveID = 160,
 
-  CXType_ObjCObject = 161
+  CXType_ObjCObject = 161,
+  CXType_ObjCTypeParam = 162
 };
 
 /**
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D48961: [Index] Add indexing support for MACROs.

2018-07-09 Thread Eric Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC336524: [Index] Add indexing support for MACROs. (authored 
by ioeric, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D48961?vs=154543&id=154550#toc

Repository:
  rC Clang

https://reviews.llvm.org/D48961

Files:
  include/clang/Index/IndexSymbol.h
  include/clang/Index/IndexingAction.h
  lib/Index/IndexSymbol.cpp
  lib/Index/IndexingAction.cpp
  lib/Index/IndexingContext.cpp
  lib/Index/IndexingContext.h
  test/Index/Core/index-macros.c
  tools/c-index-test/core_main.cpp

Index: test/Index/Core/index-macros.c
===
--- test/Index/Core/index-macros.c
+++ test/Index/Core/index-macros.c
@@ -0,0 +1,12 @@
+// RUN: c-index-test core -print-source-symbols -- %s | FileCheck %s
+
+// CHECK: [[@LINE+1]]:9 | macro/C | X1 | c:index-macros.c@157@macro@X1 | Def |
+#define X1 1
+// CHECK: [[@LINE+1]]:9 | macro/C | DEF | c:index-macros.c@251@macro@DEF | Def |
+#define DEF(x) int x
+// CHECK: [[@LINE+1]]:8 | macro/C | X1 | c:index-macros.c@157@macro@X1 | Undef |
+#undef X1
+
+// CHECK: [[@LINE+2]]:1 | macro/C | DEF | c:index-macros.c@251@macro@DEF | Ref |
+// CHECK: [[@LINE+1]]:5 | variable/C | i | c:@i | i | Def | rel: 0
+DEF(i);
Index: lib/Index/IndexingAction.cpp
===
--- lib/Index/IndexingAction.cpp
+++ lib/Index/IndexingAction.cpp
@@ -13,8 +13,11 @@
 #include "clang/Frontend/FrontendAction.h"
 #include "clang/Frontend/MultiplexConsumer.h"
 #include "clang/Index/IndexDataConsumer.h"
+#include "clang/Lex/PPCallbacks.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Serialization/ASTReader.h"
+#include "llvm/ADT/STLExtras.h"
+#include 
 
 using namespace clang;
 using namespace clang::index;
@@ -43,51 +46,84 @@
 
 class IndexASTConsumer : public ASTConsumer {
   std::shared_ptr PP;
-  IndexingContext &IndexCtx;
+  std::shared_ptr IndexCtx;
 
 public:
-  IndexASTConsumer(std::shared_ptr PP, IndexingContext &IndexCtx)
-  : PP(std::move(PP)), IndexCtx(IndexCtx) {}
+  IndexASTConsumer(std::shared_ptr PP,
+   std::shared_ptr IndexCtx)
+  : PP(std::move(PP)), IndexCtx(std::move(IndexCtx)) {}
 
 protected:
   void Initialize(ASTContext &Context) override {
-IndexCtx.setASTContext(Context);
-IndexCtx.getDataConsumer().initialize(Context);
-IndexCtx.getDataConsumer().setPreprocessor(PP);
+IndexCtx->setASTContext(Context);
+IndexCtx->getDataConsumer().initialize(Context);
+IndexCtx->getDataConsumer().setPreprocessor(PP);
   }
 
   bool HandleTopLevelDecl(DeclGroupRef DG) override {
-return IndexCtx.indexDeclGroupRef(DG);
+return IndexCtx->indexDeclGroupRef(DG);
   }
 
   void HandleInterestingDecl(DeclGroupRef DG) override {
 // Ignore deserialized decls.
   }
 
   void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) override {
-IndexCtx.indexDeclGroupRef(DG);
+IndexCtx->indexDeclGroupRef(DG);
   }
 
   void HandleTranslationUnit(ASTContext &Ctx) override {
   }
 };
 
+class IndexPPCallbacks : public PPCallbacks {
+  std::shared_ptr IndexCtx;
+
+public:
+  IndexPPCallbacks(std::shared_ptr IndexCtx)
+  : IndexCtx(std::move(IndexCtx)) {}
+
+  void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD,
+SourceRange Range, const MacroArgs *Args) override {
+IndexCtx->handleMacroReference(*MacroNameTok.getIdentifierInfo(),
+   Range.getBegin(), *MD.getMacroInfo());
+  }
+
+  void MacroDefined(const Token &MacroNameTok,
+const MacroDirective *MD) override {
+IndexCtx->handleMacroDefined(*MacroNameTok.getIdentifierInfo(),
+ MacroNameTok.getLocation(),
+ *MD->getMacroInfo());
+  }
+
+  void MacroUndefined(const Token &MacroNameTok, const MacroDefinition &MD,
+  const MacroDirective *Undef) override {
+IndexCtx->handleMacroUndefined(*MacroNameTok.getIdentifierInfo(),
+   MacroNameTok.getLocation(),
+   *MD.getMacroInfo());
+  }
+};
+
 class IndexActionBase {
 protected:
   std::shared_ptr DataConsumer;
-  IndexingContext IndexCtx;
+  std::shared_ptr IndexCtx;
 
   IndexActionBase(std::shared_ptr dataConsumer,
   IndexingOptions Opts)
-: DataConsumer(std::move(dataConsumer)),
-  IndexCtx(Opts, *DataConsumer) {}
+  : DataConsumer(std::move(dataConsumer)),
+IndexCtx(new IndexingContext(Opts, *DataConsumer)) {}
 
   std::unique_ptr
   createIndexASTConsumer(CompilerInstance &CI) {
 return llvm::make_unique(CI.getPreprocessorPtr(),
IndexCtx);
   }
 
+  std::unique_ptr createIndexPPCallbacks() {
+return llvm::make_unique(IndexCtx);
+  }
+
   void finish() {
 DataConsumer->finish();
   }
@@ -105

r336524 - [Index] Add indexing support for MACROs.

2018-07-09 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Mon Jul  9 01:44:05 2018
New Revision: 336524

URL: http://llvm.org/viewvc/llvm-project?rev=336524&view=rev
Log:
[Index] Add indexing support for MACROs.

Reviewers: akyrtzi, arphaman, sammccall

Reviewed By: sammccall

Subscribers: malaperle, sammccall, cfe-commits

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

Added:
cfe/trunk/test/Index/Core/index-macros.c
Modified:
cfe/trunk/include/clang/Index/IndexSymbol.h
cfe/trunk/include/clang/Index/IndexingAction.h
cfe/trunk/lib/Index/IndexSymbol.cpp
cfe/trunk/lib/Index/IndexingAction.cpp
cfe/trunk/lib/Index/IndexingContext.cpp
cfe/trunk/lib/Index/IndexingContext.h
cfe/trunk/tools/c-index-test/core_main.cpp

Modified: cfe/trunk/include/clang/Index/IndexSymbol.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Index/IndexSymbol.h?rev=336524&r1=336523&r2=336524&view=diff
==
--- cfe/trunk/include/clang/Index/IndexSymbol.h (original)
+++ cfe/trunk/include/clang/Index/IndexSymbol.h Mon Jul  9 01:44:05 2018
@@ -11,6 +11,7 @@
 #define LLVM_CLANG_INDEX_INDEXSYMBOL_H
 
 #include "clang/Basic/LLVM.h"
+#include "clang/Lex/MacroInfo.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/DataTypes.h"
 
@@ -93,28 +94,31 @@ static const unsigned SymbolPropertyBitN
 /// Low 9 bits of clang-c/include/Index.h CXSymbolRole mirrors this enum.
 enum class SymbolRole : uint32_t {
   Declaration = 1 << 0,
-  Definition  = 1 << 1,
-  Reference   = 1 << 2,
-  Read= 1 << 3,
-  Write   = 1 << 4,
-  Call= 1 << 5,
-  Dynamic = 1 << 6,
-  AddressOf   = 1 << 7,
-  Implicit= 1 << 8,
+  Definition = 1 << 1,
+  Reference = 1 << 2,
+  Read = 1 << 3,
+  Write = 1 << 4,
+  Call = 1 << 5,
+  Dynamic = 1 << 6,
+  AddressOf = 1 << 7,
+  Implicit = 1 << 8,
+  // FIXME: this is not mirrored in CXSymbolRole.
+  // Note that macro occurrences aren't currently supported in libclang.
+  Undefinition = 1 << 9, // macro #undef
 
   // Relation roles.
-  RelationChildOf = 1 << 9,
-  RelationBaseOf  = 1 << 10,
-  RelationOverrideOf  = 1 << 11,
-  RelationReceivedBy  = 1 << 12,
-  RelationCalledBy= 1 << 13,
-  RelationExtendedBy  = 1 << 14,
-  RelationAccessorOf  = 1 << 15,
-  RelationContainedBy = 1 << 16,
-  RelationIBTypeOf= 1 << 17,
-  RelationSpecializationOf = 1 << 18,
+  RelationChildOf = 1 << 10,
+  RelationBaseOf = 1 << 11,
+  RelationOverrideOf = 1 << 12,
+  RelationReceivedBy = 1 << 13,
+  RelationCalledBy = 1 << 14,
+  RelationExtendedBy = 1 << 15,
+  RelationAccessorOf = 1 << 16,
+  RelationContainedBy = 1 << 17,
+  RelationIBTypeOf = 1 << 18,
+  RelationSpecializationOf = 1 << 19,
 };
-static const unsigned SymbolRoleBitNum = 19;
+static const unsigned SymbolRoleBitNum = 20;
 typedef unsigned SymbolRoleSet;
 
 /// Represents a relation to another symbol for a symbol occurrence.
@@ -135,6 +139,8 @@ struct SymbolInfo {
 
 SymbolInfo getSymbolInfo(const Decl *D);
 
+SymbolInfo getSymbolInfoForMacro(const MacroInfo &MI);
+
 bool isFunctionLocalSymbol(const Decl *D);
 
 void applyForEachSymbolRole(SymbolRoleSet Roles,

Modified: cfe/trunk/include/clang/Index/IndexingAction.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Index/IndexingAction.h?rev=336524&r1=336523&r2=336524&view=diff
==
--- cfe/trunk/include/clang/Index/IndexingAction.h (original)
+++ cfe/trunk/include/clang/Index/IndexingAction.h Mon Jul  9 01:44:05 2018
@@ -11,6 +11,7 @@
 #define LLVM_CLANG_INDEX_INDEXINGACTION_H
 
 #include "clang/Basic/LLVM.h"
+#include "clang/Lex/PPCallbacks.h"
 #include "llvm/ADT/ArrayRef.h"
 #include 
 
@@ -40,18 +41,30 @@ struct IndexingOptions {
   bool IndexFunctionLocals = false;
 };
 
+/// Creates a frontend action that indexes all symbols (macros and AST decls).
 /// \param WrappedAction another frontend action to wrap over or null.
 std::unique_ptr
 createIndexingAction(std::shared_ptr DataConsumer,
  IndexingOptions Opts,
  std::unique_ptr WrappedAction);
 
+/// Recursively indexes all decls in the AST.
+/// Note that this does not index macros.
 void indexASTUnit(ASTUnit &Unit, IndexDataConsumer &DataConsumer,
   IndexingOptions Opts);
 
+/// Recursively indexes \p Decls.
+/// Note that this does not index macros.
 void indexTopLevelDecls(ASTContext &Ctx, ArrayRef Decls,
 IndexDataConsumer &DataConsumer, IndexingOptions Opts);
 
+/// Creates a PPCallbacks that indexes macros and feeds macros to \p Consumer.
+/// The caller is responsible for calling `Consumer.setPreprocessor()`.
+std::unique_ptr indexMacrosCallback(IndexDataConsumer &Consumer,
+ IndexingOptions Opts);
+
+/// Recursively indexes all top-level decls in the module.
+/// FIXME: make this index macros as well.
 void indexMo

[PATCH] D48946: [Preamble] Check system dependencies in preamble too

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

In https://reviews.llvm.org/D48946#1152764, @sammccall wrote:

> This seems like it might be a nontrivial performance hit (it's going to 
> result in `stat`ing all these files, right?).
>  Agreed it's important for correctness, it's possible someone wants the 
> performance/correctness tradeoff though.


I do agree that it's (probably) useless to stat the STL in /usr/lib for most of 
the users, maybe in some other cases too. Happy to add an option if that turns 
out to be a problem.


Repository:
  rC Clang

https://reviews.llvm.org/D48946



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


[PATCH] D48946: [Preamble] Check system dependencies in preamble too

2018-07-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 154551.
ilya-biryukov marked an inline comment as done.
ilya-biryukov added a comment.
Herald added a subscriber: omtcyfz.

- Fix a comment


Repository:
  rC Clang

https://reviews.llvm.org/D48946

Files:
  lib/Frontend/PrecompiledPreamble.cpp


Index: lib/Frontend/PrecompiledPreamble.cpp
===
--- lib/Frontend/PrecompiledPreamble.cpp
+++ lib/Frontend/PrecompiledPreamble.cpp
@@ -63,6 +63,16 @@
   return Overlay;
 }
 
+class PreambleDependencyCollector : public DependencyCollector {
+public:
+  // We want to collect all dependencies for correctness. Avoiding the real
+  // system dependencies (e.g. stl from /usr/lib) would probably be a good 
idea,
+  // but there is no way to distinguish between those and the ones that can be
+  // spuriously added by '-isystem' (e.g. to suppress warnings from those
+  // headers).
+  bool needSystemDependencies() override { return true; }
+};
+
 /// Keeps a track of files to be deleted in destructor.
 class TemporaryFiles {
 public:
@@ -311,7 +321,7 @@
   Clang->setSourceManager(
   new SourceManager(Diagnostics, Clang->getFileManager()));
 
-  auto PreambleDepCollector = std::make_shared();
+  auto PreambleDepCollector = std::make_shared();
   Clang->addDependencyCollector(PreambleDepCollector);
 
   // Remap the main source file to the preamble buffer.


Index: lib/Frontend/PrecompiledPreamble.cpp
===
--- lib/Frontend/PrecompiledPreamble.cpp
+++ lib/Frontend/PrecompiledPreamble.cpp
@@ -63,6 +63,16 @@
   return Overlay;
 }
 
+class PreambleDependencyCollector : public DependencyCollector {
+public:
+  // We want to collect all dependencies for correctness. Avoiding the real
+  // system dependencies (e.g. stl from /usr/lib) would probably be a good idea,
+  // but there is no way to distinguish between those and the ones that can be
+  // spuriously added by '-isystem' (e.g. to suppress warnings from those
+  // headers).
+  bool needSystemDependencies() override { return true; }
+};
+
 /// Keeps a track of files to be deleted in destructor.
 class TemporaryFiles {
 public:
@@ -311,7 +321,7 @@
   Clang->setSourceManager(
   new SourceManager(Diagnostics, Clang->getFileManager()));
 
-  auto PreambleDepCollector = std::make_shared();
+  auto PreambleDepCollector = std::make_shared();
   Clang->addDependencyCollector(PreambleDepCollector);
 
   // Remap the main source file to the preamble buffer.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D45383: Limit types of builtins that can be redeclared.

2018-07-09 Thread Alexander Richardson via Phabricator via cfe-commits
arichardson added a comment.

This broke the build of FreeBSD for me due to the declaration of 
__builtin_return_address(unsigned int) in 
https://github.com/tianocore/edk2/blob/master/MdePkg/Include/Base.h#L1281:

  In file included from 
/exports/users/alr48/sources/freebsd-x86/sys/contrib/edk2/Include/Uefi.h:23:
  In file included from 
/exports/users/alr48/sources/freebsd-x86/sys/contrib/edk2/Include/Uefi/UefiBaseType.h:20:
  
/exports/users/alr48/sources/freebsd-x86/sys/contrib/edk2/Include/Base.h:1231:10:
 error: cannot redeclare builtin function '__builtin_return_address'
void * __builtin_return_address (unsigned int level);
   ^
  
/exports/users/alr48/sources/freebsd-x86/sys/contrib/edk2/Include/Base.h:1231:10:
 note: '__builtin_return_address' is a builtin with type 'void *(unsigned int)'


Repository:
  rL LLVM

https://reviews.llvm.org/D45383



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


[PATCH] D48947: [clangd] Added a test for preambles and -isystem

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

- Remove Name matcher, use Field(&...::Name) instead


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D48947

Files:
  unittests/clangd/ClangdTests.cpp


Index: unittests/clangd/ClangdTests.cpp
===
--- unittests/clangd/ClangdTests.cpp
+++ unittests/clangd/ClangdTests.cpp
@@ -33,15 +33,16 @@
 namespace clang {
 namespace clangd {
 
+using ::testing::Contains;
 using ::testing::ElementsAre;
 using ::testing::Eq;
+using ::testing::Field;
 using ::testing::Gt;
 using ::testing::IsEmpty;
 using ::testing::Pair;
 using ::testing::UnorderedElementsAre;
 
 namespace {
-
 bool diagsContainErrors(const std::vector &Diagnostics) {
   for (auto D : Diagnostics) {
 if (D.Severity == DiagnosticsEngine::Error ||
@@ -927,6 +928,41 @@
   EXPECT_EQ(Expected, *Changed);
 }
 
+TEST_F(ClangdVFSTest, ChangedHeaderFromISystem) {
+  MockFSProvider FS;
+  ErrorCheckingDiagConsumer DiagConsumer;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
+
+  auto SourcePath = testPath("source/foo.cpp");
+  auto HeaderPath = testPath("headers/foo.h");
+  FS.Files[HeaderPath] = "struct X { int bar; };";
+  Annotations Code(R"cpp(
+#include "foo.h"
+
+int main() {
+  X().ba^
+})cpp");
+  CDB.ExtraClangFlags.push_back("-xc++");
+  CDB.ExtraClangFlags.push_back("-isystem" + testPath("headers"));
+
+  runAddDocument(Server, SourcePath, Code.code());
+  auto Completions = cantFail(runCodeComplete(Server, SourcePath, Code.point(),
+clangd::CodeCompleteOptions()))
+   .Completions;
+  EXPECT_THAT(Completions, ElementsAre(Field(&CodeCompletion::Name, "bar")));
+  // Update the header and rerun addDocument to make sure we get the updated
+  // files.
+  FS.Files[HeaderPath] = "struct X { int bar; int baz; };";
+  runAddDocument(Server, SourcePath, Code.code());
+  Completions = cantFail(runCodeComplete(Server, SourcePath, Code.point(),
+clangd::CodeCompleteOptions()))
+   .Completions;
+  // We want to make sure we see the updated version.
+  EXPECT_THAT(Completions, ElementsAre(Field(&CodeCompletion::Name, "bar"),
+   Field(&CodeCompletion::Name, "baz")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang


Index: unittests/clangd/ClangdTests.cpp
===
--- unittests/clangd/ClangdTests.cpp
+++ unittests/clangd/ClangdTests.cpp
@@ -33,15 +33,16 @@
 namespace clang {
 namespace clangd {
 
+using ::testing::Contains;
 using ::testing::ElementsAre;
 using ::testing::Eq;
+using ::testing::Field;
 using ::testing::Gt;
 using ::testing::IsEmpty;
 using ::testing::Pair;
 using ::testing::UnorderedElementsAre;
 
 namespace {
-
 bool diagsContainErrors(const std::vector &Diagnostics) {
   for (auto D : Diagnostics) {
 if (D.Severity == DiagnosticsEngine::Error ||
@@ -927,6 +928,41 @@
   EXPECT_EQ(Expected, *Changed);
 }
 
+TEST_F(ClangdVFSTest, ChangedHeaderFromISystem) {
+  MockFSProvider FS;
+  ErrorCheckingDiagConsumer DiagConsumer;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
+
+  auto SourcePath = testPath("source/foo.cpp");
+  auto HeaderPath = testPath("headers/foo.h");
+  FS.Files[HeaderPath] = "struct X { int bar; };";
+  Annotations Code(R"cpp(
+#include "foo.h"
+
+int main() {
+  X().ba^
+})cpp");
+  CDB.ExtraClangFlags.push_back("-xc++");
+  CDB.ExtraClangFlags.push_back("-isystem" + testPath("headers"));
+
+  runAddDocument(Server, SourcePath, Code.code());
+  auto Completions = cantFail(runCodeComplete(Server, SourcePath, Code.point(),
+clangd::CodeCompleteOptions()))
+   .Completions;
+  EXPECT_THAT(Completions, ElementsAre(Field(&CodeCompletion::Name, "bar")));
+  // Update the header and rerun addDocument to make sure we get the updated
+  // files.
+  FS.Files[HeaderPath] = "struct X { int bar; int baz; };";
+  runAddDocument(Server, SourcePath, Code.code());
+  Completions = cantFail(runCodeComplete(Server, SourcePath, Code.point(),
+clangd::CodeCompleteOptions()))
+   .Completions;
+  // We want to make sure we see the updated version.
+  EXPECT_THAT(Completions, ElementsAre(Field(&CodeCompletion::Name, "bar"),
+   Field(&CodeCompletion::Name, "baz")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r336526 - [Index] Add clangLex to LINK_LIBS

2018-07-09 Thread Heejin Ahn via cfe-commits
Author: aheejin
Date: Mon Jul  9 01:54:42 2018
New Revision: 336526

URL: http://llvm.org/viewvc/llvm-project?rev=336526&view=rev
Log:
[Index] Add clangLex to LINK_LIBS

Without this, builds with `-DSHARED_LIB=ON` fail.

Modified:
cfe/trunk/lib/Index/CMakeLists.txt

Modified: cfe/trunk/lib/Index/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Index/CMakeLists.txt?rev=336526&r1=336525&r2=336526&view=diff
==
--- cfe/trunk/lib/Index/CMakeLists.txt (original)
+++ cfe/trunk/lib/Index/CMakeLists.txt Mon Jul  9 01:54:42 2018
@@ -23,6 +23,7 @@ add_clang_library(clangIndex
   clangBasic
   clangFormat
   clangFrontend
+  clangLex
   clangRewrite
   clangSerialization
   clangToolingCore


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


r336527 - [ASTImporter] fix test failure corrected by fixed func end locs

2018-07-09 Thread Rafael Stahl via cfe-commits
Author: r.stahl
Date: Mon Jul  9 02:02:53 2018
New Revision: 336527

URL: http://llvm.org/viewvc/llvm-project?rev=336527&view=rev
Log:
[ASTImporter] fix test failure corrected by fixed func end locs

fix to rC336523 / D48941


Modified:
cfe/trunk/test/Import/attr/test.cpp

Modified: cfe/trunk/test/Import/attr/test.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Import/attr/test.cpp?rev=336527&r1=336526&r2=336527&view=diff
==
--- cfe/trunk/test/Import/attr/test.cpp (original)
+++ cfe/trunk/test/Import/attr/test.cpp Mon Jul  9 02:02:53 2018
@@ -1,6 +1,6 @@
 // RUN: clang-import-test -dump-ast -import %S/Inputs/S.cpp -expression %s | 
FileCheck %s
 // CHECK: FunctionDecl
-// CHECK-SAME: S.cpp:1:1, col:13
+// CHECK-SAME: S.cpp:1:1, col:38
 // CHECK-NEXT: ConstAttr
 // CHECK-SAME: col:32
 


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


r336528 - [Preamble] Check system dependencies in preamble too

2018-07-09 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Jul  9 02:07:01 2018
New Revision: 336528

URL: http://llvm.org/viewvc/llvm-project?rev=336528&view=rev
Log:
[Preamble] Check system dependencies in preamble too

Summary:
PrecompiledPreamble hasn't checked if the system dependencies changed
before. This resulted in invalid preamble not being rebuilt if headers
that changed were found in -isystem include paths.

This pattern is sometimes used to avoid showing warnings in third
party code, so we want to correctly handle those cases.

Tested in clangd, see the follow-up patch.

Reviewers: sammccall, ioeric

Reviewed By: sammccall

Subscribers: omtcyfz, cfe-commits

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

Modified:
cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp

Modified: cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp?rev=336528&r1=336527&r2=336528&view=diff
==
--- cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp (original)
+++ cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp Mon Jul  9 02:07:01 2018
@@ -63,6 +63,16 @@ createVFSOverlayForPreamblePCH(StringRef
   return Overlay;
 }
 
+class PreambleDependencyCollector : public DependencyCollector {
+public:
+  // We want to collect all dependencies for correctness. Avoiding the real
+  // system dependencies (e.g. stl from /usr/lib) would probably be a good 
idea,
+  // but there is no way to distinguish between those and the ones that can be
+  // spuriously added by '-isystem' (e.g. to suppress warnings from those
+  // headers).
+  bool needSystemDependencies() override { return true; }
+};
+
 /// Keeps a track of files to be deleted in destructor.
 class TemporaryFiles {
 public:
@@ -311,7 +321,7 @@ llvm::ErrorOr Preco
   Clang->setSourceManager(
   new SourceManager(Diagnostics, Clang->getFileManager()));
 
-  auto PreambleDepCollector = std::make_shared();
+  auto PreambleDepCollector = std::make_shared();
   Clang->addDependencyCollector(PreambleDepCollector);
 
   // Remap the main source file to the preamble buffer.


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


[PATCH] D48946: [Preamble] Check system dependencies in preamble too

2018-07-09 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL336528: [Preamble] Check system dependencies in preamble too 
(authored by ibiryukov, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D48946

Files:
  cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp


Index: cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp
===
--- cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp
+++ cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp
@@ -63,6 +63,16 @@
   return Overlay;
 }
 
+class PreambleDependencyCollector : public DependencyCollector {
+public:
+  // We want to collect all dependencies for correctness. Avoiding the real
+  // system dependencies (e.g. stl from /usr/lib) would probably be a good 
idea,
+  // but there is no way to distinguish between those and the ones that can be
+  // spuriously added by '-isystem' (e.g. to suppress warnings from those
+  // headers).
+  bool needSystemDependencies() override { return true; }
+};
+
 /// Keeps a track of files to be deleted in destructor.
 class TemporaryFiles {
 public:
@@ -311,7 +321,7 @@
   Clang->setSourceManager(
   new SourceManager(Diagnostics, Clang->getFileManager()));
 
-  auto PreambleDepCollector = std::make_shared();
+  auto PreambleDepCollector = std::make_shared();
   Clang->addDependencyCollector(PreambleDepCollector);
 
   // Remap the main source file to the preamble buffer.


Index: cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp
===
--- cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp
+++ cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp
@@ -63,6 +63,16 @@
   return Overlay;
 }
 
+class PreambleDependencyCollector : public DependencyCollector {
+public:
+  // We want to collect all dependencies for correctness. Avoiding the real
+  // system dependencies (e.g. stl from /usr/lib) would probably be a good idea,
+  // but there is no way to distinguish between those and the ones that can be
+  // spuriously added by '-isystem' (e.g. to suppress warnings from those
+  // headers).
+  bool needSystemDependencies() override { return true; }
+};
+
 /// Keeps a track of files to be deleted in destructor.
 class TemporaryFiles {
 public:
@@ -311,7 +321,7 @@
   Clang->setSourceManager(
   new SourceManager(Diagnostics, Clang->getFileManager()));
 
-  auto PreambleDepCollector = std::make_shared();
+  auto PreambleDepCollector = std::make_shared();
   Clang->addDependencyCollector(PreambleDepCollector);
 
   // Remap the main source file to the preamble buffer.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D27651: [clang-format] Even with AlignConsecutiveDeclarations, PointerAlignment: Right should keep *s and &s to the right

2018-07-09 Thread Cheng Li via Phabricator via cfe-commits
charlie added a comment.

Would you please merge this patch into master  &  include it in daily build as 
soon as possible? My project really need this fix. Thanks a lot.


https://reviews.llvm.org/D27651



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


[clang-tools-extra] r336530 - [clangd] Added a test for preambles and -isystem

2018-07-09 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Jul  9 02:10:22 2018
New Revision: 336530

URL: http://llvm.org/viewvc/llvm-project?rev=336530&view=rev
Log:
[clangd] Added a test for preambles and -isystem

Summary:
Checks that preambles are properly invalidated when headers from
-isystem paths change.

Reviewers: sammccall, ioeric

Reviewed By: sammccall

Subscribers: MaskRay, jkorous, cfe-commits

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

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

Modified: clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp?rev=336530&r1=336529&r2=336530&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp Mon Jul  9 
02:10:22 2018
@@ -35,6 +35,7 @@ namespace clangd {
 
 using ::testing::ElementsAre;
 using ::testing::Eq;
+using ::testing::Field;
 using ::testing::Gt;
 using ::testing::IsEmpty;
 using ::testing::Pair;
@@ -927,6 +928,41 @@ void f() {}
   EXPECT_EQ(Expected, *Changed);
 }
 
+TEST_F(ClangdVFSTest, ChangedHeaderFromISystem) {
+  MockFSProvider FS;
+  ErrorCheckingDiagConsumer DiagConsumer;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
+
+  auto SourcePath = testPath("source/foo.cpp");
+  auto HeaderPath = testPath("headers/foo.h");
+  FS.Files[HeaderPath] = "struct X { int bar; };";
+  Annotations Code(R"cpp(
+#include "foo.h"
+
+int main() {
+  X().ba^
+})cpp");
+  CDB.ExtraClangFlags.push_back("-xc++");
+  CDB.ExtraClangFlags.push_back("-isystem" + testPath("headers"));
+
+  runAddDocument(Server, SourcePath, Code.code());
+  auto Completions = cantFail(runCodeComplete(Server, SourcePath, Code.point(),
+  clangd::CodeCompleteOptions()))
+ .Completions;
+  EXPECT_THAT(Completions, ElementsAre(Field(&CodeCompletion::Name, "bar")));
+  // Update the header and rerun addDocument to make sure we get the updated
+  // files.
+  FS.Files[HeaderPath] = "struct X { int bar; int baz; };";
+  runAddDocument(Server, SourcePath, Code.code());
+  Completions = cantFail(runCodeComplete(Server, SourcePath, Code.point(),
+ clangd::CodeCompleteOptions()))
+.Completions;
+  // We want to make sure we see the updated version.
+  EXPECT_THAT(Completions, ElementsAre(Field(&CodeCompletion::Name, "bar"),
+   Field(&CodeCompletion::Name, "baz")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang


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


[PATCH] D48947: [clangd] Added a test for preambles and -isystem

2018-07-09 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL336530: [clangd] Added a test for preambles and -isystem 
(authored by ibiryukov, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D48947?vs=154552&id=154555#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D48947

Files:
  clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp


Index: clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp
@@ -35,6 +35,7 @@
 
 using ::testing::ElementsAre;
 using ::testing::Eq;
+using ::testing::Field;
 using ::testing::Gt;
 using ::testing::IsEmpty;
 using ::testing::Pair;
@@ -927,6 +928,41 @@
   EXPECT_EQ(Expected, *Changed);
 }
 
+TEST_F(ClangdVFSTest, ChangedHeaderFromISystem) {
+  MockFSProvider FS;
+  ErrorCheckingDiagConsumer DiagConsumer;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
+
+  auto SourcePath = testPath("source/foo.cpp");
+  auto HeaderPath = testPath("headers/foo.h");
+  FS.Files[HeaderPath] = "struct X { int bar; };";
+  Annotations Code(R"cpp(
+#include "foo.h"
+
+int main() {
+  X().ba^
+})cpp");
+  CDB.ExtraClangFlags.push_back("-xc++");
+  CDB.ExtraClangFlags.push_back("-isystem" + testPath("headers"));
+
+  runAddDocument(Server, SourcePath, Code.code());
+  auto Completions = cantFail(runCodeComplete(Server, SourcePath, Code.point(),
+  clangd::CodeCompleteOptions()))
+ .Completions;
+  EXPECT_THAT(Completions, ElementsAre(Field(&CodeCompletion::Name, "bar")));
+  // Update the header and rerun addDocument to make sure we get the updated
+  // files.
+  FS.Files[HeaderPath] = "struct X { int bar; int baz; };";
+  runAddDocument(Server, SourcePath, Code.code());
+  Completions = cantFail(runCodeComplete(Server, SourcePath, Code.point(),
+ clangd::CodeCompleteOptions()))
+.Completions;
+  // We want to make sure we see the updated version.
+  EXPECT_THAT(Completions, ElementsAre(Field(&CodeCompletion::Name, "bar"),
+   Field(&CodeCompletion::Name, "baz")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang


Index: clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp
@@ -35,6 +35,7 @@
 
 using ::testing::ElementsAre;
 using ::testing::Eq;
+using ::testing::Field;
 using ::testing::Gt;
 using ::testing::IsEmpty;
 using ::testing::Pair;
@@ -927,6 +928,41 @@
   EXPECT_EQ(Expected, *Changed);
 }
 
+TEST_F(ClangdVFSTest, ChangedHeaderFromISystem) {
+  MockFSProvider FS;
+  ErrorCheckingDiagConsumer DiagConsumer;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
+
+  auto SourcePath = testPath("source/foo.cpp");
+  auto HeaderPath = testPath("headers/foo.h");
+  FS.Files[HeaderPath] = "struct X { int bar; };";
+  Annotations Code(R"cpp(
+#include "foo.h"
+
+int main() {
+  X().ba^
+})cpp");
+  CDB.ExtraClangFlags.push_back("-xc++");
+  CDB.ExtraClangFlags.push_back("-isystem" + testPath("headers"));
+
+  runAddDocument(Server, SourcePath, Code.code());
+  auto Completions = cantFail(runCodeComplete(Server, SourcePath, Code.point(),
+  clangd::CodeCompleteOptions()))
+ .Completions;
+  EXPECT_THAT(Completions, ElementsAre(Field(&CodeCompletion::Name, "bar")));
+  // Update the header and rerun addDocument to make sure we get the updated
+  // files.
+  FS.Files[HeaderPath] = "struct X { int bar; int baz; };";
+  runAddDocument(Server, SourcePath, Code.code());
+  Completions = cantFail(runCodeComplete(Server, SourcePath, Code.point(),
+ clangd::CodeCompleteOptions()))
+.Completions;
+  // We want to make sure we see the updated version.
+  EXPECT_THAT(Completions, ElementsAre(Field(&CodeCompletion::Name, "bar"),
+   Field(&CodeCompletion::Name, "baz")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r336532 - Try to fix build bot after r336524

2018-07-09 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Mon Jul  9 02:17:25 2018
New Revision: 336532

URL: http://llvm.org/viewvc/llvm-project?rev=336532&view=rev
Log:
Try to fix build bot after r336524

Modified:
cfe/trunk/test/Index/Core/index-macros.c

Modified: cfe/trunk/test/Index/Core/index-macros.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/Core/index-macros.c?rev=336532&r1=336531&r2=336532&view=diff
==
--- cfe/trunk/test/Index/Core/index-macros.c (original)
+++ cfe/trunk/test/Index/Core/index-macros.c Mon Jul  9 02:17:25 2018
@@ -8,5 +8,5 @@
 #undef X1
 
 // CHECK: [[@LINE+2]]:1 | macro/C | DEF | c:index-macros.c@251@macro@DEF | Ref 
|
-// CHECK: [[@LINE+1]]:5 | variable/C | i | c:@i | i | Def | rel: 0
+// CHECK: [[@LINE+1]]:5 | variable/C | i | c:@i | {{.*}} | Def | rel: 0
 DEF(i);


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


[PATCH] D49057: [analyzer] Track multiple raw pointer symbols in DanglingInternalBufferChecker

2018-07-09 Thread Reka Kovacs via Phabricator via cfe-commits
rnkovacs added inline comments.



Comment at: lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp:32-40
+namespace clang {
+namespace ento {
+template<> struct ProgramStateTrait
+  : public ProgramStatePartialTrait {
+  static void *GDMIndex() {
+static int Index = 0;
+return &Index;

NoQ wrote:
> Please add a comment on how this template is useful. This trick is used by 
> some checkers, but it's a vry unobvious trick. We should probably add a 
> macro for that, i.e. `REGISTER_FACTORY_WITH_PROGRAMSTATE` or something like 
> that.
Should I do that then? Maybe in `CheckerContext.h`?



Comment at: lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp:115
 SVal RawPtr = Call.getReturnValue();
 if (!RawPtr.isUnknown()) {
+  // Start tracking this raw pointer by adding it to the set of symbols

NoQ wrote:
> I'd much rather unwrap the symbol here, i.e. `if (SymbolRef Sym = 
> RawPtr.getAsSymbol())`. A lot of other cornercases may occur if the 
> implementation is accidentally inlined (`Undefined`, concrete regions). Also, 
> speculatively, `.getAsSymbol(/* search for symbolic base = */ true)` for the 
> same reason//*//.
> 
> If we didn't care about inlined implementations, the `Unknown` check would 
> have been redundant. So it should also be safe to straightforwardly ignore 
> inlined implementations by consulting `C.wasInlined`, then the presence of 
> the symbol can be asserted. But i'd rather speculatively care about inlined 
> implementations as long as it seems easy.
> 
> __
> //*// In fact your code relies on a very wonky implementation detail of our 
> `SVal` hierarchy: namely, pointer-type return values of conservatively 
> evaluated functions are always expressed as `&SymRegion{conj_$N type>}` and never as `&element{SymRegion{conj_$N}, 0 S32b, 
> pointee type}`. Currently nobody knows the rules under which zero element 
> regions are added in different parts of the analyzer, i.e. what is the 
> "canonical" representation of the symbolic pointer, though i made a few 
> attempts to speculate.
I wasn't aware of much of this. Thanks for the detailed explanation :)


https://reviews.llvm.org/D49057



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


[PATCH] D49057: [analyzer] Track multiple raw pointer symbols in DanglingInternalBufferChecker

2018-07-09 Thread Reka Kovacs via Phabricator via cfe-commits
rnkovacs updated this revision to Diff 154556.
rnkovacs marked 5 inline comments as done.
rnkovacs added a comment.

Thanks very much for your review!


https://reviews.llvm.org/D49057

Files:
  lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp
  test/Analysis/dangling-internal-buffer.cpp

Index: test/Analysis/dangling-internal-buffer.cpp
===
--- test/Analysis/dangling-internal-buffer.cpp
+++ test/Analysis/dangling-internal-buffer.cpp
@@ -108,6 +108,30 @@
   // expected-note@-1 {{Use of memory after it is freed}}
 }
 
+void multiple_symbols(bool cond) {
+  const char *c1, *d1;
+  {
+std::string s1;
+c1 = s1.c_str(); // expected-note {{Pointer to dangling buffer was obtained here}}
+d1 = s1.data(); // expected-note {{Pointer to dangling buffer was obtained here}}
+const char *local = s1.c_str();
+consume(local); // no-warning
+  } // expected-note {{Internal buffer is released because the object was destroyed}}
+  // expected-note@-1 {{Internal buffer is released because the object was destroyed}}
+  std::string s2;
+  const char *c2 = s2.c_str();
+  if (cond) {
+// expected-note@-1 {{Assuming 'cond' is not equal to 0}}
+// expected-note@-2 {{Taking true branch}}
+// expected-note@-3 {{Assuming 'cond' is 0}}
+// expected-note@-4 {{Taking false branch}}
+consume(c1); // expected-warning {{Use of memory after it is freed}}
+// expected-note@-1 {{Use of memory after it is freed}}
+  } else {
+consume(d1); // expected-warning {{Use of memory after it is freed}}
+  } // expected-note@-1 {{Use of memory after it is freed}}
+}
+
 void deref_after_scope_cstr_ok() {
   const char *c;
   std::string s;
Index: lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp
+++ lib/StaticAnalyzer/Checkers/DanglingInternalBufferChecker.cpp
@@ -24,10 +24,23 @@
 using namespace clang;
 using namespace ento;
 
-// FIXME: member functions that return a pointer to the container's internal
-// buffer may be called on the object many times, so the object's memory
-// region should have a list of pointer symbols associated with it.
-REGISTER_MAP_WITH_PROGRAMSTATE(RawPtrMap, const MemRegion *, SymbolRef)
+using PtrSet = llvm::ImmutableSet;
+
+// Associate container objects with a set of raw pointer symbols.
+REGISTER_MAP_WITH_PROGRAMSTATE(RawPtrMap, const MemRegion *, PtrSet)
+
+// This is a trick to gain access to PtrSet's Factory.
+namespace clang {
+namespace ento {
+template<> struct ProgramStateTrait
+  : public ProgramStatePartialTrait {
+  static void *GDMIndex() {
+static int Index = 0;
+return &Index;
+  }
+};
+} // end namespace ento
+} // end namespace clang
 
 namespace {
 
@@ -61,7 +74,7 @@
 bool isSymbolTracked(ProgramStateRef State, SymbolRef Sym) {
   RawPtrMapTy Map = State->get();
   for (const auto Entry : Map) {
-if (Entry.second == Sym)
+if (Entry.second.contains(Sym))
   return true;
   }
   return false;
@@ -88,32 +101,42 @@
 return;
 
   SVal Obj = ICall->getCXXThisVal();
-  const auto *TypedR = dyn_cast_or_null(Obj.getAsRegion());
-  if (!TypedR)
+  const auto *ObjRegion = dyn_cast_or_null(Obj.getAsRegion());
+  if (!ObjRegion)
 return;
 
-  auto *TypeDecl = TypedR->getValueType()->getAsCXXRecordDecl();
+  auto *TypeDecl = ObjRegion->getValueType()->getAsCXXRecordDecl();
   if (TypeDecl->getName() != "basic_string")
 return;
 
   ProgramStateRef State = C.getState();
 
   if (Call.isCalled(CStrFn) || Call.isCalled(DataFn)) {
 SVal RawPtr = Call.getReturnValue();
-if (!RawPtr.isUnknown()) {
-  State = State->set(TypedR, RawPtr.getAsSymbol());
+if (SymbolRef Sym = RawPtr.getAsSymbol(/*IncludeBaseRegions=*/true)) {
+  // Start tracking this raw pointer by adding it to the set of symbols
+  // associated with this container object in the program state map.
+  PtrSet::Factory &F = State->getStateManager().get_context();
+  const PtrSet *SetPtr = State->get(ObjRegion);
+  PtrSet Set = SetPtr ? *SetPtr : F.getEmptySet();
+  assert(C.wasInlined || !Set.contains(Sym));
+  Set = F.add(Set, Sym);
+  State = State->set(ObjRegion, Set);
   C.addTransition(State);
 }
 return;
   }
 
   if (isa(ICall)) {
-if (State->contains(TypedR)) {
-  const SymbolRef *StrBufferPtr = State->get(TypedR);
-  // FIXME: What if Origin is null?
+if (const PtrSet *PS = State->get(ObjRegion)) {
+  // Mark all pointer symbols associated with the deleted object released.
   const Expr *Origin = Call.getOriginExpr();
-  State = allocation_state::markReleased(State, *StrBufferPtr, Origin);
-  State = State->remove(TypedR);
+  for (const auto Symbol : *PS) {
+// NOTE: `Origin` may be null, and will be stored so in the symbol's
+

[PATCH] D49028: [clangd] Support indexing MACROs.

2018-07-09 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 154559.
ioeric marked 5 inline comments as done.
ioeric added a comment.

- Addressed review comments.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49028

Files:
  clangd/index/SymbolCollector.cpp
  clangd/index/SymbolCollector.h
  unittests/clangd/SymbolCollectorTests.cpp

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -992,6 +992,32 @@
Field(&Symbol::Origin, SymbolOrigin::Static)));
 }
 
+TEST_F(SymbolCollectorTest, CollectMacros) {
+  CollectorOpts.CollectIncludePath = true;
+  Annotations Header(R"(
+#define X 1
+#define $mac[[MAC]](x) int x
+#define $used[[USED]](y) float y;
+
+MAC(p);
+  )");
+  const std::string Main = R"(
+#define MAIN 1  // not indexed
+USED(t);
+  )";
+  CollectorOpts.CountReferences = true;
+  CollectorOpts.CollectMacro = true;
+  runSymbolCollector(Header.code(), Main);
+  EXPECT_THAT(
+  Symbols,
+  UnorderedElementsAre(
+  QName("p"),
+  AllOf(QName("X"), DeclURI(TestHeaderURI),
+IncludeHeader(TestHeaderURI)),
+  AllOf(Labeled("MAC(x)"), Refs(0), DeclRange(Header.range("mac"))),
+  AllOf(Labeled("USED(y)"), Refs(1), DeclRange(Header.range("used");
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/index/SymbolCollector.h
===
--- clangd/index/SymbolCollector.h
+++ clangd/index/SymbolCollector.h
@@ -54,6 +54,11 @@
 bool CountReferences = false;
 // Every symbol collected will be stamped with this origin.
 SymbolOrigin Origin = SymbolOrigin::Unknown;
+/// Collect macros.
+/// Note that SymbolCollector must be run with preprocessor in order to
+/// collect macros. For example, `indexTopLevelDecls` will not index any
+/// macro even if this is true.
+bool CollectMacro = false;
   };
 
   SymbolCollector(Options Opts);
@@ -75,6 +80,10 @@
   SourceLocation Loc,
   index::IndexDataConsumer::ASTNodeInfo ASTNode) override;
 
+  bool handleMacroOccurence(const IdentifierInfo *Name, const MacroInfo *MI,
+index::SymbolRoleSet Roles,
+SourceLocation Loc) override;
+
   SymbolSlab takeSymbols() { return std::move(Symbols).build(); }
 
   void finish() override;
@@ -90,8 +99,9 @@
   std::shared_ptr CompletionAllocator;
   std::unique_ptr CompletionTUInfo;
   Options Opts;
-  // Decls referenced from the current TU, flushed on finish().
+  // Symbols referenced from the current TU, flushed on finish().
   llvm::DenseSet ReferencedDecls;
+  llvm::DenseSet ReferencedMacros;
   // Maps canonical declaration provided by clang to canonical declaration for
   // an index symbol, if clangd prefers a different declaration than that
   // provided by clang. For example, friend declaration might be considered
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -183,22 +183,19 @@
   return toURI(SM, Header, Opts);
 }
 
-// Return the symbol location of the given declaration `D`.
-//
-// For symbols defined inside macros:
-//   * use expansion location, if the symbol is formed via macro concatenation.
-//   * use spelling location, otherwise.
-llvm::Optional getSymbolLocation(
-const NamedDecl &D, SourceManager &SM, const SymbolCollector::Options &Opts,
-const clang::LangOptions &LangOpts, std::string &FileURIStorage) {
-  SourceLocation NameLoc = findNameLoc(&D);
-  auto U = toURI(SM, SM.getFilename(NameLoc), Opts);
+// Return the symbol location of the token at \p Loc.
+llvm::Optional
+getTokenLocation(SourceLocation TokLoc, const SourceManager &SM,
+ const SymbolCollector::Options &Opts,
+ const clang::LangOptions &LangOpts,
+ std::string &FileURIStorage) {
+  auto U = toURI(SM, SM.getFilename(TokLoc), Opts);
   if (!U)
 return llvm::None;
   FileURIStorage = std::move(*U);
   SymbolLocation Result;
   Result.FileURI = FileURIStorage;
-  auto TokenLength = clang::Lexer::MeasureTokenLength(NameLoc, SM, LangOpts);
+  auto TokenLength = clang::Lexer::MeasureTokenLength(TokLoc, SM, LangOpts);
 
   auto CreatePosition = [&SM](SourceLocation Loc) {
 auto LSPLoc = sourceLocToPosition(SM, Loc);
@@ -208,8 +205,8 @@
 return Pos;
   };
 
-  Result.Start = CreatePosition(NameLoc);
-  auto EndLoc = NameLoc.getLocWithOffset(TokenLength);
+  Result.Start = CreatePosition(TokLoc);
+  auto EndLoc = TokLoc.getLocWithOffset(TokenLength);
   Result.End = CreatePosition(EndLoc);
 
   return std::move(Result);
@@ -345,18 +342,106 @@
   return true;
 }
 
+bool SymbolCollector::hand

[PATCH] D49028: [clangd] Support indexing MACROs.

2018-07-09 Thread Eric Liu via Phabricator via cfe-commits
ioeric added inline comments.



Comment at: clangd/index/SymbolCollector.cpp:360
+
+  llvm::SmallString<128> USR;
+  if (index::generateUSRForMacro(Name.getName(), MI.getDefinitionLoc(), SM,

sammccall wrote:
> as above, can we avoid generating the USR for every reference?
> The macro name or hash thereof should be enough to identify it, right?
I thought I needed to store both the name and the location in order to 
calculate USR for macros, and just calculating USRs seems easier and not too 
expensive. But after another look, it turned out that `IdentifierInfo` + 
`Preprocessor` would also work. Thanks for pressing on this! :) 


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49028



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


[PATCH] D47154: Try to make builtin address space declarations not useless

2018-07-09 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm updated this revision to Diff 154561.
arsenm added a comment.

Add sema test for numbered address spaces


https://reviews.llvm.org/D47154

Files:
  include/clang/AST/ASTContext.h
  include/clang/Basic/BuiltinsAMDGPU.def
  include/clang/Basic/TargetInfo.h
  lib/AST/ASTContext.cpp
  lib/Basic/Targets/AMDGPU.h
  lib/CodeGen/CGBuiltin.cpp
  lib/Sema/SemaExpr.cpp
  test/CodeGenCUDA/builtins-amdgcn.cu
  test/CodeGenOpenCL/builtins-amdgcn.cl
  test/CodeGenOpenCL/numbered-address-space.cl
  test/SemaOpenCL/numbered-address-space.cl

Index: test/SemaOpenCL/numbered-address-space.cl
===
--- /dev/null
+++ test/SemaOpenCL/numbered-address-space.cl
@@ -0,0 +1,31 @@
+// REQUIRES: amdgpu-registered-target
+// RUN: %clang_cc1 -cl-std=CL2.0 -triple amdgcn-amd-amdhsa -verify -pedantic -fsyntax-only %s
+
+void test_numeric_as_to_generic_implicit_cast(__attribute__((address_space(3))) int *as3_ptr, float src) {
+  generic int* generic_ptr = as3_ptr; // FIXME: This should error
+}
+
+void test_numeric_as_to_generic_explicit_cast(__attribute__((address_space(3))) int *as3_ptr, float src) {
+  generic int* generic_ptr = (generic int*) as3_ptr; // Should maybe be valid?
+}
+
+void test_generic_to_numeric_as_implicit_cast() {
+  generic int* generic_ptr = 0;
+  __attribute__((address_space(3))) int *as3_ptr = generic_ptr; // expected-error{{initializing '__attribute__((address_space(3))) int *' with an expression of type '__generic int *' changes address space of pointer}}
+}
+
+void test_generic_to_numeric_as_explicit_cast() {
+  generic int* generic_ptr = 0;
+  __attribute__((address_space(3))) int *as3_ptr = (__attribute__((address_space(3))) int *)generic_ptr;
+}
+
+void test_generic_as_to_builtin_parameter_explicit_cast_numeric(__attribute__((address_space(3))) int *as3_ptr, float src) {
+  generic int* generic_ptr = as3_ptr; // FIXME: This should error
+  volatile float result = __builtin_amdgcn_ds_fmaxf((__attribute__((address_space(3))) float*) generic_ptr, src, 0, 0, false); // expected-error {{passing '__attribute__((address_space(3))) float *' to parameter of type '__local float *' changes address space of pointer}}
+}
+
+void test_generic_as_to_builtin_parameterimplicit_cast_numeric(__attribute__((address_space(3))) int *as3_ptr, float src) {
+  generic int* generic_ptr = as3_ptr;
+  volatile float result = __builtin_amdgcn_ds_fmaxf(generic_ptr, src, 0, 0, false); // expected-warning {{incompatible pointer types passing '__generic int *' to parameter of type '__local float *'}}
+}
+
Index: test/CodeGenOpenCL/numbered-address-space.cl
===
--- /dev/null
+++ test/CodeGenOpenCL/numbered-address-space.cl
@@ -0,0 +1,34 @@
+// REQUIRES: amdgpu-registered-target
+// RUN: %clang_cc1 -cl-std=CL2.0 -triple amdgcn-unknown-unknown -target-cpu tonga -S -emit-llvm -O0 -o - %s | FileCheck %s
+
+// Make sure using numbered address spaces doesn't trigger crashes when a
+// builtin has an address space parameter.
+
+// CHECK-LABEL: @test_numbered_as_to_generic(
+// CHECK: addrspacecast i32 addrspace(42)* %0 to i32*
+void test_numbered_as_to_generic(__attribute__((address_space(42))) int *arbitary_numbered_ptr) {
+  generic int* generic_ptr = arbitary_numbered_ptr;
+  *generic_ptr = 4;
+}
+
+// CHECK-LABEL: @test_numbered_as_to_builtin(
+// CHECK: addrspacecast i32 addrspace(42)* %0 to float addrspace(3)*
+void test_numbered_as_to_builtin(__attribute__((address_space(42))) int *arbitary_numbered_ptr, float src) {
+  volatile float result = __builtin_amdgcn_ds_fmaxf(arbitary_numbered_ptr, src, 0, 0, false);
+}
+
+// CHECK-LABEL: @test_generic_as_to_builtin_parameter_explicit_cast(
+// CHECK: addrspacecast i32 addrspace(3)* %0 to i32*
+void test_generic_as_to_builtin_parameter_explicit_cast(__local int *local_ptr, float src) {
+  generic int* generic_ptr = local_ptr;
+  volatile float result = __builtin_amdgcn_ds_fmaxf((__local float*) generic_ptr, src, 0, 0, false);
+}
+
+// CHECK-LABEL: @test_generic_as_to_builtin_parameter_implicit_cast(
+// CHECK: addrspacecast i32* %2 to float addrspace(3)*
+void test_generic_as_to_builtin_parameter_implicit_cast(__local int *local_ptr, float src) {
+  generic int* generic_ptr = local_ptr;
+
+  volatile float result = __builtin_amdgcn_ds_fmaxf(generic_ptr, src, 0, 0, false);
+}
+
Index: test/CodeGenOpenCL/builtins-amdgcn.cl
===
--- test/CodeGenOpenCL/builtins-amdgcn.cl
+++ test/CodeGenOpenCL/builtins-amdgcn.cl
@@ -1,6 +1,6 @@
 // REQUIRES: amdgpu-registered-target
-// RUN: %clang_cc1 -triple amdgcn-unknown-unknown -S -emit-llvm -o - %s | FileCheck %s
-// RUN: %clang_cc1 -triple amdgcn-unknown-unknown-opencl -S -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -cl-std=CL2.0 -triple amdgcn-unknown-unknown -S -emit-llvm -o - %s | FileCheck -enable-var-scope %s
+// RUN: %clang_cc1 -cl-std=CL2.0 -triple amd

[PATCH] D47154: Try to make builtin address space declarations not useless

2018-07-09 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: lib/CodeGen/CGBuiltin.cpp:3500
+if (auto *PtrTy = dyn_cast(PTy)) {
+  if (PtrTy->getAddressSpace() !=
+  ArgValue->getType()->getPointerAddressSpace()) {

Anastasia wrote:
> arsenm wrote:
> > Anastasia wrote:
> > > arsenm wrote:
> > > > Anastasia wrote:
> > > > > Would this be correct for OpenCL? Should we use  
> > > > > `isAddressSpaceSupersetOf` helper instead? Would it also sort the 
> > > > > issue with constant AS (at least for OpenCL)? 
> > > > The issue I mentioned for the other builtin is that it modifies the 
> > > > memory, and doesn't have to do with the casting.
> > > > 
> > > > At this point the AddrSpaceCast has to be emitted. The checking if the 
> > > > cast is legal I guess would be in the SemaExpr part. I know at one 
> > > > point I was trying to use isAddressSpaceSupersetOf in 
> > > > rewriteBuiltinFunctionDecl, but there was some problem with that. I 
> > > > think it didn't make sense with the magic where the builtin without an 
> > > > address space is supposed to accept any address space or something 
> > > > along those lines.
> > > Yes, I think Sema has to check it before indeed. I am not sure it works 
> > > right with OpenCL rules though for the Builtin functions.  Would it make 
> > > sense to add a negative test for this then? 
> > I'm not sure what this test would look like. Do you mean a test that 
> > erroneously is accepted now?
> Ok, so at this point you are trying to change generation of `bitcast` to 
> `addrspacecast` which makes sense to me. Do we still need a `bitcast` though?
> 
> I think `addrspacecast` can be used to convert type and address space too:
>   The ‘addrspacecast‘ instruction converts ptrval from pty in address space n 
> to type pty2 in address space m.
> 
> It would be nice to add proper Sema checking for `Builtins` for address space 
> of pointers in OpenCL mode, but this might be more work.
I think the canonical form is to use the bitcast for the type pointer 
conversion, and then separate the addrspacecast. I think instcombine splits 
these apart



Comment at: test/CodeGenOpenCL/numbered-address-space.cl:36
+#if 0
+// XXX: Should this compile?
+void 
test_generic_as_to_builtin_parameter_explicit_cast_numeric(__attribute__((address_space(3)))
 int *local_ptr, float src) {

Anastasia wrote:
> arsenm wrote:
> > Anastasia wrote:
> > > `__attribute__((address_space(N)))` is not an OpenCL feature and I think 
> > > it's not specified in C either? But I think generally non matching 
> > > address spaces don't compile in Clang. So it might be useful to disallow 
> > > this?
> > I'm pretty sure it's a C extension. The way things seem to work now is 
> > address spaces are accepted anywhere and everywhere.
> Yes, the line below should give an error for OpenCL?
>   generic int* generic_ptr = local_ptr;
This does not error. The wording of the spec seems to leave some interpretation 
for other address spaces. It whitelists the valid address spaces for implicit 
casts, and blacklists constant for implicit or explicit casts. My reading 
between the lines is that an explicit cast would be OK. I think this is a 
separate fix since this is independent from the builtins


https://reviews.llvm.org/D47154



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


[PATCH] D48940: [clangd] Wait for first preamble before code completion

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

- Add a test


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D48940

Files:
  clangd/TUScheduler.cpp
  clangd/TUScheduler.h
  unittests/clangd/TUSchedulerTests.cpp

Index: unittests/clangd/TUSchedulerTests.cpp
===
--- unittests/clangd/TUSchedulerTests.cpp
+++ unittests/clangd/TUSchedulerTests.cpp
@@ -19,6 +19,7 @@
 namespace clangd {
 
 using ::testing::_;
+using ::testing::Each;
 using ::testing::AnyOf;
 using ::testing::Pair;
 using ::testing::Pointee;
@@ -299,5 +300,40 @@
   UnorderedElementsAre(Foo, AnyOf(Bar, Baz)));
 }
 
+TEST_F(TUSchedulerTests, RunWaitsForPreamble) {
+  // Testing strategy: we update the file and schedule a few preamble reads at
+  // the same time. All reads should get the same non-null preamble.
+  TUScheduler S(
+  /*AsyncThreadsCount=*/4, /*StorePreambleInMemory=*/true,
+  PreambleParsedCallback(),
+  /*UpdateDebounce=*/std::chrono::steady_clock::duration::zero(),
+  ASTRetentionPolicy());
+  auto Foo = testPath("foo.cpp");
+  auto NonEmptyPreamble = R"cpp(
+#define FOO 1
+#define BAR 2
+
+int main() {}
+  )cpp";
+  constexpr int ReadsToSchedule = 10;
+  std::mutex PreamblesMut;
+  std::vector Preambles(ReadsToSchedule, nullptr);
+  S.update(Foo, getInputs(Foo, NonEmptyPreamble), WantDiagnostics::Auto,
+   [](std::vector) {});
+  for (int I = 0; I < ReadsToSchedule; ++I) {
+S.runWithPreamble(
+"test", Foo,
+[I, &PreamblesMut, &Preambles](llvm::Expected IP) {
+  std::lock_guard Lock(PreamblesMut);
+  Preambles[I] = cantFail(std::move(IP)).Preamble;
+});
+  }
+  ASSERT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
+  // Check all actions got the same non-null preamble.
+  std::lock_guard Lock(PreamblesMut);
+  ASSERT_NE(Preambles[0], nullptr);
+  ASSERT_THAT(Preambles, Each(Preambles[0]));
+}
+
 } // namespace clangd
 } // namespace clang
Index: clangd/TUScheduler.h
===
--- clangd/TUScheduler.h
+++ clangd/TUScheduler.h
@@ -101,6 +101,9 @@
   /// - validate that the preamble is still valid, and only use it in this case
   /// - accept that preamble contents may be outdated, and try to avoid reading
   ///   source code from headers.
+  /// If there's no preamble yet (because the file was just opened), we'll wait
+  /// for it to build. The preamble may still be null if it fails to build or is
+  /// empty.
   /// If an error occurs during processing, it is forwarded to the \p Action
   /// callback.
   void runWithPreamble(llvm::StringRef Name, PathRef File,
Index: clangd/TUScheduler.cpp
===
--- clangd/TUScheduler.cpp
+++ clangd/TUScheduler.cpp
@@ -176,6 +176,12 @@
   bool blockUntilIdle(Deadline Timeout) const;
 
   std::shared_ptr getPossiblyStalePreamble() const;
+  /// Wait for the first build of preamble to finish. Preamble itself can be
+  /// accessed via getPossibleStalePreamble(). Note that this function will
+  /// return after an unsuccessful build of the preamble too, i.e. result of
+  /// getPossiblyStalePreamble() can be null even after this function returns.
+  void waitForFirstPreamble() const;
+
   std::size_t getUsedBytes() const;
   bool isASTCached() const;
 
@@ -226,6 +232,8 @@
   /// Guards members used by both TUScheduler and the worker thread.
   mutable std::mutex Mutex;
   std::shared_ptr LastBuiltPreamble; /* GUARDED_BY(Mutex) */
+  /// Becomes ready when the first preamble build finishes.
+  Notification PreambleWasBuilt;
   /// Set to true to signal run() to finish processing.
   bool Done;/* GUARDED_BY(Mutex) */
   std::deque Requests; /* GUARDED_BY(Mutex) */
@@ -329,6 +337,9 @@
 buildCompilerInvocation(Inputs);
 if (!Invocation) {
   log("Could not build CompilerInvocation for file " + FileName);
+  // Make sure anyone waiting for the preamble gets notified it could not
+  // be built.
+  PreambleWasBuilt.notify();
   return;
 }
 
@@ -340,6 +351,8 @@
   if (NewPreamble)
 LastBuiltPreamble = NewPreamble;
 }
+PreambleWasBuilt.notify();
+
 // Build the AST for diagnostics.
 llvm::Optional AST =
 buildAST(FileName, std::move(Invocation), Inputs, NewPreamble, PCHs);
@@ -392,6 +405,10 @@
   return LastBuiltPreamble;
 }
 
+void ASTWorker::waitForFirstPreamble() const {
+  PreambleWasBuilt.wait();
+}
+
 std::size_t ASTWorker::getUsedBytes() const {
   // Note that we don't report the size of ASTs currently used for processing
   // the in-flight requests. We used this information for debugging purposes
@@ -655,6 +672,11 @@
  std::string Contents,
  tooling::CompileCommand Command, Context C

[PATCH] D48940: [clangd] Wait for first preamble before code completion

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

In https://reviews.llvm.org/D48940#1152750, @sammccall wrote:

> Possible test: add a file with complicated preamble (billion laughs?) and 
> immediately schedule 5 preamble actions. They should all get a non-null 
> preamble and the pointers should all be the same.


The most trivial test that updates a file and immediately schedules a few 
preamble actions failed without this change for me. I have added it to the 
patch.




Comment at: clangd/TUScheduler.cpp:408
 
+void ASTWorker::waitForFirstPreamble() const {
+  PreambleWasBuilt.wait();

sammccall wrote:
> inline? should fit on one line...
This is used in TUScheduler, where we don't have access to the fields of 
ASTWorker.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D48940



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


[PATCH] D48940: [clangd] Wait for first preamble before code completion

2018-07-09 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE336538: [clangd] Wait for first preamble before code 
completion (authored by ibiryukov, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D48940?vs=154562&id=154563#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D48940

Files:
  clangd/TUScheduler.cpp
  clangd/TUScheduler.h
  unittests/clangd/TUSchedulerTests.cpp

Index: unittests/clangd/TUSchedulerTests.cpp
===
--- unittests/clangd/TUSchedulerTests.cpp
+++ unittests/clangd/TUSchedulerTests.cpp
@@ -19,6 +19,7 @@
 namespace clangd {
 
 using ::testing::_;
+using ::testing::Each;
 using ::testing::AnyOf;
 using ::testing::Pair;
 using ::testing::Pointee;
@@ -299,5 +300,40 @@
   UnorderedElementsAre(Foo, AnyOf(Bar, Baz)));
 }
 
+TEST_F(TUSchedulerTests, RunWaitsForPreamble) {
+  // Testing strategy: we update the file and schedule a few preamble reads at
+  // the same time. All reads should get the same non-null preamble.
+  TUScheduler S(
+  /*AsyncThreadsCount=*/4, /*StorePreambleInMemory=*/true,
+  PreambleParsedCallback(),
+  /*UpdateDebounce=*/std::chrono::steady_clock::duration::zero(),
+  ASTRetentionPolicy());
+  auto Foo = testPath("foo.cpp");
+  auto NonEmptyPreamble = R"cpp(
+#define FOO 1
+#define BAR 2
+
+int main() {}
+  )cpp";
+  constexpr int ReadsToSchedule = 10;
+  std::mutex PreamblesMut;
+  std::vector Preambles(ReadsToSchedule, nullptr);
+  S.update(Foo, getInputs(Foo, NonEmptyPreamble), WantDiagnostics::Auto,
+   [](std::vector) {});
+  for (int I = 0; I < ReadsToSchedule; ++I) {
+S.runWithPreamble(
+"test", Foo,
+[I, &PreamblesMut, &Preambles](llvm::Expected IP) {
+  std::lock_guard Lock(PreamblesMut);
+  Preambles[I] = cantFail(std::move(IP)).Preamble;
+});
+  }
+  ASSERT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
+  // Check all actions got the same non-null preamble.
+  std::lock_guard Lock(PreamblesMut);
+  ASSERT_NE(Preambles[0], nullptr);
+  ASSERT_THAT(Preambles, Each(Preambles[0]));
+}
+
 } // namespace clangd
 } // namespace clang
Index: clangd/TUScheduler.h
===
--- clangd/TUScheduler.h
+++ clangd/TUScheduler.h
@@ -101,6 +101,9 @@
   /// - validate that the preamble is still valid, and only use it in this case
   /// - accept that preamble contents may be outdated, and try to avoid reading
   ///   source code from headers.
+  /// If there's no preamble yet (because the file was just opened), we'll wait
+  /// for it to build. The preamble may still be null if it fails to build or is
+  /// empty.
   /// If an error occurs during processing, it is forwarded to the \p Action
   /// callback.
   void runWithPreamble(llvm::StringRef Name, PathRef File,
Index: clangd/TUScheduler.cpp
===
--- clangd/TUScheduler.cpp
+++ clangd/TUScheduler.cpp
@@ -176,6 +176,12 @@
   bool blockUntilIdle(Deadline Timeout) const;
 
   std::shared_ptr getPossiblyStalePreamble() const;
+  /// Wait for the first build of preamble to finish. Preamble itself can be
+  /// accessed via getPossibleStalePreamble(). Note that this function will
+  /// return after an unsuccessful build of the preamble too, i.e. result of
+  /// getPossiblyStalePreamble() can be null even after this function returns.
+  void waitForFirstPreamble() const;
+
   std::size_t getUsedBytes() const;
   bool isASTCached() const;
 
@@ -226,6 +232,8 @@
   /// Guards members used by both TUScheduler and the worker thread.
   mutable std::mutex Mutex;
   std::shared_ptr LastBuiltPreamble; /* GUARDED_BY(Mutex) */
+  /// Becomes ready when the first preamble build finishes.
+  Notification PreambleWasBuilt;
   /// Set to true to signal run() to finish processing.
   bool Done;/* GUARDED_BY(Mutex) */
   std::deque Requests; /* GUARDED_BY(Mutex) */
@@ -329,6 +337,9 @@
 buildCompilerInvocation(Inputs);
 if (!Invocation) {
   log("Could not build CompilerInvocation for file " + FileName);
+  // Make sure anyone waiting for the preamble gets notified it could not
+  // be built.
+  PreambleWasBuilt.notify();
   return;
 }
 
@@ -340,6 +351,8 @@
   if (NewPreamble)
 LastBuiltPreamble = NewPreamble;
 }
+PreambleWasBuilt.notify();
+
 // Build the AST for diagnostics.
 llvm::Optional AST =
 buildAST(FileName, std::move(Invocation), Inputs, NewPreamble, PCHs);
@@ -392,6 +405,10 @@
   return LastBuiltPreamble;
 }
 
+void ASTWorker::waitForFirstPreamble() const {
+  PreambleWasBuilt.wait();
+}
+
 std::size_t ASTWorker::getUsedBytes() const {
   // Note that we don't report the size of ASTs currently used for processing
   // the in-flight requests. We used this information for debugging purposes
@@ -655,6 +672,11 @@
 

[PATCH] D48940: [clangd] Wait for first preamble before code completion

2018-07-09 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL336538: [clangd] Wait for first preamble before code 
completion (authored by ibiryukov, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D48940

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

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
@@ -19,6 +19,7 @@
 namespace clangd {
 
 using ::testing::_;
+using ::testing::Each;
 using ::testing::AnyOf;
 using ::testing::Pair;
 using ::testing::Pointee;
@@ -299,5 +300,40 @@
   UnorderedElementsAre(Foo, AnyOf(Bar, Baz)));
 }
 
+TEST_F(TUSchedulerTests, RunWaitsForPreamble) {
+  // Testing strategy: we update the file and schedule a few preamble reads at
+  // the same time. All reads should get the same non-null preamble.
+  TUScheduler S(
+  /*AsyncThreadsCount=*/4, /*StorePreambleInMemory=*/true,
+  PreambleParsedCallback(),
+  /*UpdateDebounce=*/std::chrono::steady_clock::duration::zero(),
+  ASTRetentionPolicy());
+  auto Foo = testPath("foo.cpp");
+  auto NonEmptyPreamble = R"cpp(
+#define FOO 1
+#define BAR 2
+
+int main() {}
+  )cpp";
+  constexpr int ReadsToSchedule = 10;
+  std::mutex PreamblesMut;
+  std::vector Preambles(ReadsToSchedule, nullptr);
+  S.update(Foo, getInputs(Foo, NonEmptyPreamble), WantDiagnostics::Auto,
+   [](std::vector) {});
+  for (int I = 0; I < ReadsToSchedule; ++I) {
+S.runWithPreamble(
+"test", Foo,
+[I, &PreamblesMut, &Preambles](llvm::Expected IP) {
+  std::lock_guard Lock(PreamblesMut);
+  Preambles[I] = cantFail(std::move(IP)).Preamble;
+});
+  }
+  ASSERT_TRUE(S.blockUntilIdle(timeoutSeconds(10)));
+  // Check all actions got the same non-null preamble.
+  std::lock_guard Lock(PreamblesMut);
+  ASSERT_NE(Preambles[0], nullptr);
+  ASSERT_THAT(Preambles, Each(Preambles[0]));
+}
+
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/trunk/clangd/TUScheduler.h
===
--- clang-tools-extra/trunk/clangd/TUScheduler.h
+++ clang-tools-extra/trunk/clangd/TUScheduler.h
@@ -101,6 +101,9 @@
   /// - validate that the preamble is still valid, and only use it in this case
   /// - accept that preamble contents may be outdated, and try to avoid reading
   ///   source code from headers.
+  /// If there's no preamble yet (because the file was just opened), we'll wait
+  /// for it to build. The preamble may still be null if it fails to build or is
+  /// empty.
   /// If an error occurs during processing, it is forwarded to the \p Action
   /// callback.
   void runWithPreamble(llvm::StringRef Name, PathRef File,
Index: clang-tools-extra/trunk/clangd/TUScheduler.cpp
===
--- clang-tools-extra/trunk/clangd/TUScheduler.cpp
+++ clang-tools-extra/trunk/clangd/TUScheduler.cpp
@@ -176,6 +176,12 @@
   bool blockUntilIdle(Deadline Timeout) const;
 
   std::shared_ptr getPossiblyStalePreamble() const;
+  /// Wait for the first build of preamble to finish. Preamble itself can be
+  /// accessed via getPossibleStalePreamble(). Note that this function will
+  /// return after an unsuccessful build of the preamble too, i.e. result of
+  /// getPossiblyStalePreamble() can be null even after this function returns.
+  void waitForFirstPreamble() const;
+
   std::size_t getUsedBytes() const;
   bool isASTCached() const;
 
@@ -226,6 +232,8 @@
   /// Guards members used by both TUScheduler and the worker thread.
   mutable std::mutex Mutex;
   std::shared_ptr LastBuiltPreamble; /* GUARDED_BY(Mutex) */
+  /// Becomes ready when the first preamble build finishes.
+  Notification PreambleWasBuilt;
   /// Set to true to signal run() to finish processing.
   bool Done;/* GUARDED_BY(Mutex) */
   std::deque Requests; /* GUARDED_BY(Mutex) */
@@ -329,6 +337,9 @@
 buildCompilerInvocation(Inputs);
 if (!Invocation) {
   log("Could not build CompilerInvocation for file " + FileName);
+  // Make sure anyone waiting for the preamble gets notified it could not
+  // be built.
+  PreambleWasBuilt.notify();
   return;
 }
 
@@ -340,6 +351,8 @@
   if (NewPreamble)
 LastBuiltPreamble = NewPreamble;
 }
+PreambleWasBuilt.notify();
+
 // Build the AST for diagnostics.
 llvm::Optional AST =
 buildAST(FileName, std::move(Invocation), Inputs, NewPreamble, PCHs);
@@ -392,6 +405,10 @@
   return LastBuiltPreamble;
 }
 
+void ASTWorker::waitForFirstPreamble() const {
+  PreambleWasBu

[clang-tools-extra] r336538 - [clangd] Wait for first preamble before code completion

2018-07-09 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Jul  9 03:45:33 2018
New Revision: 336538

URL: http://llvm.org/viewvc/llvm-project?rev=336538&view=rev
Log:
[clangd] Wait for first preamble before code completion

Summary:
To avoid doing extra work of processing headers in the preamble
mutilple times in parallel.

Reviewers: sammccall

Reviewed By: sammccall

Subscribers: javed.absar, ioeric, MaskRay, jkorous, cfe-commits

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

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

Modified: clang-tools-extra/trunk/clangd/TUScheduler.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/TUScheduler.cpp?rev=336538&r1=336537&r2=336538&view=diff
==
--- clang-tools-extra/trunk/clangd/TUScheduler.cpp (original)
+++ clang-tools-extra/trunk/clangd/TUScheduler.cpp Mon Jul  9 03:45:33 2018
@@ -176,6 +176,12 @@ public:
   bool blockUntilIdle(Deadline Timeout) const;
 
   std::shared_ptr getPossiblyStalePreamble() const;
+  /// Wait for the first build of preamble to finish. Preamble itself can be
+  /// accessed via getPossibleStalePreamble(). Note that this function will
+  /// return after an unsuccessful build of the preamble too, i.e. result of
+  /// getPossiblyStalePreamble() can be null even after this function returns.
+  void waitForFirstPreamble() const;
+
   std::size_t getUsedBytes() const;
   bool isASTCached() const;
 
@@ -226,6 +232,8 @@ private:
   /// Guards members used by both TUScheduler and the worker thread.
   mutable std::mutex Mutex;
   std::shared_ptr LastBuiltPreamble; /* GUARDED_BY(Mutex) 
*/
+  /// Becomes ready when the first preamble build finishes.
+  Notification PreambleWasBuilt;
   /// Set to true to signal run() to finish processing.
   bool Done;/* GUARDED_BY(Mutex) */
   std::deque Requests; /* GUARDED_BY(Mutex) */
@@ -329,6 +337,9 @@ void ASTWorker::update(
 buildCompilerInvocation(Inputs);
 if (!Invocation) {
   log("Could not build CompilerInvocation for file " + FileName);
+  // Make sure anyone waiting for the preamble gets notified it could not
+  // be built.
+  PreambleWasBuilt.notify();
   return;
 }
 
@@ -340,6 +351,8 @@ void ASTWorker::update(
   if (NewPreamble)
 LastBuiltPreamble = NewPreamble;
 }
+PreambleWasBuilt.notify();
+
 // Build the AST for diagnostics.
 llvm::Optional AST =
 buildAST(FileName, std::move(Invocation), Inputs, NewPreamble, PCHs);
@@ -392,6 +405,10 @@ ASTWorker::getPossiblyStalePreamble() co
   return LastBuiltPreamble;
 }
 
+void ASTWorker::waitForFirstPreamble() const {
+  PreambleWasBuilt.wait();
+}
+
 std::size_t ASTWorker::getUsedBytes() const {
   // Note that we don't report the size of ASTs currently used for processing
   // the in-flight requests. We used this information for debugging purposes
@@ -655,6 +672,11 @@ void TUScheduler::runWithPreamble(
  std::string Contents,
  tooling::CompileCommand Command, Context Ctx,
  decltype(Action) Action) mutable {
+// We don't want to be running preamble actions before the preamble was
+// built for the first time. This avoids extra work of processing the
+// preamble headers in parallel multiple times.
+Worker->waitForFirstPreamble();
+
 std::lock_guard BarrierLock(Barrier);
 WithContext Guard(std::move(Ctx));
 trace::Span Tracer(Name);

Modified: clang-tools-extra/trunk/clangd/TUScheduler.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/TUScheduler.h?rev=336538&r1=336537&r2=336538&view=diff
==
--- clang-tools-extra/trunk/clangd/TUScheduler.h (original)
+++ clang-tools-extra/trunk/clangd/TUScheduler.h Mon Jul  9 03:45:33 2018
@@ -101,6 +101,9 @@ public:
   /// - validate that the preamble is still valid, and only use it in this case
   /// - accept that preamble contents may be outdated, and try to avoid reading
   ///   source code from headers.
+  /// If there's no preamble yet (because the file was just opened), we'll wait
+  /// for it to build. The preamble may still be null if it fails to build or 
is
+  /// empty.
   /// If an error occurs during processing, it is forwarded to the \p Action
   /// callback.
   void runWithPreamble(llvm::StringRef Name, PathRef File,

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=336538&r1=336537&r2=336538&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/TUSchedulerTests.cpp (original)
+++ 

[PATCH] D49067: Stop wrapping __has_include in another macro

2018-07-09 Thread Alexander Richardson via Phabricator via cfe-commits
arichardson created this revision.
arichardson added reviewers: EricWF, rsmith.
Herald added subscribers: cfe-commits, ldionne, christof.

This is not guaranteed to work since the characters after '__has_include('
have special lexing rules that can't possibly be applied when
__has_include is generated by a macro. It also breaks the crash reproducers
generated by -frewrite-includes (see https://llvm.org/pr37990).


Repository:
  rCXX libc++

https://reviews.llvm.org/D49067

Files:
  include/__config
  test/support/test_macros.h


Index: test/support/test_macros.h
===
--- test/support/test_macros.h
+++ test/support/test_macros.h
@@ -27,10 +27,8 @@
 #define TEST_HAS_FEATURE(X) 0
 #endif
 
-#ifdef __has_include
-#define TEST_HAS_INCLUDE(X) __has_include(X)
-#else
-#define TEST_HAS_INCLUDE(X) 0
+#ifndef __has_include
+#define __has_include(...) 0
 #endif
 
 #ifdef __has_extension
@@ -90,7 +88,7 @@
 #endif
 
 // Attempt to deduce GCC version
-#if defined(_LIBCPP_VERSION) && TEST_HAS_INCLUDE()
+#if defined(_LIBCPP_VERSION) && __has_include()
 #include 
 #define TEST_HAS_GLIBC
 #define TEST_GLIBC_PREREQ(major, minor) __GLIBC_PREREQ(major, minor)
Index: include/__config
===
--- include/__config
+++ include/__config
@@ -149,10 +149,8 @@
 
 #define __has_keyword(__x) !(__is_identifier(__x))
 
-#ifdef __has_include
-#  define __libcpp_has_include(__x) __has_include(__x)
-#else
-#  define __libcpp_has_include(__x) 0
+#ifndef __has_include
+#define __has_include(...) 0
 #endif
 
 #if defined(__clang__)
@@ -1068,7 +1066,7 @@
   defined(__APPLE__) || \
   defined(__CloudABI__) || \
   defined(__sun__) || \
-  (defined(__MINGW32__) && __libcpp_has_include())
+  (defined(__MINGW32__) && __has_include())
 #define _LIBCPP_HAS_THREAD_API_PTHREAD
 #  elif defined(_LIBCPP_WIN32API)
 #define _LIBCPP_HAS_THREAD_API_WIN32


Index: test/support/test_macros.h
===
--- test/support/test_macros.h
+++ test/support/test_macros.h
@@ -27,10 +27,8 @@
 #define TEST_HAS_FEATURE(X) 0
 #endif
 
-#ifdef __has_include
-#define TEST_HAS_INCLUDE(X) __has_include(X)
-#else
-#define TEST_HAS_INCLUDE(X) 0
+#ifndef __has_include
+#define __has_include(...) 0
 #endif
 
 #ifdef __has_extension
@@ -90,7 +88,7 @@
 #endif
 
 // Attempt to deduce GCC version
-#if defined(_LIBCPP_VERSION) && TEST_HAS_INCLUDE()
+#if defined(_LIBCPP_VERSION) && __has_include()
 #include 
 #define TEST_HAS_GLIBC
 #define TEST_GLIBC_PREREQ(major, minor) __GLIBC_PREREQ(major, minor)
Index: include/__config
===
--- include/__config
+++ include/__config
@@ -149,10 +149,8 @@
 
 #define __has_keyword(__x) !(__is_identifier(__x))
 
-#ifdef __has_include
-#  define __libcpp_has_include(__x) __has_include(__x)
-#else
-#  define __libcpp_has_include(__x) 0
+#ifndef __has_include
+#define __has_include(...) 0
 #endif
 
 #if defined(__clang__)
@@ -1068,7 +1066,7 @@
   defined(__APPLE__) || \
   defined(__CloudABI__) || \
   defined(__sun__) || \
-  (defined(__MINGW32__) && __libcpp_has_include())
+  (defined(__MINGW32__) && __has_include())
 #define _LIBCPP_HAS_THREAD_API_PTHREAD
 #  elif defined(_LIBCPP_WIN32API)
 #define _LIBCPP_HAS_THREAD_API_WIN32
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D49068: Fixing builtin __atomic_fetch_min definition

2018-07-09 Thread Omer Paparo Bivas via Phabricator via cfe-commits
opaparo created this revision.
opaparo added a reviewer: delena.
Herald added a subscriber: cfe-commits.

Repository:
  rC Clang

https://reviews.llvm.org/D49068

Files:
  include/clang/Basic/Builtins.def


Index: include/clang/Basic/Builtins.def
===
--- include/clang/Basic/Builtins.def
+++ include/clang/Basic/Builtins.def
@@ -722,7 +722,7 @@
 ATOMIC_BUILTIN(__opencl_atomic_fetch_max, "v.", "t")
 
 // GCC does not support these, they are a Clang extension.
-ATOMIC_BUILTIN(__atomic_fetch_min, "iiD*i.", "t")
+ATOMIC_BUILTIN(__atomic_fetch_min, "v.", "t")
 ATOMIC_BUILTIN(__atomic_fetch_max, "v.", "t")
 
 #undef ATOMIC_BUILTIN


Index: include/clang/Basic/Builtins.def
===
--- include/clang/Basic/Builtins.def
+++ include/clang/Basic/Builtins.def
@@ -722,7 +722,7 @@
 ATOMIC_BUILTIN(__opencl_atomic_fetch_max, "v.", "t")
 
 // GCC does not support these, they are a Clang extension.
-ATOMIC_BUILTIN(__atomic_fetch_min, "iiD*i.", "t")
+ATOMIC_BUILTIN(__atomic_fetch_min, "v.", "t")
 ATOMIC_BUILTIN(__atomic_fetch_max, "v.", "t")
 
 #undef ATOMIC_BUILTIN
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D46871: [AMDGPU] Add interpolation builtins

2018-07-09 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm accepted this revision.
arsenm added a comment.
This revision is now accepted and ready to land.

LGTM. Checking the full operands wouldn't hurt though.


Repository:
  rC Clang

https://reviews.llvm.org/D46871



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


[PATCH] D48943: [clangd] Do not write comments into Preamble PCH

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

- Fix a comment


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D48943

Files:
  clangd/ClangdUnit.cpp
  clangd/CodeCompletionStrings.cpp


Index: clangd/CodeCompletionStrings.cpp
===
--- clangd/CodeCompletionStrings.cpp
+++ clangd/CodeCompletionStrings.cpp
@@ -32,34 +32,6 @@
   }
 }
 
-bool canRequestComment(const ASTContext &Ctx, const NamedDecl &D,
-   bool CommentsFromHeaders) {
-  if (CommentsFromHeaders)
-return true;
-  auto &SourceMgr = Ctx.getSourceManager();
-  // Accessing comments for decls from  invalid preamble can lead to crashes.
-  // So we only return comments from the main file when doing code completion.
-  // For indexing, we still read all the comments.
-  // FIXME: find a better fix, e.g. store file contents in the preamble or get
-  // doc comments from the index.
-  auto canRequestForDecl = [&](const NamedDecl &D) -> bool {
-for (auto *Redecl : D.redecls()) {
-  auto Loc = SourceMgr.getSpellingLoc(Redecl->getLocation());
-  if (!SourceMgr.isWrittenInMainFile(Loc))
-return false;
-}
-return true;
-  };
-  // First, check the decl itself.
-  if (!canRequestForDecl(D))
-return false;
-  // Completion also returns comments for properties, corresponding to ObjC
-  // methods.
-  const ObjCMethodDecl *M = dyn_cast(&D);
-  const ObjCPropertyDecl *PDecl = M ? M->findPropertyDecl() : nullptr;
-  return !PDecl || canRequestForDecl(*PDecl);
-}
-
 bool LooksLikeDocComment(llvm::StringRef CommentText) {
   // We don't report comments that only contain "special" chars.
   // This avoids reporting various delimiters, like:
@@ -87,12 +59,13 @@
 // the comments for namespaces.
 return "";
   }
-  if (!canRequestComment(Ctx, *Decl, CommentsFromHeaders))
-return "";
-
   const RawComment *RC = getCompletionComment(Ctx, Decl);
   if (!RC)
 return "";
+
+  // Sanity check that the comment does not come from the PCH. We choose to not
+  // write them into PCH, because they are racy and slow to load.
+  assert(!Ctx.getSourceManager().isLoadedSourceLocation(RC->getLocStart()));
   std::string Doc = RC->getFormattedText(Ctx.getSourceManager(), 
Ctx.getDiagnostics());
   if (!LooksLikeDocComment(Doc))
 return "";
@@ -104,11 +77,14 @@
const CodeCompleteConsumer::OverloadCandidate &Result,
unsigned ArgIndex, bool CommentsFromHeaders) {
   auto *Func = Result.getFunction();
-  if (!Func || !canRequestComment(Ctx, *Func, CommentsFromHeaders))
+  if (!Func)
 return "";
   const RawComment *RC = getParameterComment(Ctx, Result, ArgIndex);
   if (!RC)
 return "";
+  // Sanity check that the comment does not come from the PCH. We choose to not
+  // write them into PCH, because they are racy and slow to load.
+  assert(!Ctx.getSourceManager().isLoadedSourceLocation(RC->getLocStart()));
   std::string Doc = RC->getFormattedText(Ctx.getSourceManager(), 
Ctx.getDiagnostics());
   if (!LooksLikeDocComment(Doc))
 return "";
Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -24,6 +24,7 @@
 #include "clang/Lex/Lexer.h"
 #include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/PreprocessorOptions.h"
 #include "clang/Sema/Sema.h"
 #include "clang/Serialization/ASTWriter.h"
 #include "clang/Tooling/CompilationDatabase.h"
@@ -323,6 +324,9 @@
   // the preamble and make it smaller.
   assert(!CI.getFrontendOpts().SkipFunctionBodies);
   CI.getFrontendOpts().SkipFunctionBodies = true;
+  // We don't want to write comment locations into PCH. They are racy and slow
+  // to read back. We rely on dynamic index for the comments instead.
+  CI.getPreprocessorOpts().WriteCommentListToPCH = false;
 
   CppFilePreambleCallbacks SerializedDeclsCollector(FileName, 
PreambleCallback);
   if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {


Index: clangd/CodeCompletionStrings.cpp
===
--- clangd/CodeCompletionStrings.cpp
+++ clangd/CodeCompletionStrings.cpp
@@ -32,34 +32,6 @@
   }
 }
 
-bool canRequestComment(const ASTContext &Ctx, const NamedDecl &D,
-   bool CommentsFromHeaders) {
-  if (CommentsFromHeaders)
-return true;
-  auto &SourceMgr = Ctx.getSourceManager();
-  // Accessing comments for decls from  invalid preamble can lead to crashes.
-  // So we only return comments from the main file when doing code completion.
-  // For indexing, we still read all the comments.
-  // FIXME: find a better fix, e.g. store file contents in the preamble or get
-  // doc comments from the index.
-  auto canRequestForDecl = [&](const NamedDecl &D) -> bool {
-  

[clang-tools-extra] r336540 - [clangd] Do not write comments into Preamble PCH

2018-07-09 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Jul  9 04:33:31 2018
New Revision: 336540

URL: http://llvm.org/viewvc/llvm-project?rev=336540&view=rev
Log:
[clangd] Do not write comments into Preamble PCH

Summary:
To avoid wasting time deserializing them on code completion and
further reparses.

We do not use the comments anyway, because we cannot rely on the file
contents staying the same for reparses that reuse the prebuilt
preamble PCH.

Reviewers: sammccall

Reviewed By: sammccall

Subscribers: ioeric, MaskRay, jkorous, cfe-commits

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

Modified:
clang-tools-extra/trunk/clangd/ClangdUnit.cpp
clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdUnit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdUnit.cpp?rev=336540&r1=336539&r2=336540&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdUnit.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdUnit.cpp Mon Jul  9 04:33:31 2018
@@ -24,6 +24,7 @@
 #include "clang/Lex/Lexer.h"
 #include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/PreprocessorOptions.h"
 #include "clang/Sema/Sema.h"
 #include "clang/Serialization/ASTWriter.h"
 #include "clang/Tooling/CompilationDatabase.h"
@@ -323,6 +324,9 @@ std::shared_ptr clan
   // the preamble and make it smaller.
   assert(!CI.getFrontendOpts().SkipFunctionBodies);
   CI.getFrontendOpts().SkipFunctionBodies = true;
+  // We don't want to write comment locations into PCH. They are racy and slow
+  // to read back. We rely on dynamic index for the comments instead.
+  CI.getPreprocessorOpts().WriteCommentListToPCH = false;
 
   CppFilePreambleCallbacks SerializedDeclsCollector(FileName, 
PreambleCallback);
   if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {

Modified: clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp?rev=336540&r1=336539&r2=336540&view=diff
==
--- clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeCompletionStrings.cpp Mon Jul  9 
04:33:31 2018
@@ -32,34 +32,6 @@ void appendEscapeSnippet(const llvm::Str
   }
 }
 
-bool canRequestComment(const ASTContext &Ctx, const NamedDecl &D,
-   bool CommentsFromHeaders) {
-  if (CommentsFromHeaders)
-return true;
-  auto &SourceMgr = Ctx.getSourceManager();
-  // Accessing comments for decls from  invalid preamble can lead to crashes.
-  // So we only return comments from the main file when doing code completion.
-  // For indexing, we still read all the comments.
-  // FIXME: find a better fix, e.g. store file contents in the preamble or get
-  // doc comments from the index.
-  auto canRequestForDecl = [&](const NamedDecl &D) -> bool {
-for (auto *Redecl : D.redecls()) {
-  auto Loc = SourceMgr.getSpellingLoc(Redecl->getLocation());
-  if (!SourceMgr.isWrittenInMainFile(Loc))
-return false;
-}
-return true;
-  };
-  // First, check the decl itself.
-  if (!canRequestForDecl(D))
-return false;
-  // Completion also returns comments for properties, corresponding to ObjC
-  // methods.
-  const ObjCMethodDecl *M = dyn_cast(&D);
-  const ObjCPropertyDecl *PDecl = M ? M->findPropertyDecl() : nullptr;
-  return !PDecl || canRequestForDecl(*PDecl);
-}
-
 bool LooksLikeDocComment(llvm::StringRef CommentText) {
   // We don't report comments that only contain "special" chars.
   // This avoids reporting various delimiters, like:
@@ -87,12 +59,13 @@ std::string getDocComment(const ASTConte
 // the comments for namespaces.
 return "";
   }
-  if (!canRequestComment(Ctx, *Decl, CommentsFromHeaders))
-return "";
-
   const RawComment *RC = getCompletionComment(Ctx, Decl);
   if (!RC)
 return "";
+
+  // Sanity check that the comment does not come from the PCH. We choose to not
+  // write them into PCH, because they are racy and slow to load.
+  assert(!Ctx.getSourceManager().isLoadedSourceLocation(RC->getLocStart()));
   std::string Doc = RC->getFormattedText(Ctx.getSourceManager(), 
Ctx.getDiagnostics());
   if (!LooksLikeDocComment(Doc))
 return "";
@@ -104,11 +77,14 @@ getParameterDocComment(const ASTContext
const CodeCompleteConsumer::OverloadCandidate &Result,
unsigned ArgIndex, bool CommentsFromHeaders) {
   auto *Func = Result.getFunction();
-  if (!Func || !canRequestComment(Ctx, *Func, CommentsFromHeaders))
+  if (!Func)
 return "";
   const RawComment *RC = getParameterComment(Ctx, Result, ArgIndex);
   if (!RC)
 return "";
+  // Sanity check that the comment does not come from the PCH. We choose to not
+  // write them into PCH, 

r336539 - [PCH] Add an option to not write comments into PCH

2018-07-09 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Mon Jul  9 04:33:23 2018
New Revision: 336539

URL: http://llvm.org/viewvc/llvm-project?rev=336539&view=rev
Log:
[PCH] Add an option to not write comments into PCH

Summary:
Will be used in clangd, see the follow-up change.
Clangd does not use comments read from PCH to avoid crashes due to
changed contents of the file. However, reading them considerably slows
down code completion on files with large preambles.

Reviewers: sammccall

Reviewed By: sammccall

Subscribers: ioeric, cfe-commits

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

Modified:
cfe/trunk/include/clang/Lex/PreprocessorOptions.h
cfe/trunk/lib/Serialization/ASTWriter.cpp

Modified: cfe/trunk/include/clang/Lex/PreprocessorOptions.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/PreprocessorOptions.h?rev=336539&r1=336538&r2=336539&view=diff
==
--- cfe/trunk/include/clang/Lex/PreprocessorOptions.h (original)
+++ cfe/trunk/include/clang/Lex/PreprocessorOptions.h Mon Jul  9 04:33:23 2018
@@ -95,6 +95,11 @@ public:
   /// processing the rest of the file.
   bool GeneratePreamble = false;
 
+  /// Whether to write comment locations into the PCH when building it.
+  /// Reading the comments from the PCH can be a performance hit even if the
+  /// clients don't use them.
+  bool WriteCommentListToPCH = true;
+
   /// The implicit PTH input included at the start of the translation unit, or
   /// empty.
   std::string ImplicitPTHInclude;

Modified: cfe/trunk/lib/Serialization/ASTWriter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Serialization/ASTWriter.cpp?rev=336539&r1=336538&r2=336539&view=diff
==
--- cfe/trunk/lib/Serialization/ASTWriter.cpp (original)
+++ cfe/trunk/lib/Serialization/ASTWriter.cpp Mon Jul  9 04:33:23 2018
@@ -78,6 +78,7 @@
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/PointerIntPair.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
@@ -3252,6 +3253,9 @@ void ASTWriter::WriteFileDeclIDsMap() {
 
 void ASTWriter::WriteComments() {
   Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
+  auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
+  if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
+return;
   ArrayRef RawComments = Context->Comments.getComments();
   RecordData Record;
   for (const auto *I : RawComments) {
@@ -3262,7 +3266,6 @@ void ASTWriter::WriteComments() {
 Record.push_back(I->isAlmostTrailingComment());
 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
   }
-  Stream.ExitBlock();
 }
 
 
//===--===//


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


[PATCH] D48942: [PCH] Add an option to not write comments into PCH

2018-07-09 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC336539: [PCH] Add an option to not write comments into PCH 
(authored by ibiryukov, committed by ).
Herald added a subscriber: omtcyfz.

Changed prior to commit:
  https://reviews.llvm.org/D48942?vs=154115&id=154571#toc

Repository:
  rC Clang

https://reviews.llvm.org/D48942

Files:
  include/clang/Lex/PreprocessorOptions.h
  lib/Serialization/ASTWriter.cpp


Index: include/clang/Lex/PreprocessorOptions.h
===
--- include/clang/Lex/PreprocessorOptions.h
+++ include/clang/Lex/PreprocessorOptions.h
@@ -95,6 +95,11 @@
   /// processing the rest of the file.
   bool GeneratePreamble = false;
 
+  /// Whether to write comment locations into the PCH when building it.
+  /// Reading the comments from the PCH can be a performance hit even if the
+  /// clients don't use them.
+  bool WriteCommentListToPCH = true;
+
   /// The implicit PTH input included at the start of the translation unit, or
   /// empty.
   std::string ImplicitPTHInclude;
Index: lib/Serialization/ASTWriter.cpp
===
--- lib/Serialization/ASTWriter.cpp
+++ lib/Serialization/ASTWriter.cpp
@@ -78,6 +78,7 @@
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/PointerIntPair.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
@@ -3252,6 +3253,9 @@
 
 void ASTWriter::WriteComments() {
   Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
+  auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
+  if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
+return;
   ArrayRef RawComments = Context->Comments.getComments();
   RecordData Record;
   for (const auto *I : RawComments) {
@@ -3262,7 +3266,6 @@
 Record.push_back(I->isAlmostTrailingComment());
 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
   }
-  Stream.ExitBlock();
 }
 
 
//===--===//


Index: include/clang/Lex/PreprocessorOptions.h
===
--- include/clang/Lex/PreprocessorOptions.h
+++ include/clang/Lex/PreprocessorOptions.h
@@ -95,6 +95,11 @@
   /// processing the rest of the file.
   bool GeneratePreamble = false;
 
+  /// Whether to write comment locations into the PCH when building it.
+  /// Reading the comments from the PCH can be a performance hit even if the
+  /// clients don't use them.
+  bool WriteCommentListToPCH = true;
+
   /// The implicit PTH input included at the start of the translation unit, or
   /// empty.
   std::string ImplicitPTHInclude;
Index: lib/Serialization/ASTWriter.cpp
===
--- lib/Serialization/ASTWriter.cpp
+++ lib/Serialization/ASTWriter.cpp
@@ -78,6 +78,7 @@
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/PointerIntPair.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
@@ -3252,6 +3253,9 @@
 
 void ASTWriter::WriteComments() {
   Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
+  auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
+  if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
+return;
   ArrayRef RawComments = Context->Comments.getComments();
   RecordData Record;
   for (const auto *I : RawComments) {
@@ -3262,7 +3266,6 @@
 Record.push_back(I->isAlmostTrailingComment());
 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
   }
-  Stream.ExitBlock();
 }
 
 //===--===//
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D48943: [clangd] Do not write comments into Preamble PCH

2018-07-09 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE336540: [clangd] Do not write comments into Preamble PCH 
(authored by ibiryukov, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D48943?vs=154569&id=154572#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D48943

Files:
  clangd/ClangdUnit.cpp
  clangd/CodeCompletionStrings.cpp


Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -24,6 +24,7 @@
 #include "clang/Lex/Lexer.h"
 #include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/PreprocessorOptions.h"
 #include "clang/Sema/Sema.h"
 #include "clang/Serialization/ASTWriter.h"
 #include "clang/Tooling/CompilationDatabase.h"
@@ -323,6 +324,9 @@
   // the preamble and make it smaller.
   assert(!CI.getFrontendOpts().SkipFunctionBodies);
   CI.getFrontendOpts().SkipFunctionBodies = true;
+  // We don't want to write comment locations into PCH. They are racy and slow
+  // to read back. We rely on dynamic index for the comments instead.
+  CI.getPreprocessorOpts().WriteCommentListToPCH = false;
 
   CppFilePreambleCallbacks SerializedDeclsCollector(FileName, 
PreambleCallback);
   if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
Index: clangd/CodeCompletionStrings.cpp
===
--- clangd/CodeCompletionStrings.cpp
+++ clangd/CodeCompletionStrings.cpp
@@ -32,34 +32,6 @@
   }
 }
 
-bool canRequestComment(const ASTContext &Ctx, const NamedDecl &D,
-   bool CommentsFromHeaders) {
-  if (CommentsFromHeaders)
-return true;
-  auto &SourceMgr = Ctx.getSourceManager();
-  // Accessing comments for decls from  invalid preamble can lead to crashes.
-  // So we only return comments from the main file when doing code completion.
-  // For indexing, we still read all the comments.
-  // FIXME: find a better fix, e.g. store file contents in the preamble or get
-  // doc comments from the index.
-  auto canRequestForDecl = [&](const NamedDecl &D) -> bool {
-for (auto *Redecl : D.redecls()) {
-  auto Loc = SourceMgr.getSpellingLoc(Redecl->getLocation());
-  if (!SourceMgr.isWrittenInMainFile(Loc))
-return false;
-}
-return true;
-  };
-  // First, check the decl itself.
-  if (!canRequestForDecl(D))
-return false;
-  // Completion also returns comments for properties, corresponding to ObjC
-  // methods.
-  const ObjCMethodDecl *M = dyn_cast(&D);
-  const ObjCPropertyDecl *PDecl = M ? M->findPropertyDecl() : nullptr;
-  return !PDecl || canRequestForDecl(*PDecl);
-}
-
 bool LooksLikeDocComment(llvm::StringRef CommentText) {
   // We don't report comments that only contain "special" chars.
   // This avoids reporting various delimiters, like:
@@ -87,12 +59,13 @@
 // the comments for namespaces.
 return "";
   }
-  if (!canRequestComment(Ctx, *Decl, CommentsFromHeaders))
-return "";
-
   const RawComment *RC = getCompletionComment(Ctx, Decl);
   if (!RC)
 return "";
+
+  // Sanity check that the comment does not come from the PCH. We choose to not
+  // write them into PCH, because they are racy and slow to load.
+  assert(!Ctx.getSourceManager().isLoadedSourceLocation(RC->getLocStart()));
   std::string Doc = RC->getFormattedText(Ctx.getSourceManager(), 
Ctx.getDiagnostics());
   if (!LooksLikeDocComment(Doc))
 return "";
@@ -104,11 +77,14 @@
const CodeCompleteConsumer::OverloadCandidate &Result,
unsigned ArgIndex, bool CommentsFromHeaders) {
   auto *Func = Result.getFunction();
-  if (!Func || !canRequestComment(Ctx, *Func, CommentsFromHeaders))
+  if (!Func)
 return "";
   const RawComment *RC = getParameterComment(Ctx, Result, ArgIndex);
   if (!RC)
 return "";
+  // Sanity check that the comment does not come from the PCH. We choose to not
+  // write them into PCH, because they are racy and slow to load.
+  assert(!Ctx.getSourceManager().isLoadedSourceLocation(RC->getLocStart()));
   std::string Doc = RC->getFormattedText(Ctx.getSourceManager(), 
Ctx.getDiagnostics());
   if (!LooksLikeDocComment(Doc))
 return "";


Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -24,6 +24,7 @@
 #include "clang/Lex/Lexer.h"
 #include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/PreprocessorOptions.h"
 #include "clang/Sema/Sema.h"
 #include "clang/Serialization/ASTWriter.h"
 #include "clang/Tooling/CompilationDatabase.h"
@@ -323,6 +324,9 @@
   // the preamble and make it smaller.
   assert(!CI.getFrontendOpts().SkipFunctionBodies);
   CI.getFrontendOpts().SkipFunctionBodies = true;
+  // We don't want to write comment locations into PCH. They are racy and slow
+  // 

[PATCH] D47817: [sanitizer_common] Fix using libtirpc on Linux

2018-07-09 Thread Peter Wu via Phabricator via cfe-commits
Lekensteyn added a comment.

Hi, thank you for the patch. First a disclaimer, I am not familiar with this 
RPC API at all.

This would be the first user of pkg-config here. I am not sure if this would be 
the best fix. Usually you cannot (easily) recompile libc and override it, but 
for external libs such as libtirpc this should be more doable (I think).

I'm not comfortable with adding the tirpc include path to the default include 
path and stripping `-nodefaultlibs` either, would this approach work for 
cross-compilation?


Repository:
  rCRT Compiler Runtime

https://reviews.llvm.org/D47817



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


[PATCH] D49073: Introducing __builtin_speculation_safe_value

2018-07-09 Thread Kristof Beyls via Phabricator via cfe-commits
kristof.beyls created this revision.
Herald added subscribers: cfe-commits, aheejin, dschuff.

This is part of implementing a technique to mitigate against Spectre v1,
similar in spirit to what has been proposed by Chandler for X86_64 at
http://lists.llvm.org/pipermail/llvm-dev/2018-March/122085.html.

This patch adds a new builtin function that provides a mechanism for
limiting the effects of miss-speculation by a CPU.
This patch provides the clang-side of the needed functionality; there is
also an llvm-side patch this patch is dependent on.

We've tried to design this in such a way that it can be used for any
target where this might be necessary. The patch provides a generic
implementation of the builtin, with most of the target-specific
support in the LLVM counter part to this clang patch.

The signature of the new, polymorphic, builtin is:

T __builtin_speculation_safe_value(T v)

T can be any integral type (signed or unsigned char, int, short, long,
etc) or any pointer type.

The builtin assures that value v will be made 0 on execution paths that
are being executed under control flow miss-speculation by the CPU, when
the miss-speculated path originated due to misprediction of a direct
conditional branch.

Whereas this still leaves open the possibility of execution on a
miss-speculated path starting at misprediction of other control flow
instructions, our believe is that the above guarantee is still useful in
mitigating vulnerability to Spectre v1-style attacks and implementable
for most, if not all, target instruction sets.

This also introduces the predefined pre-processor macro
__HAVE_SPECULATION_SAFE_LOAD, that allows users to check if their
version of the compiler supports this intrinsic.


Repository:
  rC Clang

https://reviews.llvm.org/D49073

Files:
  include/clang/Basic/Builtins.def
  include/clang/Basic/DiagnosticSemaKinds.td
  include/clang/Sema/Sema.h
  lib/CodeGen/CGBuiltin.cpp
  lib/Frontend/InitPreprocessor.cpp
  lib/Sema/SemaChecking.cpp
  test/CodeGen/builtin-speculation-safe-value.c
  test/Preprocessor/init.c
  test/Sema/builtin-speculation-safe-value.c
  test/Sema/builtin-speculation-safe-value.cpp

Index: test/Sema/builtin-speculation-safe-value.cpp
===
--- /dev/null
+++ test/Sema/builtin-speculation-safe-value.cpp
@@ -0,0 +1,58 @@
+// REQUIRES: aarch64-registered-target
+// RUN: %clang_cc1 -triple aarch64 -x c++ -std=c++11 -DENABLE_ERRORS -verify %s
+// RUN: %clang_cc1 -triple aarch64 -x c++ -std=c++11 %s -emit-llvm -o -
+
+void test_type() {
+  char c;
+  c = __builtin_speculation_safe_value(c);
+
+  short s;
+  s = __builtin_speculation_safe_value(s);
+
+  int i;
+  i = __builtin_speculation_safe_value(i);
+
+  long l;
+  l = __builtin_speculation_safe_value(l);
+
+  long long ll;
+  ll = __builtin_speculation_safe_value(ll);
+
+  int *ip;
+  ip = __builtin_speculation_safe_value(ip);
+
+  int (*fp)(int, int);
+  fp = __builtin_speculation_safe_value(fp);
+
+  enum {e1, e2} e;
+  e = __builtin_speculation_safe_value(e);
+
+#ifdef enable_errors
+  float f;
+  f = __builtin_speculation_safe_value(f); // expected-error {{argument to speculation_safe_value builtin must be a pointer or integer ('float' invalid)}}
+
+  struct s { int a; } s;
+  s = __builtin_speculation_safe_value(s); // expected-error {{argument to speculation_safe_value builtin must be a pointer or integer ('struct s' invalid)}}
+
+  union u { int a; } u;
+  u = __builtin_speculation_safe_value(u); // expected-error {{argument to speculation_safe_value builtin must be a pointer or integer ('union u' invalid)}}
+
+  char __attribute__((vector_size(16))) v;
+  v = __builtin_speculation_safe_value(v); // expected-error {{argument to speculation_safe_value builtin must be a pointer or integer ('__attribute__((__vector_size__(16 * sizeof(char char' (vector of 16 'char' values) invalid)}}
+#endif
+}
+
+#ifdef ENABLE_ERRORS
+template
+T load(const T v) {
+  return __builtin_speculation_safe_value(v); // expected-error {{argument to speculation_safe_value builtin must be a pointer or integer ('float' invalid)}}
+}
+
+void test_templates() {
+  int i;
+  load(i);
+
+  float f;
+  load(f); // expected-note {{in instantiation of function template specialization 'load' requested here}}
+}
+#endif
Index: test/Sema/builtin-speculation-safe-value.c
===
--- /dev/null
+++ test/Sema/builtin-speculation-safe-value.c
@@ -0,0 +1,46 @@
+// REQUIRES: aarch64-registered-target
+// RUN: %clang_cc1 -triple aarch64 -DENABLE_ERRORS -verify %s
+// RUN: %clang_cc1 -triple aarch64 %s -emit-llvm -o -
+
+void test_type() {
+  char c;
+  c = __builtin_speculation_safe_value(c);
+
+  short s;
+  s = __builtin_speculation_safe_value(s);
+
+  int i;
+  i = __builtin_speculation_safe_value(i);
+
+  long l;
+  l = __builtin_speculation_safe_value(l);
+
+  long long ll;
+  ll = __builtin_speculation_safe_value(ll);
+
+  int *

[PATCH] D49074: [Analyzer] [WIP] Basic support for multiplication and division in the constraint manager

2018-07-09 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware created this revision.
baloghadamsoftware added reviewers: NoQ, dcoughlin.
Herald added subscribers: mikhail.ramalho, a.sidorin, szepet.
Herald added a reviewer: george.karpenkov.

Currently, the default (range-based) constrain manager supports symbolic 
expressions of the format "symbol + integer" or "symbol - integer" to compare 
them to another integer. However, multiplication and division is not supported 
yet.

An example where this lack of support causes false positives is the following:

  unsigned size = 32;
  int init(int *s);
  void assert(int);
  static void test(void)
  {
int val;
if (size>10 && size<=100){
   for (unsigned j = 0; jhttps://reviews.llvm.org/D49074

Files:
  include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
  lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  lib/StaticAnalyzer/Core/RangedConstraintManager.cpp
  test/Analysis/constraint_manager_scale.c

Index: test/Analysis/constraint_manager_scale.c
===
--- /dev/null
+++ test/Analysis/constraint_manager_scale.c
@@ -0,0 +1,175 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection,core.builtin -verify %s
+
+void clang_analyzer_eval(int);
+
+#define UINT_MAX (~0U)
+#define INT_MAX (UINT_MAX & (UINT_MAX >> 1))
+#define INT_MIN (UINT_MAX & ~(UINT_MAX >> 1))
+
+extern void __assert_fail (__const char *__assertion, __const char *__file,
+unsigned int __line, __const char *__function)
+ __attribute__ ((__noreturn__));
+#define assert(expr) \
+  ((expr)  ? (void)(0)  : __assert_fail (#expr, __FILE__, __LINE__, __func__))
+
+void add_ne(int x) {
+  assert(x + 1 != 3);
+  clang_analyzer_eval(x == 2); // expected-warning{{FALSE}}
+  clang_analyzer_eval(x == 3); // expected-warning{{UNKNOWN}}
+}
+
+void sub_ne(int x) {
+  assert(x - 1 != 1);
+  clang_analyzer_eval(x == 2); // expected-warning{{FALSE}}
+  clang_analyzer_eval(x == 1); // expected-warning{{UNKNOWN}}
+}
+
+void mult_ne(int x) {
+  assert(x * 2 != 4);
+  clang_analyzer_eval(x == 2); // expected-warning{{FALSE}}
+  clang_analyzer_eval(x == 4); // expected-warning{{UNKNOWN}}
+}
+
+void div_ne(int x) {
+  assert(x / 2 != 1);
+  clang_analyzer_eval(x == 2); // expected-warning{{FALSE}}
+  clang_analyzer_eval(x == 1); // expected-warning{{UNKNOWN}}
+}
+
+void add_eq(int x) {
+  assert(x + 1 == 3);
+  clang_analyzer_eval(x == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x == 3); // expected-warning{{FALSE}}
+}
+
+void sub_eq(int x) {
+  assert(x - 1 == 1);
+  clang_analyzer_eval(x == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x == 1); // expected-warning{{FALSE}}
+}
+
+void mult_eq(int x) {
+  assert(x * 2 == 4);
+  clang_analyzer_eval(x == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x == 4); // expected-warning{{FALSE}}
+}
+
+void div_eq(int x) {
+  assert(x / 2 == 1);
+  clang_analyzer_eval(x == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x == 1); // expected-warning{{FALSE}}
+}
+
+void add_lt(int x) {
+  assert(x < INT_MAX);
+  assert(x + 1 < 5);
+  clang_analyzer_eval(x < 4); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x < 3); // expected-warning{{UNKNOWN}}
+}
+
+void sub_lt(int x) {
+  assert(x - 1 < 3);
+  clang_analyzer_eval(x < 4); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x < 3); // expected-warning{{UNKNOWN}}
+}
+
+void mult_lt(int x) {
+  assert(x * 2 < 8);
+  clang_analyzer_eval(x < 4); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x < 2); // expected-warning{{UNKNOWN}}
+}
+
+void div_lt(int x) {
+  assert(x / 2 < 2);
+  clang_analyzer_eval(x < 4); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x < 2); // expected-warning{{UNKNOWN}}
+}
+
+void add_gt(int x) {
+  assert(x + 1 > 3);
+  clang_analyzer_eval(x > 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x > 3); // expected-warning{{UNKNOWN}}
+}
+
+void sub_gt(int x) {
+  assert(x >= 0);
+  assert(x - 1 > 1);
+  clang_analyzer_eval(x > 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x > 3); // expected-warning{{UNKNOWN}}
+}
+
+void mult_gt(int x) {
+  assert(x * 2 > 4);
+  clang_analyzer_eval(x > 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x > 3); // expected-warning{{UNKNOWN}}
+}
+
+void div_gt(int x) {
+  assert(x / 2 > 1);
+  clang_analyzer_eval(x > 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x > 3); // expected-warning{{UNKNOWN}}
+}
+
+void add_ge(int x) {
+  assert(x + 1 >= 3);
+  clang_analyzer_eval(x >= 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x >= 3); // expected-warning{{UNKNOWN}}
+}
+
+void sub_ge(int x) {
+  assert(x >= 0);
+  assert(x - 1 >= 1);
+  clang_analyzer_eval(x >= 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x >= 3); // expected-warning{{UNKNOWN}}
+}
+
+void mult_ge(int x) {
+  assert(x * 2 >= 4);
+  clang_analyzer_eval(x >= 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(x >= 3); // expected-warning{{UNKNOWN}}
+}
+
+void div_g

[PATCH] D49074: [Analyzer] [WIP] Basic support for multiplication and division in the constraint manager

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

All existing tests pass. I could not find the appropriate test file so I 
created a new one, but this is probably not the correct way.


https://reviews.llvm.org/D49074



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


[PATCH] D49074: [Analyzer] [WIP] Basic support for multiplication and division in the constraint manager

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

This seems to solve https://bugs.llvm.org/show_bug.cgi?id=32911.


https://reviews.llvm.org/D49074



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


[PATCH] D47632: [ASTImporter] Refactor Decl creation

2018-07-09 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 154582.
martong marked 6 inline comments as done.
martong added a comment.

Address review comments


Repository:
  rC Clang

https://reviews.llvm.org/D47632

Files:
  include/clang/AST/ASTImporter.h
  include/clang/AST/ASTStructuralEquivalence.h
  include/clang/AST/DeclBase.h
  lib/AST/ASTImporter.cpp
  lib/AST/ASTStructuralEquivalence.cpp
  lib/AST/ExternalASTMerger.cpp
  lib/Sema/SemaType.cpp
  unittests/AST/ASTImporterTest.cpp
  unittests/AST/StructuralEquivalenceTest.cpp

Index: unittests/AST/StructuralEquivalenceTest.cpp
===
--- unittests/AST/StructuralEquivalenceTest.cpp
+++ unittests/AST/StructuralEquivalenceTest.cpp
@@ -60,8 +60,9 @@
 
   bool testStructuralMatch(NamedDecl *D0, NamedDecl *D1) {
 llvm::DenseSet> NonEquivalentDecls;
-StructuralEquivalenceContext Ctx(D0->getASTContext(), D1->getASTContext(),
- NonEquivalentDecls, false, false);
+StructuralEquivalenceContext Ctx(
+D0->getASTContext(), D1->getASTContext(), NonEquivalentDecls,
+StructuralEquivalenceKind::Default, false, false);
 return Ctx.IsStructurallyEquivalent(D0, D1);
   }
 
Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -284,19 +284,32 @@
   // Buffer for the To context, must live in the test scope.
   std::string ToCode;
 
+  // Represents a "From" translation unit and holds an importer object which we
+  // use to import from this translation unit.
   struct TU {
 // Buffer for the context, must live in the test scope.
 std::string Code;
 std::string FileName;
 std::unique_ptr Unit;
 TranslationUnitDecl *TUDecl = nullptr;
+std::unique_ptr Importer;
 TU(StringRef Code, StringRef FileName, ArgVector Args)
 : Code(Code), FileName(FileName),
   Unit(tooling::buildASTFromCodeWithArgs(this->Code, Args,
  this->FileName)),
   TUDecl(Unit->getASTContext().getTranslationUnitDecl()) {
   Unit->enableSourceFileDiagnostics();
 }
+
+Decl *import(ASTUnit *ToAST, Decl *FromDecl) {
+  assert(ToAST);
+  if (!Importer) {
+Importer.reset(new ASTImporter(
+ToAST->getASTContext(), ToAST->getFileManager(),
+Unit->getASTContext(), Unit->getFileManager(), false));
+  }
+  return Importer->Import(FromDecl);
+}
   };
 
   // We may have several From contexts and related translation units. In each
@@ -329,14 +342,10 @@
 ToAST = tooling::buildASTFromCodeWithArgs(ToCode, ToArgs, OutputFileName);
 ToAST->enableSourceFileDiagnostics();
 
-ASTContext &FromCtx = FromTU.Unit->getASTContext(),
-   &ToCtx = ToAST->getASTContext();
+ASTContext &FromCtx = FromTU.Unit->getASTContext();
 
 createVirtualFileIfNeeded(ToAST.get(), InputFileName, FromTU.Code);
 
-ASTImporter Importer(ToCtx, ToAST->getFileManager(), FromCtx,
- FromTU.Unit->getFileManager(), false);
-
 IdentifierInfo *ImportedII = &FromCtx.Idents.get(Identifier);
 assert(ImportedII && "Declaration with the given identifier "
  "should be specified in test!");
@@ -347,7 +356,8 @@
 
 assert(FoundDecls.size() == 1);
 
-Decl *Imported = Importer.Import(FoundDecls.front());
+Decl *Imported = FromTU.import(ToAST.get(), FoundDecls.front());
+
 assert(Imported);
 return std::make_tuple(*FoundDecls.begin(), Imported);
   }
@@ -401,11 +411,7 @@
 assert(It != FromTUs.end());
 createVirtualFileIfNeeded(ToAST.get(), It->FileName, It->Code);
 
-ASTContext &FromCtx = From->getASTContext(),
-   &ToCtx = ToAST->getASTContext();
-ASTImporter Importer(ToCtx, ToAST->getFileManager(), FromCtx,
- FromCtx.getSourceManager().getFileManager(), false);
-return Importer.Import(From);
+return It->import(ToAST.get(), From);
   }
 
   ~ASTImporterTestBase() {
@@ -1089,8 +1095,7 @@
   EXPECT_EQ(ToTemplated1, ToTemplated);
 }
 
-TEST_P(ASTImporterTestBase,
-   DISABLED_ImportOfTemplatedDeclOfFunctionTemplateDecl) {
+TEST_P(ASTImporterTestBase, ImportOfTemplatedDeclOfFunctionTemplateDecl) {
   Decl *FromTU = getTuDecl("template void f(){}", Lang_CXX);
   auto From = FirstDeclMatcher().match(
   FromTU, functionTemplateDecl());
@@ -1166,7 +1171,7 @@
   ASSERT_EQ(ToTemplated1, ToTemplated);
 }
 
-TEST_P(ASTImporterTestBase, DISABLED_ImportFunctionWithBackReferringParameter) {
+TEST_P(ASTImporterTestBase, ImportFunctionWithBackReferringParameter) {
   Decl *From, *To;
   std::tie(From, To) = getImportedDecl(
   R"(
@@ -1711,6 +1716,49 @@
   EXPECT_NE(To0->getCanonicalDecl(), To1->getCanonicalDecl());
 }
 
+TEST_P(ASTImporterTestBase, ImportDoesUpdateUsedFlag) {
+  auto Pattern = varDecl(hasName("

[PATCH] D47632: [ASTImporter] Refactor Decl creation

2018-07-09 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: lib/AST/ASTImporter.cpp:161
+  ToD->IdentifierNamespace = FromD->IdentifierNamespace;
+  if (FromD->hasAttrs())
+for (const Attr *FromAttr : FromD->getAttrs())

a_sidorin wrote:
> Should we move the below operations into `updateAttrAndFlags()` and use it 
> instead?
`updateAttrAndFlags` should handle only those properties of a `Decl` which can 
change during a subsequent import. Such as `isUsed` and `isReferenced`.

There are other properties which cannot change, e.g. `isImplicit`.
Similarly, `Decl::hasAttrs()` refers to the syntactic attributes of a 
declaration, e.g. `[[noreturn]]`, which will not change during a subsequent 
import.

Perhaps the `Attr` syllable is confusing in the `updateAttrAndFlags()` 
function. Thus I suggest a new name: `updateFlags()`.



Comment at: lib/AST/ASTImporter.cpp:1587
   StructuralEquivalenceContext Ctx(
   Importer.getFromContext(), Importer.getToContext(),
+  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),

a_sidorin wrote:
> (Thinking out loud) We need to introduce some method to return 
> `StructuralEquivalenceContext` in ASTImporter. But this is an item for a 
> separate patch, not this one.
Yes, I agree. Or perhaps we should have a common `isStructuralMatch(Decl*, 
Decl*)` function which is called by the other overloads of `isStructuralMatch`.



Comment at: lib/AST/ASTImporter.cpp:1890
   TypedefNameDecl *ToTypedef;
-  if (IsAlias)
-ToTypedef = TypeAliasDecl::Create(Importer.getToContext(), DC, StartL, Loc,
-  Name.getAsIdentifierInfo(), TInfo);
-  else
-ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC,
-StartL, Loc,
-Name.getAsIdentifierInfo(),
-TInfo);
+  if (IsAlias && GetImportedOrCreateDecl(
+ ToTypedef, D, Importer.getToContext(), DC, StartL, Loc,

a_sidorin wrote:
> This is not strictly equivalent to the source condition. If 
> GetImportedOrCreateDecl returns false, we'll fall to the `else` branch, and 
> it doesn't seem correct to me.
Thanks, this is a very good catch. Fixed it.



Comment at: lib/AST/ASTImporter.cpp:6905
 Decl *ToD = Pos->second;
+// FIXME: remove this call from this function
 ASTNodeImporter(*this).ImportDefinitionIfNeeded(FromD, ToD);

balazske wrote:
> I think this comment is not needed (or with other text). There is a case when 
> `GetAlreadyImportedOrNull` is called during import of a Decl that is already 
> imported but its definition is not yet completely imported. If this call is 
> here we have after `GetAlreadyImportedOrNull` a Decl with complete 
> definition. (Name of the function is still bad: It does not only "get" but 
> makes update too. The `ImportDefinitionIfNeeded` call can be moved into the 
> decl create function?)
Yes, I agree. Changed the text of the code, because I believe that we should do 
the import of the definition on the call side of `GetAlreadyImportedOrNull` for 
the case where it is needed (in `ImportDeclParts`).


Repository:
  rC Clang

https://reviews.llvm.org/D47632



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


[PATCH] D47817: [sanitizer_common] Fix using libtirpc on Linux

2018-07-09 Thread Michał Górny via Phabricator via cfe-commits
mgorny added a comment.

In https://reviews.llvm.org/D47817#1155637, @Lekensteyn wrote:

> Hi, thank you for the patch. First a disclaimer, I am not familiar with this 
> RPC API at all.


Me neither. I'm only familiar with this particular issue because it's what 
we're hitting a lot recently.

> This would be the first user of pkg-config here. I am not sure if this would 
> be the best fix. Usually you cannot (easily) recompile libc and override it, 
> but for external libs such as libtirpc this should be more doable (I think).

I don't think libtirpc's include path is expected to be predictable by design. 
I think it's something distro maintainers have to choose to avoid collision 
with headers that (used to be) installed by glibc. In any case, I can't think 
of a better solution than pkg-config here (libtirpc doesn't come with CMake 
modules).

> I'm not comfortable with adding the tirpc include path to the default include 
> path and stripping `-nodefaultlibs` either, would this approach work for 
> cross-compilation?

I can't see why not — I suppose most of cross-compilation environments already 
redefine pkg-config paths appropriately. Even if it wouldn't, this shouldn't 
cause a regression because the 'default' case (RPC headers sraight in default 
paths) is not affected, and libtirpc case never could have worked.

As for `no-defaultlibs`, that is only stripped for the purpose of 
`check_include_file` and is afterwards restored. I can't think of a reason it 
would fail with stripping, and it certainly fails for me if it's not stripped.


Repository:
  rCRT Compiler Runtime

https://reviews.llvm.org/D47817



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


[PATCH] D49075: [NEON] Define fp16 vld and vst intrinsics conditionally

2018-07-09 Thread Ivan Kosarev via Phabricator via cfe-commits
kosarev created this revision.
kosarev added reviewers: SjoerdMeijer, jgreenhalgh, rengolin.
kosarev added a project: clang.
Herald added a reviewer: javed.absar.

This patch fixes definitions of vld and vst NEON intrinsics so that we only 
define them if half-precision arithmetic is supported on the target platform, 
as prescribed in ACLE 2.0.


https://reviews.llvm.org/D49075

Files:
  include/clang/Basic/arm_neon.td
  test/CodeGen/arm-neon-vld.c
  test/CodeGen/arm-neon-vst.c

Index: test/CodeGen/arm-neon-vst.c
===
--- test/CodeGen/arm-neon-vst.c
+++ test/CodeGen/arm-neon-vst.c
@@ -2,8 +2,8 @@
 // RUN: -S -disable-O0-optnone -emit-llvm -o - %s | opt -S -mem2reg | \
 // RUN: FileCheck -check-prefixes=CHECK,CHECK-A64 %s
 // RUN: %clang_cc1 -triple armv8-none-linux-gnueabi -target-feature +neon \
-// RUN: -S -disable-O0-optnone -emit-llvm -o - %s | opt -S -mem2reg | \
-// RUN: FileCheck -check-prefixes=CHECK,CHECK-A32 %s
+// RUN: -target-feature +fp16 -S -disable-O0-optnone -emit-llvm -o - %s | \
+// RUN: opt -S -mem2reg | FileCheck -check-prefixes=CHECK,CHECK-A32 %s
 
 #include 
 
Index: test/CodeGen/arm-neon-vld.c
===
--- test/CodeGen/arm-neon-vld.c
+++ test/CodeGen/arm-neon-vld.c
@@ -2,8 +2,8 @@
 // RUN: -S -disable-O0-optnone -emit-llvm -o - %s | opt -S -mem2reg | \
 // RUN: FileCheck -check-prefixes=CHECK,CHECK-A64 %s
 // RUN: %clang_cc1 -triple armv8-none-linux-gnueabi -target-feature +neon \
-// RUN: -S -disable-O0-optnone -emit-llvm -o - %s | opt -S -mem2reg | \
-// RUN: FileCheck -check-prefixes=CHECK,CHECK-A32 %s
+// RUN: -target-feature +fp16 -S -disable-O0-optnone -emit-llvm -o - %s | \
+// RUN: opt -S -mem2reg | FileCheck -check-prefixes=CHECK,CHECK-A32 %s
 
 #include 
 
Index: include/clang/Basic/arm_neon.td
===
--- include/clang/Basic/arm_neon.td
+++ include/clang/Basic/arm_neon.td
@@ -337,48 +337,78 @@
 
 // E.3.14 Loads and stores of a single vector
 def VLD1  : WInst<"vld1", "dc",
-  "QUcQUsQUiQUlQcQsQiQlQhQfQPcQPsUcUsUiUlcsilhfPcPs">;
+  "QUcQUsQUiQUlQcQsQiQlQfQPcQPsUcUsUiUlcsilfPcPs">;
 def VLD1_X2   : WInst<"vld1_x2", "2c",
-  "cfhilsUcUiUlUsQcQfQhQiQlQsQUcQUiQUlQUsPcPsQPcQPs">;
+  "cfilsUcUiUlUsQcQfQiQlQsQUcQUiQUlQUsPcPsQPcQPs">;
 def VLD1_X3   : WInst<"vld1_x3", "3c",
-  "cfhilsUcUiUlUsQcQfQhQiQlQsQUcQUiQUlQUsPcPsQPcQPs">;
+  "cfilsUcUiUlUsQcQfQiQlQsQUcQUiQUlQUsPcPsQPcQPs">;
 def VLD1_X4   : WInst<"vld1_x4", "4c",
-  "cfhilsUcUiUlUsQcQfQhQiQlQsQUcQUiQUlQUsPcPsQPcQPs">;
+  "cfilsUcUiUlUsQcQfQiQlQsQUcQUiQUlQUsPcPsQPcQPs">;
 def VLD1_LANE : WInst<"vld1_lane", "dcdi",
-  "QUcQUsQUiQUlQcQsQiQlQhQfQPcQPsUcUsUiUlcsilhfPcPs">;
+  "QUcQUsQUiQUlQcQsQiQlQfQPcQPsUcUsUiUlcsilfPcPs">;
 def VLD1_DUP  : WInst<"vld1_dup", "dc",
-  "QUcQUsQUiQUlQcQsQiQlQhQfQPcQPsUcUsUiUlcsilhfPcPs">;
+  "QUcQUsQUiQUlQcQsQiQlQfQPcQPsUcUsUiUlcsilfPcPs">;
 def VST1  : WInst<"vst1", "vpd",
-  "QUcQUsQUiQUlQcQsQiQlQhQfQPcQPsUcUsUiUlcsilhfPcPs">;
+  "QUcQUsQUiQUlQcQsQiQlQfQPcQPsUcUsUiUlcsilfPcPs">;
 def VST1_X2   : WInst<"vst1_x2", "vp2",
-  "cfhilsUcUiUlUsQcQfQhQiQlQsQUcQUiQUlQUsPcPsQPcQPs">;
+  "cfilsUcUiUlUsQcQfQiQlQsQUcQUiQUlQUsPcPsQPcQPs">;
 def VST1_X3   : WInst<"vst1_x3", "vp3",
-  "cfhilsUcUiUlUsQcQfQhQiQlQsQUcQUiQUlQUsPcPsQPcQPs">;
+  "cfilsUcUiUlUsQcQfQiQlQsQUcQUiQUlQUsPcPsQPcQPs">;
 def VST1_X4   : WInst<"vst1_x4", "vp4",
-  "cfhilsUcUiUlUsQcQfQhQiQlQsQUcQUiQUlQUsPcPsQPcQPs">;
+  "cfilsUcUiUlUsQcQfQiQlQsQUcQUiQUlQUsPcPsQPcQPs">;
 def VST1_LANE : WInst<"vst1_lane", "vpdi",
-  "QUcQUsQUiQUlQcQsQiQlQhQfQPcQPsUcUsUiUlcsilhfPcPs">;
+  "QUcQUsQUiQUlQcQsQiQlQfQPcQPsUcUsUiUlcsilfPcPs">;
+let ArchGuard = "(__ARM_FP & 2)" in {
+def VLD1_F16  : WInst<"vld1", "dc", "hQh">;
+def VLD1_X2_F16   : WInst<"vld1_x2", "2c", "hQh">;
+def VLD1_X3_F16   : WInst<"vld1_x3", "3c", "hQh">;
+def VLD1_X4_F16   : WInst<"vld1_x4", "4c", "hQh">;
+def VLD1_LANE_F16 : WInst<"vld1_lane", "dcdi", "hQh">;
+def VLD1_DUP_F16  : WInst<"vld1_dup", "dc", "hQh">;
+def VST1_F16  : WInst<"vst1", "vpd", "hQh">;
+def VST1_X2_F16   : WInst<"vst1_x2", "vp2", "hQh">;
+def VST1_X3_F16   : WInst<"vst1_x3", "vp3", "hQh">;
+def VST1_X4_F16   : WInst<"vst1_x4", "vp4", "hQh">;
+def VST1_LANE_F16 : WInst<"vst1_lane", "vpdi", "hQh">;
+}
 
 ///

[PATCH] D48829: [NEON] Fix support for vrndi_f32(), vrndiq_f32() and vrndns_f32() intrinsics

2018-07-09 Thread Ivan Kosarev via Phabricator via cfe-commits
kosarev added a comment.

Ping.


https://reviews.llvm.org/D48829



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


[PATCH] D45383: Limit types of builtins that can be redeclared.

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

I'm curious why that file is declaring the builtin like that?  The declaration 
doesn't seem like it is ever useful, builtins are available without any 
includes/etc as far back as I could go on all 3 compilers that I validated 
against.

Additionally, I believe that the declaration is actually prohibited by the 
standard, since it is declaring an identifier that is reserved for the 
implementation.

Is this a situation where the target project cannot be corrected? That line 
simply needs to be removed as far as I can tell.


Repository:
  rL LLVM

https://reviews.llvm.org/D45383



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


[PATCH] D49077: [clangd] Remove JSON library in favor of llvm/Support/JSON

2018-07-09 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: ilya-biryukov.
Herald added subscribers: cfe-commits, omtcyfz, jkorous, MaskRay, ioeric, 
mgorny.

The library has graduated from clangd to llvm/Support.
This is a mechanical change to move to the new API and remove the old one.

Main API changes:

- namespace clang::clangd::json --> llvm::json
- json::Expr --> json::Value
- Expr::asString() etc --> Value::getAsString() etc
- unsigned longs need a cast (due to r336541 adding lossless integer support)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49077

Files:
  clangd/CMakeLists.txt
  clangd/ClangdLSPServer.cpp
  clangd/CodeComplete.cpp
  clangd/JSONExpr.cpp
  clangd/JSONExpr.h
  clangd/JSONRPCDispatcher.cpp
  clangd/JSONRPCDispatcher.h
  clangd/Protocol.cpp
  clangd/Protocol.h
  clangd/ProtocolHandlers.cpp
  clangd/Trace.cpp
  clangd/Trace.h
  unittests/clangd/CMakeLists.txt
  unittests/clangd/JSONExprTests.cpp

Index: unittests/clangd/JSONExprTests.cpp
===
--- unittests/clangd/JSONExprTests.cpp
+++ /dev/null
@@ -1,293 +0,0 @@
-//===-- JSONExprTests.cpp - JSON expression unit tests --*- C++ -*-===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===--===//
-
-#include "JSONExpr.h"
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-
-namespace clang {
-namespace clangd {
-namespace json {
-
-namespace {
-
-std::string s(const Expr &E) { return llvm::formatv("{0}", E).str(); }
-std::string sp(const Expr &E) { return llvm::formatv("{0:2}", E).str(); }
-
-TEST(JSONExprTests, Types) {
-  EXPECT_EQ("true", s(true));
-  EXPECT_EQ("null", s(nullptr));
-  EXPECT_EQ("2.5", s(2.5));
-  EXPECT_EQ(R"("foo")", s("foo"));
-  EXPECT_EQ("[1,2,3]", s({1, 2, 3}));
-  EXPECT_EQ(R"({"x":10,"y":20})", s(obj{{"x", 10}, {"y", 20}}));
-}
-
-TEST(JSONExprTests, Constructors) {
-  // Lots of edge cases around empty and singleton init lists.
-  EXPECT_EQ("[[[3]]]", s({{{3}}}));
-  EXPECT_EQ("[[[]]]", s({{{}}}));
-  EXPECT_EQ("[[{}]]", s({{obj{}}}));
-  EXPECT_EQ(R"({"A":{"B":{}}})", s(obj{{"A", obj{{"B", obj{}));
-  EXPECT_EQ(R"({"A":{"B":{"X":"Y"}}})",
-s(obj{{"A", obj{{"B", obj{{"X", "Y"}}));
-  EXPECT_EQ("null", s(llvm::Optional()));
-  EXPECT_EQ("2.5", s(llvm::Optional(2.5)));
-}
-
-TEST(JSONExprTests, StringOwnership) {
-  char X[] = "Hello";
-  Expr Alias = static_cast(X);
-  X[1] = 'a';
-  EXPECT_EQ(R"("Hallo")", s(Alias));
-
-  std::string Y = "Hello";
-  Expr Copy = Y;
-  Y[1] = 'a';
-  EXPECT_EQ(R"("Hello")", s(Copy));
-}
-
-TEST(JSONExprTests, CanonicalOutput) {
-  // Objects are sorted (but arrays aren't)!
-  EXPECT_EQ(R"({"a":1,"b":2,"c":3})", s(obj{{"a", 1}, {"c", 3}, {"b", 2}}));
-  EXPECT_EQ(R"(["a","c","b"])", s({"a", "c", "b"}));
-  EXPECT_EQ("3", s(3.0));
-}
-
-TEST(JSONExprTests, Escaping) {
-  std::string test = {
-  0,// Strings may contain nulls.
-  '\b',   '\f', // Have mnemonics, but we escape numerically.
-  '\r',   '\n',   '\t', // Escaped with mnemonics.
-  'S','\"',   '\\', // Printable ASCII characters.
-  '\x7f',   // Delete is not escaped.
-  '\xce', '\x94',   // Non-ASCII UTF-8 is not escaped.
-  };
-
-  std::string teststring = R"("\u\u0008\u000c\r\n\tS\"\\)"
-   "\x7f\xCE\x94\"";
-
-  EXPECT_EQ(teststring, s(test));
-
-  EXPECT_EQ(R"({"object keys are\nescaped":true})",
-s(obj{{"object keys are\nescaped", true}}));
-}
-
-TEST(JSONExprTests, PrettyPrinting) {
-  const char str[] = R"({
-  "empty_array": [],
-  "empty_object": {},
-  "full_array": [
-1,
-null
-  ],
-  "full_object": {
-"nested_array": [
-  {
-"property": "value"
-  }
-]
-  }
-})";
-
-  EXPECT_EQ(str, sp(obj{
- {"empty_object", obj{}},
- {"empty_array", {}},
- {"full_array", {1, nullptr}},
- {"full_object",
-  obj{
-  {"nested_array",
-   {obj{
-   {"property", "value"},
-   }}},
-  }},
- }));
-}
-
-TEST(JSONTest, Parse) {
-  auto Compare = [](llvm::StringRef S, Expr Expected) {
-if (auto E = parse(S)) {
-  // Compare both string forms and with operator==, in case we have bugs.
-  EXPECT_EQ(*E, Expected);
-  EXPECT_EQ(sp(*E), sp(Expected));
-} else {
-  handleAllErrors(E.takeError(), [S](const llvm::ErrorInfoBase &E) {
-FAIL() << "Failed to parse JSON >>> " << S << " <<<: " << E.message();
-  });
-}
-  };
-
-  Compare(R"(true)", true);
-  Compare(R"(false)", false);
-  Compare(R"(null)", nullpt

[PATCH] D47817: [sanitizer_common] Fix using libtirpc on Linux

2018-07-09 Thread Peter Wu via Phabricator via cfe-commits
Lekensteyn added a comment.

In https://reviews.llvm.org/D47817#1155717, @mgorny wrote:

> > This would be the first user of pkg-config here. I am not sure if this 
> > would be the best fix. Usually you cannot (easily) recompile libc and 
> > override it, but for external libs such as libtirpc this should be more 
> > doable (I think).
>
> I don't think libtirpc's include path is expected to be predictable by 
> design. I think it's something distro maintainers have to choose to avoid 
> collision with headers that (used to be) installed by glibc. In any case, I 
> can't think of a better solution than pkg-config here (libtirpc doesn't come 
> with CMake modules).


On Arch (libtirpc-1.0.3-2), Debian (libtirpc-dev 0.2.5-1.2 in sid), Gentoo 
(libtirpc-1.0.3), the include files happen to be installed in 
/usr/include/libtirpc, so it seems pretty consistent. So you could consider 
writing a `cmake/Modules/FindLibtirpc.cmake` module that looks like:

  # sets Libtirpc_FOUND Libtirpc_INCLUDE_DIRS
  
  find_path(Libtirpc_INCLUDE_DIR
NAMES rpc/xdr.h
PATH_SUFFIXES tirpc
  )
  include(FindPackageHandleStandardArgs)
  find_package_handle_standard_args(Libtirpc REQUIRED_VARS Libtirpc_INCLUDE_DIR)
  if(Libtirpc_FOUND)
set(Libtirpc_INCLUDE_DIRS ${Libtirpc_INCLUDE_DIR})
  endif()

then you can use `find_package(Libtirpc)` without depending on `pkg-config`.

> libtirpc case never could have worked.

The reason for that is probably because of 
lib/sanitizer_common/sanitizer_platform.h saying:

  // Assume obsolete RPC headers are available by default
  #if !defined(HAVE_RPC_XDR_H) && !defined(HAVE_TIRPC_RPC_XDR_H)
  # define HAVE_RPC_XDR_H (SANITIZER_LINUX && !SANITIZER_ANDROID)
  # define HAVE_TIRPC_RPC_XDR_H 0
  #endif

That should probably be addressed too.


Repository:
  rCRT Compiler Runtime

https://reviews.llvm.org/D47817



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


[PATCH] D49077: [clangd] Remove JSON library in favor of llvm/Support/JSON

2018-07-09 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:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49077



___
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-09 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri updated this revision to Diff 154591.
lebedev.ri retitled this revision from "[private][clang] Implicit Cast 
Sanitizer - integer truncation  - clang part" to "[clang][ubsan] Implicit Cast 
Sanitizer - integer truncation  - clang part".
lebedev.ri edited the summary of this revision.
lebedev.ri added reviewers: rjmccall, rsmith, samsonov, pcc, vsk, eugenis, 
efriedma, kcc.
lebedev.ri added a project: Sanitizers.
lebedev.ri added subscribers: cfe-commits, mclow.lists, milianw, dvyukov, 
ygribov, danielaustin, filcab, dtzWill, RKSimon, aaron.ballman, Sanitizers.
lebedev.ri added a comment.

C and C++ are interesting languages. They are statically typed, but weakly.
The implicit conversions are allowed. This is nice, allows to write code
while balancing between getting drowned in everything being convertible,
and nothing being convertible. As usual, this comes with a price:

  unsigned char store = 0;
  
  bool consume(unsigned int val);
  
  void test(unsigned long val) {
if (consume(val)) {
  // the 'val' is `unsigned long`, but `consume()` takes `unsigned int`.
  // If their bit widths are different on this platform, the implicit
  // truncation happens. And if that `unsigned long` had a value bigger
  // than UINT_MAX, then you may or may not have a bug.
  
  // Similarly, integer addition happens on `int`s, so `store` will
  // be promoted to an `int`, the sum calculated (0+768=768),
  // and the result demoted to `unsigned char`, and stored to `store`.
  // In this case, the `store` will still be 0. Again, not always intended.
  store = store + 768; // before addition, 'store' was promoted to int.
}
  
// But yes, sometimes this is intentional.
// You can either make the cast explicit
(void)consume((unsigned int)val);
// or mask the value so no bits will be *implicitly* lost.
(void)consume((~((unsigned int)0)) & val);
  }

Yes, there is a `-Wconversion`` diagnostic group, but first, it is kinda
noisy, since it warns on everything (unlike sanitizers, warning on an
actual issues), and second, there are cases where it does **not** warn.
So a Sanitizer is needed. I don't have any motivational numbers, but i know
i had this kind of problem 10-20 times, and it was never easy to track down.

The logic to detect whether an truncation has happened is pretty simple
if you think about it - https://godbolt.org/g/NEzXbb - basically, just
extend (using the new, not original!, signedness) the 'truncated' value
back to it's original width, and equality-compare it with the original value.

The most non-trivial thing here is the logic to detect whether this
`ImplicitCastExpr` AST node is **actually** an implicit cast, //or// part of
an explicit cast. Because the explicit casts are modeled as an outer
`ExplicitCastExpr` with some `ImplicitCastExpr`'s as **direct** children.
https://godbolt.org/g/eE1GkJ

It would //seem//, we can just check that the current `ImplicitCastExpr`
we are processing either has no `CastExpr` parents, or all of them are
`ImplicitCastExpr`.

As you may have noted, this isn't just named 
`-fsanitize=implicit-integer-truncation`.
There are potentially some more implicit casts to be warned about.
Namely, implicit casts that result in sign change; implicit cast
between different floating point types, or between fp and an integer,
when again, that conversion is lossy.

I suspect, there may be some false-negatives, cases yet to be handled.

This is a clang part.
The compiler-rt part is https://reviews.llvm.org/D48959.

Fixes PR21530 , PR37552 
, PR35409 
.
Partially fixes PR9821 .
Fixes https://github.com/google/sanitizers/issues/940.


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-l

[clang-tools-extra] r336549 - [clangd] Remove JSON library in favor of llvm/Support/JSON

2018-07-09 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Mon Jul  9 07:25:59 2018
New Revision: 336549

URL: http://llvm.org/viewvc/llvm-project?rev=336549&view=rev
Log:
[clangd] Remove JSON library in favor of llvm/Support/JSON

Summary:
The library has graduated from clangd to llvm/Support.
This is a mechanical change to move to the new API and remove the old one.

Main API changes:
 - namespace clang::clangd::json --> llvm::json
 - json::Expr --> json::Value
 - Expr::asString() etc --> Value::getAsString() etc
 - unsigned longs need a cast (due to r336541 adding lossless integer support)

Reviewers: ilya-biryukov

Subscribers: mgorny, ioeric, MaskRay, jkorous, omtcyfz, cfe-commits

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

Removed:
clang-tools-extra/trunk/clangd/JSONExpr.cpp
clang-tools-extra/trunk/clangd/JSONExpr.h
clang-tools-extra/trunk/unittests/clangd/JSONExprTests.cpp
Modified:
clang-tools-extra/trunk/clangd/CMakeLists.txt
clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
clang-tools-extra/trunk/clangd/CodeComplete.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/Protocol.h
clang-tools-extra/trunk/clangd/ProtocolHandlers.cpp
clang-tools-extra/trunk/clangd/Trace.cpp
clang-tools-extra/trunk/clangd/Trace.h
clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt

Modified: clang-tools-extra/trunk/clangd/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CMakeLists.txt?rev=336549&r1=336548&r2=336549&view=diff
==
--- clang-tools-extra/trunk/clangd/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clangd/CMakeLists.txt Mon Jul  9 07:25:59 2018
@@ -23,7 +23,6 @@ add_clang_library(clangDaemon
   FuzzyMatch.cpp
   GlobalCompilationDatabase.cpp
   Headers.cpp
-  JSONExpr.cpp
   JSONRPCDispatcher.cpp
   Logger.cpp
   Protocol.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp?rev=336549&r1=336548&r2=336549&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp Mon Jul  9 07:25:59 2018
@@ -18,6 +18,7 @@
 
 using namespace clang::clangd;
 using namespace clang;
+using namespace llvm;
 
 namespace {
 
@@ -87,25 +88,25 @@ void ClangdLSPServer::onInitialize(Initi
 }
   }
 
-  reply(json::obj{
+  reply(json::Object{
   {{"capabilities",
-json::obj{
+json::Object{
 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
 {"documentFormattingProvider", true},
 {"documentRangeFormattingProvider", true},
 {"documentOnTypeFormattingProvider",
- json::obj{
+ json::Object{
  {"firstTriggerCharacter", "}"},
  {"moreTriggerCharacter", {}},
  }},
 {"codeActionProvider", true},
 {"completionProvider",
- json::obj{
+ json::Object{
  {"resolveProvider", false},
  {"triggerCharacters", {".", ">", ":"}},
  }},
 {"signatureHelpProvider",
- json::obj{
+ json::Object{
  {"triggerCharacters", {"(", ","}},
  }},
 {"definitionProvider", true},
@@ -115,7 +116,7 @@ void ClangdLSPServer::onInitialize(Initi
 {"documentSymbolProvider", true},
 {"workspaceSymbolProvider", true},
 {"executeCommandProvider",
- json::obj{
+ json::Object{
  {"commands", 
{ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
  }},
 );
@@ -212,7 +213,7 @@ void ClangdLSPServer::onWorkspaceSymbol(
 for (auto &Sym : *Items)
   Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
 
-reply(json::ary(*Items));
+reply(json::Array(*Items));
   });
 }
 
@@ -258,7 +259,7 @@ void ClangdLSPServer::onDocumentOnTypeFo
 
   auto ReplacementsOrError = Server.formatOnType(*Code, File, Params.position);
   if (ReplacementsOrError)
-reply(json::ary(replacementsToEdits(*Code, ReplacementsOrError.get(;
+reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get(;
   else
 replyError(ErrorCode::UnknownErrorCode,
llvm::toString(ReplacementsOrError.takeError()));
@@ -274,7 +275,7 @@ void ClangdLSPServer::onDocumentRangeFor
 
   auto ReplacementsOrError = Server.formatRange(*Code, File, Params.range);
   if (ReplacementsOrError)
-reply(json::ary(replacementsToEdits(*Code, ReplacementsOrError.get(;
+reply(json::Array(replacementsToEdits(*C

[PATCH] D49077: [clangd] Remove JSON library in favor of llvm/Support/JSON

2018-07-09 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE336549: [clangd] Remove JSON library in favor of 
llvm/Support/JSON (authored by sammccall, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D49077?vs=154597&id=154600#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49077

Files:
  clangd/CMakeLists.txt
  clangd/ClangdLSPServer.cpp
  clangd/CodeComplete.cpp
  clangd/JSONExpr.cpp
  clangd/JSONExpr.h
  clangd/JSONRPCDispatcher.cpp
  clangd/JSONRPCDispatcher.h
  clangd/Protocol.cpp
  clangd/Protocol.h
  clangd/ProtocolHandlers.cpp
  clangd/Trace.cpp
  clangd/Trace.h
  unittests/clangd/CMakeLists.txt
  unittests/clangd/JSONExprTests.cpp

Index: unittests/clangd/CMakeLists.txt
===
--- unittests/clangd/CMakeLists.txt
+++ unittests/clangd/CMakeLists.txt
@@ -23,7 +23,6 @@
   GlobalCompilationDatabaseTests.cpp
   HeadersTests.cpp
   IndexTests.cpp
-  JSONExprTests.cpp
   QualityTests.cpp
   SourceCodeTests.cpp
   SymbolCollectorTests.cpp
Index: clangd/JSONRPCDispatcher.cpp
===
--- clangd/JSONRPCDispatcher.cpp
+++ clangd/JSONRPCDispatcher.cpp
@@ -8,29 +8,30 @@
 //===--===//
 
 #include "JSONRPCDispatcher.h"
-#include "JSONExpr.h"
 #include "ProtocolHandlers.h"
 #include "Trace.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/Chrono.h"
 #include "llvm/Support/Errno.h"
+#include "llvm/Support/JSON.h"
 #include "llvm/Support/SourceMgr.h"
 #include 
 
+using namespace llvm;
 using namespace clang;
 using namespace clangd;
 
 namespace {
-static Key RequestID;
+static Key RequestID;
 static Key RequestOut;
 
 // When tracing, we trace a request and attach the repsonse in reply().
 // Because the Span isn't available, we find the current request using Context.
 class RequestSpan {
-  RequestSpan(json::obj *Args) : Args(Args) {}
+  RequestSpan(llvm::json::Object *Args) : Args(Args) {}
   std::mutex Mu;
-  json::obj *Args;
+  llvm::json::Object *Args;
   static Key> RSKey;
 
 public:
@@ -41,7 +42,7 @@
   }
 
   // If there's an enclosing request and the tracer is interested, calls \p F
-  // with a json::obj where request info can be added.
+  // with a json::Object where request info can be added.
   template  static void attach(Func &&F) {
 auto *RequestArgs = Context::current().get(RSKey);
 if (!RequestArgs || !*RequestArgs || !(*RequestArgs)->Args)
@@ -53,7 +54,7 @@
 Key> RequestSpan::RSKey;
 } // namespace
 
-void JSONOutput::writeMessage(const json::Expr &Message) {
+void JSONOutput::writeMessage(const json::Value &Message) {
   std::string S;
   llvm::raw_string_ostream OS(S);
   if (Pretty)
@@ -86,50 +87,50 @@
   InputMirror->flush();
 }
 
-void clangd::reply(json::Expr &&Result) {
+void clangd::reply(json::Value &&Result) {
   auto ID = Context::current().get(RequestID);
   if (!ID) {
 log("Attempted to reply to a notification!");
 return;
   }
-  RequestSpan::attach([&](json::obj &Args) { Args["Reply"] = Result; });
+  RequestSpan::attach([&](json::Object &Args) { Args["Reply"] = Result; });
   Context::current()
   .getExisting(RequestOut)
-  ->writeMessage(json::obj{
+  ->writeMessage(json::Object{
   {"jsonrpc", "2.0"},
   {"id", *ID},
   {"result", std::move(Result)},
   });
 }
 
 void clangd::replyError(ErrorCode code, const llvm::StringRef &Message) {
   log("Error " + Twine(static_cast(code)) + ": " + Message);
-  RequestSpan::attach([&](json::obj &Args) {
-Args["Error"] =
-json::obj{{"code", static_cast(code)}, {"message", Message.str()}};
+  RequestSpan::attach([&](json::Object &Args) {
+Args["Error"] = json::Object{{"code", static_cast(code)},
+ {"message", Message.str()}};
   });
 
   if (auto ID = Context::current().get(RequestID)) {
 Context::current()
 .getExisting(RequestOut)
-->writeMessage(json::obj{
+->writeMessage(json::Object{
 {"jsonrpc", "2.0"},
 {"id", *ID},
-{"error",
- json::obj{{"code", static_cast(code)}, {"message", Message}}},
+{"error", json::Object{{"code", static_cast(code)},
+   {"message", Message}}},
 });
   }
 }
 
-void clangd::call(StringRef Method, json::Expr &&Params) {
+void clangd::call(StringRef Method, json::Value &&Params) {
   // FIXME: Generate/Increment IDs for every request so that we can get proper
   // replies once we need to.
-  RequestSpan::attach([&](json::obj &Args) {
-Args["Call"] = json::obj{{"method", Method.str()}, {"params", Params}};
+  RequestSpan::attach([&](json::Object &Args) {
+Args["Call"] = json::Object{{"method", Method.str()}, {"params", Params}};
   });
   Context::current()
   .ge

[clang-tools-extra] r336550 - [clangd] Mark "Document Symbols" as implemented in the docs

2018-07-09 Thread Marc-Andre Laperle via cfe-commits
Author: malaperle
Date: Mon Jul  9 07:34:07 2018
New Revision: 336550

URL: http://llvm.org/viewvc/llvm-project?rev=336550&view=rev
Log:
[clangd] Mark "Document Symbols" as implemented in the docs

Summary: Signed-off-by: Marc-Andre Laperle 

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

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

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

Modified: clang-tools-extra/trunk/docs/clangd.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clangd.rst?rev=336550&r1=336549&r2=336550&view=diff
==
--- clang-tools-extra/trunk/docs/clangd.rst (original)
+++ clang-tools-extra/trunk/docs/clangd.rst Mon Jul  9 07:34:07 2018
@@ -81,7 +81,7 @@ extension to the protocol.
 +-++--+
 | Code Lens   | Yes|   No |
 +-++--+
-| Document Symbols| Yes|   No |
+| Document Symbols| Yes|   Yes|
 +-++--+
 | Workspace Symbols   | Yes|   No |
 +-++--+


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


[PATCH] D48996: [clangd] Mark "Document Symbols" as implemented in the docs

2018-07-09 Thread Marc-Andre Laperle via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rL336550: [clangd] Mark "Document Symbols" as 
implemented in the docs (authored by malaperle, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D48996

Files:
  clang-tools-extra/trunk/docs/clangd.rst


Index: clang-tools-extra/trunk/docs/clangd.rst
===
--- clang-tools-extra/trunk/docs/clangd.rst
+++ clang-tools-extra/trunk/docs/clangd.rst
@@ -81,7 +81,7 @@
 +-++--+
 | Code Lens   | Yes|   No |
 +-++--+
-| Document Symbols| Yes|   No |
+| Document Symbols| Yes|   Yes|
 +-++--+
 | Workspace Symbols   | Yes|   No |
 +-++--+


Index: clang-tools-extra/trunk/docs/clangd.rst
===
--- clang-tools-extra/trunk/docs/clangd.rst
+++ clang-tools-extra/trunk/docs/clangd.rst
@@ -81,7 +81,7 @@
 +-++--+
 | Code Lens   | Yes|   No |
 +-++--+
-| Document Symbols| Yes|   No |
+| Document Symbols| Yes|   Yes|
 +-++--+
 | Workspace Symbols   | Yes|   No |
 +-++--+
___
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-09 Thread Simon Marchi via Phabricator via cfe-commits
simark marked 6 inline comments as done.
simark added inline comments.



Comment at: lib/Basic/VirtualFileSystem.cpp:488
+  }
+  StringRef getName() const { return Stat.getName(); }
   InMemoryNodeKind getKind() const { return Kind; }

ilya-biryukov wrote:
> Given that this method is inconsistent with `getStatus()` and seems to be 
> only used in `toString` methods, maybe we could make it `protected`? 
> Otherwise it's really easy to write code that gets the wrong path.
I now use it in `InMemoryDirIterator::setCurrentEntry`.  I will write a comment 
to the `getName` method to clarify this.


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] D49081: [libclang] Add support for AttributedType

2018-07-09 Thread Michael Wu via Phabricator via cfe-commits
michaelwu created this revision.

This patch adds support to the libclang API for identifying AttributedTypes in 
CXTypes and reading the modified type that the type points to. Currently 
AttributedTypes are skipped. This patch continues to skip AttributedTypes by 
default, but adds a parsing option to CXTranslationUnit to include 
AttributedTypes.

This patch depends on https://reviews.llvm.org/D49066 since it also adds a 
CXType.

Testing will be added in another patch which depends on this one.


Repository:
  rC Clang

https://reviews.llvm.org/D49081

Files:
  include/clang-c/Index.h
  tools/libclang/CXType.cpp
  tools/libclang/libclang.exports

Index: tools/libclang/libclang.exports
===
--- tools/libclang/libclang.exports
+++ tools/libclang/libclang.exports
@@ -103,6 +103,7 @@
 clang_Type_getObjCProtocolDecl
 clang_Type_getNumObjCTypeArgs
 clang_Type_getObjCTypeArg
+clang_Type_getModifiedType
 clang_VerbatimBlockLineComment_getText
 clang_VerbatimLineComment_getText
 clang_HTMLTagComment_getAsString
Index: tools/libclang/CXType.cpp
===
--- tools/libclang/CXType.cpp
+++ tools/libclang/CXType.cpp
@@ -112,6 +112,7 @@
 TKCASE(Auto);
 TKCASE(Elaborated);
 TKCASE(Pipe);
+TKCASE(Attributed);
 default:
   return CXType_Unexposed;
   }
@@ -125,7 +126,9 @@
   if (TU && !T.isNull()) {
 // Handle attributed types as the original type
 if (auto *ATT = T->getAs()) {
-  return MakeCXType(ATT->getModifiedType(), TU);
+  if (!(TU->ParsingOptions & CXTranslationUnit_IncludeAttributedTypes)) {
+return MakeCXType(ATT->getModifiedType(), TU);
+  }
 }
 // Handle paren types as the original type
 if (auto *PTT = T->getAs()) {
@@ -591,6 +594,7 @@
 TKIND(Auto);
 TKIND(Elaborated);
 TKIND(Pipe);
+TKIND(Attributed);
 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) TKIND(Id);
 #include "clang/Basic/OpenCLImageTypes.def"
 #undef IMAGE_TYPE
@@ -996,6 +1000,17 @@
   return CXTypeLayoutError_InvalidFieldName;
 }
 
+CXType clang_Type_getModifiedType(CXType CT) {
+  QualType T = GetQualType(CT);
+  if (T.isNull())
+return MakeCXType(QualType(), GetTU(CT));
+
+  if (auto *ATT = T->getAs())
+return MakeCXType(ATT->getModifiedType(), GetTU(CT));
+
+  return MakeCXType(QualType(), GetTU(CT));
+}
+
 long long clang_Cursor_getOffsetOfField(CXCursor C) {
   if (clang_isDeclaration(C.kind)) {
 // we need to validate the parent type
Index: include/clang-c/Index.h
===
--- include/clang-c/Index.h
+++ include/clang-c/Index.h
@@ -1332,7 +1332,12 @@
*
* The function bodies of the main file are not skipped.
*/
-  CXTranslationUnit_LimitSkipFunctionBodiesToPreamble = 0x800
+  CXTranslationUnit_LimitSkipFunctionBodiesToPreamble = 0x800,
+
+  /**
+   * Used to indicate that attributed types should be included in CXType.
+   */
+  CXTranslationUnit_IncludeAttributedTypes = 0x1000
 };
 
 /**
@@ -3269,7 +3274,8 @@
   CXType_OCLReserveID = 160,
 
   CXType_ObjCObject = 161,
-  CXType_ObjCTypeParam = 162
+  CXType_ObjCTypeParam = 162,
+  CXType_Attributed = 163
 };
 
 /**
@@ -3818,6 +3824,13 @@
  */
 CINDEX_LINKAGE long long clang_Type_getOffsetOf(CXType T, const char *S);
 
+/**
+ * Return the type that was modified by this attributed type.
+ *
+ * If the type is not an attributed type, an invalid type is returned.
+ */
+CINDEX_LINKAGE CXType clang_Type_getModifiedType(CXType T);
+
 /**
  * Return the offset of the field represented by the Cursor.
  *
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D47474: Implement cpu_dispatch/cpu_specific Multiversioning

2018-07-09 Thread Erich Keane via Phabricator via cfe-commits
erichkeane marked 4 inline comments as done.
erichkeane added a comment.

In https://reviews.llvm.org/D47474#1154858, @lebedev.ri wrote:

> Some drive-by nits.
>  General observation: this is kinda large.
>  I would //personally// split split off the codegen part into a second patch.


Thanks for the review!  I definitely agree this is a sizable patch, I'm not 
sure the non-codegen part has any value without the codegen so I'm not sure 
that splitting it would provide value.  I can definitely do so if reviewers in 
general believe this is the right tack.




Comment at: include/clang/Basic/X86Target.def:288
+
+// FIXME: When commented out features are supported in LLVM, enable them here.
+CPU_SPECIFIC("generic", 'A', "")

lebedev.ri wrote:
> This is going to go stale.
> It already does not have znver1, btver2.
> Surely this info already exists elsewhere in llvm?
> Can it be deduplicated somehow?
You'll note that this doesn't have any non-intel names :)   This is non-Intel 
processor friendly version of the ICC implementation of the same feature.  
Because of this, I don't have a good feature list for those.

I'd searched in a few places for an alternate source for these names/feature 
lists. I was unable to find anywhere else that needs/has similar information, 
though any alternate sources are greatly appreciated.

I'll note that the name and mangling-name aren't going to be able to be 
removed, though perhaps there is a source of these features somewhere?



Comment at: lib/CodeGen/CodeGenModule.cpp:868
+  const auto &Target = CGM.getTarget();
+  return std::string(".") + Target.CPUSpecificManglingCharacter(Name);
+}

lebedev.ri wrote:
> I think
> ```
> return Twine(".", Target.CPUSpecificManglingCharacter(Name)).str();
> ```
A twine of char + a char is actually pretty challenging... I rewrote it without 
the intermediate string though.  I am generally unconcerned, since 2 chars is 
very much in the 'short string optimization' range of all implementations.


https://reviews.llvm.org/D47474



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


[PATCH] D47474: Implement cpu_dispatch/cpu_specific Multiversioning

2018-07-09 Thread Erich Keane via Phabricator via cfe-commits
erichkeane updated this revision to Diff 154610.
erichkeane marked an inline comment as done.
erichkeane added a comment.

@lebedev.ri 's comments, plus a rebase.


https://reviews.llvm.org/D47474

Files:
  include/clang/AST/Decl.h
  include/clang/Basic/Attr.td
  include/clang/Basic/AttrDocs.td
  include/clang/Basic/DiagnosticGroups.td
  include/clang/Basic/DiagnosticSemaKinds.td
  include/clang/Basic/TargetInfo.h
  include/clang/Basic/X86Target.def
  lib/AST/Decl.cpp
  lib/Basic/Targets/X86.cpp
  lib/Basic/Targets/X86.h
  lib/CodeGen/CGBuiltin.cpp
  lib/CodeGen/CodeGenFunction.cpp
  lib/CodeGen/CodeGenFunction.h
  lib/CodeGen/CodeGenModule.cpp
  lib/CodeGen/CodeGenModule.h
  lib/Parse/ParseDecl.cpp
  lib/Sema/AnalysisBasedWarnings.cpp
  lib/Sema/Sema.cpp
  lib/Sema/SemaDecl.cpp
  lib/Sema/SemaDeclAttr.cpp
  lib/Sema/SemaExpr.cpp
  lib/Sema/SemaOverload.cpp
  test/CodeGen/attr-cpuspecific.c
  test/Misc/pragma-attribute-supported-attributes-list.test
  test/Sema/attr-cpuspecific.c
  test/SemaCXX/attr-cpuspecific.cpp
  utils/TableGen/ClangAttrEmitter.cpp

Index: utils/TableGen/ClangAttrEmitter.cpp
===
--- utils/TableGen/ClangAttrEmitter.cpp
+++ utils/TableGen/ClangAttrEmitter.cpp
@@ -1173,6 +1173,13 @@
 }
   };
 
+  class VariadicIdentifierArgument : public VariadicArgument {
+  public:
+VariadicIdentifierArgument(const Record &Arg, StringRef Attr)
+  : VariadicArgument(Arg, Attr, "IdentifierInfo *")
+{}
+  };
+
   class VariadicStringArgument : public VariadicArgument {
   public:
 VariadicStringArgument(const Record &Arg, StringRef Attr)
@@ -1278,6 +1285,8 @@
 Ptr = llvm::make_unique(Arg, Attr);
   else if (ArgName == "ParamIdxArgument")
 Ptr = llvm::make_unique(Arg, Attr, "ParamIdx");
+  else if (ArgName == "VariadicIdentifierArgument")
+Ptr = llvm::make_unique(Arg, Attr);
   else if (ArgName == "VersionArgument")
 Ptr = llvm::make_unique(Arg, Attr);
 
@@ -2106,6 +2115,34 @@
 .Default(false);
 }
 
+static bool isVariadicIdentifierArgument(Record *Arg) {
+  return !Arg->getSuperClasses().empty() &&
+ llvm::StringSwitch(
+ Arg->getSuperClasses().back().first->getName())
+ .Case("VariadicIdentifierArgument", true)
+ .Default(false);
+}
+
+static void emitClangAttrVariadicIdentifierArgList(RecordKeeper &Records,
+   raw_ostream &OS) {
+  OS << "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
+  std::vector Attrs = Records.getAllDerivedDefinitions("Attr");
+  for (const auto *A : Attrs) {
+// Determine whether the first argument is a variadic identifier.
+std::vector Args = A->getValueAsListOfDefs("Args");
+if (Args.empty() || !isVariadicIdentifierArgument(Args[0]))
+  continue;
+
+// All these spellings take an identifier argument.
+forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
+  OS << ".Case(\"" << S.name() << "\", "
+ << "true"
+ << ")\n";
+});
+  }
+  OS << "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
+}
+
 // Emits the first-argument-is-identifier property for attributes.
 static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
   OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
@@ -3696,6 +3733,7 @@
   emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
   emitClangAttrArgContextList(Records, OS);
   emitClangAttrIdentifierArgList(Records, OS);
+  emitClangAttrVariadicIdentifierArgList(Records, OS);
   emitClangAttrTypeArgList(Records, OS);
   emitClangAttrLateParsedList(Records, OS);
 }
Index: test/SemaCXX/attr-cpuspecific.cpp
===
--- /dev/null
+++ test/SemaCXX/attr-cpuspecific.cpp
@@ -0,0 +1,111 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu  -fsyntax-only -verify -fexceptions -fcxx-exceptions %s -std=c++14
+
+// expected-error@+1{{invalid option 'invalid' for cpu_dispatch}}
+void __attribute__((cpu_dispatch(atom, invalid))) invalid_cpu();
+
+void __attribute__((cpu_specific(atom))) no_default(void);
+void __attribute__((cpu_specific(sandybridge)))  no_default(void);
+
+struct MVReference {
+  int __attribute__((cpu_specific(sandybridge))) bar(void);
+  int __attribute__((cpu_specific(ivybridge))) bar(void);
+  int __attribute__((cpu_specific(sandybridge))) foo(void);
+};
+
+void use1(void){
+  // OK, will fail in the linker, unless another TU provides the cpu_dispatch.
+  no_default();
+
+  // expected-error@+1 {{call to non-static member function without an object argument}}
+  +MVReference::bar;
+  // expected-error@+1 {{call to non-static member function without an object argument}}
+  +MVReference::foo;
+  // expected-error@+1 {{reference to multiversioned function could not be resolved; did you mean to call it?}}
+  &MVReference::bar;
+  // expected-error@+1 {{reference to multiversioned function could not 

[PATCH] D49082: [libclang] Add the clang_Type_getNullability() API

2018-07-09 Thread Michael Wu via Phabricator via cfe-commits
michaelwu created this revision.

This patch adds a clang-c API for querying the nullability of an AttributedType.

The test here also tests https://reviews.llvm.org/D49081


Repository:
  rC Clang

https://reviews.llvm.org/D49082

Files:
  include/clang-c/Index.h
  test/Index/nullability.c
  tools/c-index-test/c-index-test.c
  tools/libclang/CXType.cpp
  tools/libclang/libclang.exports

Index: tools/libclang/libclang.exports
===
--- tools/libclang/libclang.exports
+++ tools/libclang/libclang.exports
@@ -104,6 +104,7 @@
 clang_Type_getNumObjCTypeArgs
 clang_Type_getObjCTypeArg
 clang_Type_getModifiedType
+clang_Type_getNullability
 clang_VerbatimBlockLineComment_getText
 clang_VerbatimLineComment_getText
 clang_HTMLTagComment_getAsString
Index: tools/libclang/CXType.cpp
===
--- tools/libclang/CXType.cpp
+++ tools/libclang/CXType.cpp
@@ -1240,3 +1240,22 @@
   }
   return false;
 }
+
+enum CXTypeNullabilityKind clang_Type_getNullability(CXType CT) {
+  QualType T = GetQualType(CT);
+  if (T.isNull())
+return CXTypeNullability_Invalid;
+
+  ASTContext &Ctx = cxtu::getASTUnit(GetTU(CT))->getASTContext();
+  if (auto nullability = T->getNullability(Ctx)) {
+switch (*nullability) {
+  case NullabilityKind::NonNull:
+return CXTypeNullability_NonNull;
+  case NullabilityKind::Nullable:
+return CXTypeNullability_Nullable;
+  case NullabilityKind::Unspecified:
+return CXTypeNullability_Unspecified;
+}
+  }
+  return CXTypeNullability_Invalid;
+}
Index: tools/c-index-test/c-index-test.c
===
--- tools/c-index-test/c-index-test.c
+++ tools/c-index-test/c-index-test.c
@@ -84,6 +84,8 @@
 options |= CXTranslationUnit_KeepGoing;
   if (getenv("CINDEXTEST_LIMIT_SKIP_FUNCTION_BODIES_TO_PREAMBLE"))
 options |= CXTranslationUnit_LimitSkipFunctionBodiesToPreamble;
+  if (getenv("CINDEXTEST_INCLUDE_ATTRIBUTED_TYPES"))
+options |= CXTranslationUnit_IncludeAttributedTypes;
 
   return options;
 }
@@ -1496,14 +1498,31 @@
   }
 }
 
+static void PrintNullabilityKind(CXType T, const char *Format) {
+  enum CXTypeNullabilityKind N = clang_Type_getNullability(T);
+
+  const char *nullability = 0;
+  switch (N) {
+case CXTypeNullability_NonNull: nullability = "nonnull"; break;
+case CXTypeNullability_Nullable: nullability = "nullable"; break;
+case CXTypeNullability_Unspecified: nullability = "unspecified"; break;
+case CXTypeNullability_Invalid: break;
+  }
+
+  if (nullability) {
+printf(Format, nullability);
+  }
+}
+
 static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
  CXClientData d) {
   if (!clang_isInvalid(clang_getCursorKind(cursor))) {
 CXType T = clang_getCursorType(cursor);
 CXType PT = clang_getPointeeType(T);
 enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
 PrintCursor(cursor, NULL);
 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
+PrintNullabilityKind(T, " [nullability=%s]");
 if (clang_isConstQualifiedType(T))
   printf(" const");
 if (clang_isVolatileQualifiedType(T))
@@ -1524,12 +1543,20 @@
 PrintTypeTemplateArgs(CT, " [canonicaltemplateargs/%d=");
   }
 }
+/* Print the modified type if it exists. */
+{
+  CXType MT = clang_Type_getModifiedType(T);
+  if (MT.kind != CXType_Invalid) {
+PrintTypeAndTypeKind(MT, " [modifiedtype=%s] [modifiedtypekind=%s]");
+  }
+}
 /* Print the return type if it exists. */
 {
   CXType RT = clang_getCursorResultType(cursor);
   if (RT.kind != CXType_Invalid) {
 PrintTypeAndTypeKind(RT, " [resulttype=%s] [resulttypekind=%s]");
   }
+  PrintNullabilityKind(RT, " [resultnullability=%s]");
 }
 /* Print the argument types if they exist. */
 {
@@ -1541,6 +1568,7 @@
   CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
   if (T.kind != CXType_Invalid) {
 PrintTypeAndTypeKind(T, " [%s] [%s]");
+PrintNullabilityKind(T, " [%s]");
   }
 }
 printf("]");
Index: test/Index/nullability.c
===
--- /dev/null
+++ test/Index/nullability.c
@@ -0,0 +1,10 @@
+int *a;
+int * _Nonnull b;
+int * _Nullable c;
+int * _Null_unspecified d;
+
+// RUN: env CINDEXTEST_INCLUDE_ATTRIBUTED_TYPES=1 c-index-test -test-print-type %s | FileCheck %s
+// CHECK: VarDecl=a:1:6 [type=int *] [typekind=Pointer] [isPOD=1] [pointeetype=int] [pointeekind=Int]
+// CHECK: VarDecl=b:2:16 [type=int * _Nonnull] [typekind=Attributed] [nullability=nonnull] [canonicaltype=int *] [canonicaltypekind=Pointer] [modifiedtype=int *] [modifiedtypekind=Pointer] [isPOD=1]
+// CHECK: VarDecl=c:3:17 [type=int * _Nullable] [typekind=Attribute

[PATCH] D49083: [HIP] Register/unregister device fat binary only once

2018-07-09 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl created this revision.
yaxunl added reviewers: tra, rjmccall.

HIP generates one fat binary for all devices after linking. However, for each 
compilation
unit a ctor function is emitted which register the same fat binary. Measures 
need to be
taken to make sure the fat binary is only registered once.

Currently each ctor function calls `__hipRegisterFatBinary` and stores the 
returned value
to `_gpubin_handle`. This patch changes the linkage of `_gpubin_handle` to be 
linkonce
so that they are shared between LLVM modules. Then this patch adds check of 
value of
`_gpubin_handle` to make sure `__hipRegisterFatBinary` is only called once. The 
code
is equivalent to

  void *_gpubin_handle;
  void ctor() {
if (_gpubin_handle == 0) {
  _gpubin_handle = __hipRegisterFatBinary(...);
}
// register kernels and variables.
  }

The patch also does similar change to dtors so that `__hipUnregisterFatBinary`
is called once.


https://reviews.llvm.org/D49083

Files:
  lib/CodeGen/CGCUDANV.cpp
  test/CodeGenCUDA/device-stub.cu

Index: test/CodeGenCUDA/device-stub.cu
===
--- test/CodeGenCUDA/device-stub.cu
+++ test/CodeGenCUDA/device-stub.cu
@@ -19,7 +19,7 @@
 // RUN:   | FileCheck %s -check-prefixes=NOGLOBALS,HIPNOGLOBALS
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm %s \
 // RUN: -fcuda-rdc -fcuda-include-gpubinary %t -o - -x hip \
-// RUN:   | FileCheck %s --check-prefixes=ALL,RDC,HIP,HIPRDC
+// RUN:   | FileCheck %s --check-prefixes=ALL,NORDC,HIP
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm %s -o - -x hip\
 // RUN:   | FileCheck %s -check-prefix=NOGPUBIN
 
@@ -79,11 +79,11 @@
 // CUDA-SAME: section ".nvFatBinSegment"
 // HIP-SAME: section ".hipFatBinSegment"
 // * variable to save GPU binary handle after initialization
-// NORDC: @__[[PREFIX]]_gpubin_handle = internal global i8** null
+// CUDANORDC: @__[[PREFIX]]_gpubin_handle = internal global i8** null
+// HIP: @__[[PREFIX]]_gpubin_handle = linkonce global i8** null
 // * constant unnamed string with NVModuleID
 // RDC: [[MODULE_ID_GLOBAL:@.*]] = private constant
 // CUDARDC-SAME: c"[[MODULE_ID:.+]]\00", section "__nv_module_id", align 32
-// HIPRDC-SAME: c"[[MODULE_ID:.+]]\00", section "__hip_module_id", align 32
 // * Make sure our constructor was added to global ctor list.
 // ALL: @llvm.global_ctors = appending global {{.*}}@__[[PREFIX]]_module_ctor
 // * Alias to global symbol containing the NVModuleID.
@@ -120,10 +120,18 @@
 // ALL: define internal void @__[[PREFIX]]_module_ctor
 
 // In separate mode it calls __[[PREFIX]]RegisterFatBinary(&__[[PREFIX]]_fatbin_wrapper)
+// HIP only register fat binary once.
+// HIP: load i8**, i8*** @__hip_gpubin_handle
+// HIP-NEXT: icmp eq i8** {{.*}}, null
+// HIP-NEXT: br i1 {{.*}}, label %if, label %exit
+// HIP: if:
 // NORDC: call{{.*}}[[PREFIX]]RegisterFatBinary{{.*}}__[[PREFIX]]_fatbin_wrapper
 //   .. stores return value in __[[PREFIX]]_gpubin_handle
 // NORDC-NEXT: store{{.*}}__[[PREFIX]]_gpubin_handle
 //   .. and then calls __[[PREFIX]]_register_globals
+// HIP-NEXT: br label %exit
+// HIP: exit:
+// HIP-NEXT: load i8**, i8*** @__hip_gpubin_handle
 // NORDC-NEXT: call void @__[[PREFIX]]_register_globals
 // * In separate mode we also register a destructor.
 // NORDC-NEXT: call i32 @atexit(void (i8*)* @__[[PREFIX]]_module_dtor)
@@ -136,7 +144,14 @@
 // Test that we've created destructor.
 // NORDC: define internal void @__[[PREFIX]]_module_dtor
 // NORDC: load{{.*}}__[[PREFIX]]_gpubin_handle
-// NORDC-NEXT: call void @__[[PREFIX]]UnregisterFatBinary
+// CUDANORDC-NEXT: call void @__[[PREFIX]]UnregisterFatBinary
+// HIP-NEXT: icmp ne i8** {{.*}}, null
+// HIP-NEXT: br i1 {{.*}}, label %if, label %exit
+// HIP: if:
+// HIP-NEXT: call void @__[[PREFIX]]UnregisterFatBinary
+// HIP-NEXT: store i8** null, i8*** @__hip_gpubin_handle
+// HIP-NEXT: br label %exit
+// HIP: exit:
 
 // There should be no __[[PREFIX]]_register_globals if we have no
 // device-side globals, but we still need to register GPU binary.
Index: lib/CodeGen/CGCUDANV.cpp
===
--- lib/CodeGen/CGCUDANV.cpp
+++ lib/CodeGen/CGCUDANV.cpp
@@ -427,9 +427,42 @@
   /*constant*/ true);
   FatbinWrapper->setSection(FatbinSectionName);
 
-  // Register binary with CUDA/HIP runtime. This is substantially different in
-  // default mode vs. separate compilation!
-  if (!RelocatableDeviceCode) {
+  // There is only one HIP fat binary per linked module, however there are
+  // multiple constructor functions. Make sure the fat binary is registered
+  // only once.
+  if (IsHIP) {
+llvm::BasicBlock *IfBlock =
+llvm::BasicBlock::Create(Context, "if", ModuleCtorFunc);
+llvm::BasicBlock *ExitBlock =
+llvm::BasicBlock::Create(Context, "exit", ModuleCtorFunc);
+GpuBinaryHandle = new llvm::GlobalVariable(
+TheModule, VoidPtrPtrTy, /*isConstant=*/false,
+llvm

[PATCH] D47817: [sanitizer_common] Fix using libtirpc on Linux

2018-07-09 Thread Michał Górny via Phabricator via cfe-commits
mgorny added a comment.

In https://reviews.llvm.org/D47817#1155788, @Lekensteyn wrote:

> In https://reviews.llvm.org/D47817#1155717, @mgorny wrote:
>
> > > This would be the first user of pkg-config here. I am not sure if this 
> > > would be the best fix. Usually you cannot (easily) recompile libc and 
> > > override it, but for external libs such as libtirpc this should be more 
> > > doable (I think).
> >
> > I don't think libtirpc's include path is expected to be predictable by 
> > design. I think it's something distro maintainers have to choose to avoid 
> > collision with headers that (used to be) installed by glibc. In any case, I 
> > can't think of a better solution than pkg-config here (libtirpc doesn't 
> > come with CMake modules).
>
>
> On Arch (libtirpc-1.0.3-2), Debian (libtirpc-dev 0.2.5-1.2 in sid), Gentoo 
> (libtirpc-1.0.3), the include files happen to be installed in 
> /usr/include/libtirpc, so it seems pretty consistent. So you could consider 
> writing a `cmake/Modules/FindLibtirpc.cmake` module that looks like:
>
>   # sets Libtirpc_FOUND Libtirpc_INCLUDE_DIRS
>  
>   find_path(Libtirpc_INCLUDE_DIR
> NAMES rpc/xdr.h
> PATH_SUFFIXES tirpc
>   )
>   include(FindPackageHandleStandardArgs)
>   find_package_handle_standard_args(Libtirpc REQUIRED_VARS 
> Libtirpc_INCLUDE_DIR)
>   if(Libtirpc_FOUND)
> set(Libtirpc_INCLUDE_DIRS ${Libtirpc_INCLUDE_DIR})
>   endif()
>
>
> then you can use `find_package(Libtirpc)` without depending on `pkg-config`.


I'm sorry but I'm not interested in putting a lot of effort to write a cheap 
hack-a-round to avoid following upstream recommendations. Not using pkg-config 
is just asking for forcing downstream maintainers to specially account for 
LLVM, and it only creates yet another excuse not to use pkg-config in the 
future ('because we managed to hack-it-around so far').

>> libtirpc case never could have worked.
> 
> The reason for that is probably because of 
> lib/sanitizer_common/sanitizer_platform.h saying:
> 
>   // Assume obsolete RPC headers are available by default
>   #if !defined(HAVE_RPC_XDR_H) && !defined(HAVE_TIRPC_RPC_XDR_H)
>   # define HAVE_RPC_XDR_H (SANITIZER_LINUX && !SANITIZER_ANDROID)
>   # define HAVE_TIRPC_RPC_XDR_H 0
>   #endif
> 
> 
> That should probably be addressed too.

Are you suggesting that I remove that?


Repository:
  rCRT Compiler Runtime

https://reviews.llvm.org/D47817



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


[PATCH] D49051: [libclang] check that the cursor is declaration before trying to evaluate the cursor like a declaration

2018-07-09 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith accepted this revision.
dexonsmith added a comment.
This revision is now accepted and ready to land.

LGTM.




Comment at: tools/libclang/CIndex.cpp:3892-3922
 CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
-  const Decl *D = getCursorDecl(C);
-  if (D) {
-const Expr *expr = nullptr;
-if (auto *Var = dyn_cast(D)) {
-  expr = Var->getInit();
-} else if (auto *Field = dyn_cast(D)) {
-  expr = Field->getInClassInitializer();
+  if (clang_isDeclaration(C.kind)) {
+const Decl *D = getCursorDecl(C);
+if (D) {
+  const Expr *expr = nullptr;
+  if (auto *Var = dyn_cast(D)) {
+expr = Var->getInit();

There's unfortunate nesting here.  It would be nice if, either pre-commit or 
post-commit, you could refactor this to be more straightline using early 
returns.  E.g.:
```
static CXEvalResult evaluateDeclExpr(const Decl *D) {
  if (!D)
return nullptr;
  // ...
}
static CXEvalResult evaluateCompoundStmtExpr(const CompoundStmt *CS) {
  if (!CS)
return nullptr;
  // ...
}
CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
  if (clang_isDeclaration(C.kind)) {
return evaluateDeclExpr(getCursorDecl(C));
  return evaluateCompoundStmtExpr(
  dyn_cast_or_null(getCursorStmt(C)));
}
```


Repository:
  rC Clang

https://reviews.llvm.org/D49051



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


[clang-tools-extra] r336553 - [clangd] Support indexing MACROs.

2018-07-09 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Mon Jul  9 08:31:07 2018
New Revision: 336553

URL: http://llvm.org/viewvc/llvm-project?rev=336553&view=rev
Log:
[clangd] Support indexing MACROs.

Summary: This is not enabled in the global-symbol-builder or dynamic index yet.

Reviewers: sammccall

Reviewed By: sammccall

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

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

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

Modified: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp?rev=336553&r1=336552&r2=336553&view=diff
==
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp Mon Jul  9 
08:31:07 2018
@@ -183,22 +183,19 @@ getIncludeHeader(llvm::StringRef QName,
   return toURI(SM, Header, Opts);
 }
 
-// Return the symbol location of the given declaration `D`.
-//
-// For symbols defined inside macros:
-//   * use expansion location, if the symbol is formed via macro concatenation.
-//   * use spelling location, otherwise.
-llvm::Optional getSymbolLocation(
-const NamedDecl &D, SourceManager &SM, const SymbolCollector::Options 
&Opts,
-const clang::LangOptions &LangOpts, std::string &FileURIStorage) {
-  SourceLocation NameLoc = findNameLoc(&D);
-  auto U = toURI(SM, SM.getFilename(NameLoc), Opts);
+// Return the symbol location of the token at \p Loc.
+llvm::Optional
+getTokenLocation(SourceLocation TokLoc, const SourceManager &SM,
+ const SymbolCollector::Options &Opts,
+ const clang::LangOptions &LangOpts,
+ std::string &FileURIStorage) {
+  auto U = toURI(SM, SM.getFilename(TokLoc), Opts);
   if (!U)
 return llvm::None;
   FileURIStorage = std::move(*U);
   SymbolLocation Result;
   Result.FileURI = FileURIStorage;
-  auto TokenLength = clang::Lexer::MeasureTokenLength(NameLoc, SM, LangOpts);
+  auto TokenLength = clang::Lexer::MeasureTokenLength(TokLoc, SM, LangOpts);
 
   auto CreatePosition = [&SM](SourceLocation Loc) {
 auto LSPLoc = sourceLocToPosition(SM, Loc);
@@ -208,8 +205,8 @@ llvm::Optional getSymbol
 return Pos;
   };
 
-  Result.Start = CreatePosition(NameLoc);
-  auto EndLoc = NameLoc.getLocWithOffset(TokenLength);
+  Result.Start = CreatePosition(TokLoc);
+  auto EndLoc = TokLoc.getLocWithOffset(TokenLength);
   Result.End = CreatePosition(EndLoc);
 
   return std::move(Result);
@@ -345,18 +342,106 @@ bool SymbolCollector::handleDeclOccurenc
   return true;
 }
 
+bool SymbolCollector::handleMacroOccurence(const IdentifierInfo *Name,
+   const MacroInfo *MI,
+   index::SymbolRoleSet Roles,
+   SourceLocation Loc) {
+  if (!Opts.CollectMacro)
+return true;
+  assert(PP.get());
+
+  const auto &SM = PP->getSourceManager();
+  if (SM.isInMainFile(SM.getExpansionLoc(MI->getDefinitionLoc(
+return true;
+  // Header guards are not interesting in index. Builtin macros don't have
+  // useful locations and are not needed for code completions.
+  if (MI->isUsedForHeaderGuard() || MI->isBuiltinMacro())
+return true;
+
+  // Mark the macro as referenced if this is a reference coming from the main
+  // file. The macro may not be an interesting symbol, but it's cheaper to 
check
+  // at the end.
+  if (Opts.CountReferences &&
+  (Roles & static_cast(index::SymbolRole::Reference)) &&
+  SM.getFileID(SM.getSpellingLoc(Loc)) == SM.getMainFileID())
+ReferencedMacros.insert(Name);
+  // Don't continue indexing if this is a mere reference.
+  // FIXME: remove macro with ID if it is undefined.
+  if (!(Roles & static_cast(index::SymbolRole::Declaration) ||
+Roles & static_cast(index::SymbolRole::Definition)))
+return true;
+
+
+  llvm::SmallString<128> USR;
+  if (index::generateUSRForMacro(Name->getName(), MI->getDefinitionLoc(), SM,
+ USR))
+return true;
+  SymbolID ID(USR);
+
+  // Only collect one instance in case there are multiple.
+  if (Symbols.find(ID) != nullptr)
+return true;
+
+  Symbol S;
+  S.ID = std::move(ID);
+  S.Name = Name->getName();
+  S.IsIndexedForCodeCompletion = true;
+  S.SymInfo = index::getSymbolInfoForMacro(*MI);
+  std::string FileURI;
+  if (auto DeclLoc = getTokenLocation(MI->getDefinitionLoc(), SM, Opts,
+  PP->getLangOpts(), FileURI))
+S.CanonicalDeclaration = *DeclLoc;
+
+  CodeCompletionResult SymbolCompletion(Name);
+  const auto *CCS = SymbolCompletion.CreateCodeCompletionStringForMacro(
+  *PP, *CompletionAllocator, *Com

[PATCH] D49028: [clangd] Support indexing MACROs.

2018-07-09 Thread Eric Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE336553: [clangd] Support indexing MACROs. (authored by 
ioeric, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D49028?vs=154559&id=154615#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49028

Files:
  clangd/index/SymbolCollector.cpp
  clangd/index/SymbolCollector.h
  unittests/clangd/SymbolCollectorTests.cpp

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -992,6 +992,32 @@
Field(&Symbol::Origin, SymbolOrigin::Static)));
 }
 
+TEST_F(SymbolCollectorTest, CollectMacros) {
+  CollectorOpts.CollectIncludePath = true;
+  Annotations Header(R"(
+#define X 1
+#define $mac[[MAC]](x) int x
+#define $used[[USED]](y) float y;
+
+MAC(p);
+  )");
+  const std::string Main = R"(
+#define MAIN 1  // not indexed
+USED(t);
+  )";
+  CollectorOpts.CountReferences = true;
+  CollectorOpts.CollectMacro = true;
+  runSymbolCollector(Header.code(), Main);
+  EXPECT_THAT(
+  Symbols,
+  UnorderedElementsAre(
+  QName("p"),
+  AllOf(QName("X"), DeclURI(TestHeaderURI),
+IncludeHeader(TestHeaderURI)),
+  AllOf(Labeled("MAC(x)"), Refs(0), DeclRange(Header.range("mac"))),
+  AllOf(Labeled("USED(y)"), Refs(1), DeclRange(Header.range("used");
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/index/SymbolCollector.h
===
--- clangd/index/SymbolCollector.h
+++ clangd/index/SymbolCollector.h
@@ -54,6 +54,11 @@
 bool CountReferences = false;
 // Every symbol collected will be stamped with this origin.
 SymbolOrigin Origin = SymbolOrigin::Unknown;
+/// Collect macros.
+/// Note that SymbolCollector must be run with preprocessor in order to
+/// collect macros. For example, `indexTopLevelDecls` will not index any
+/// macro even if this is true.
+bool CollectMacro = false;
   };
 
   SymbolCollector(Options Opts);
@@ -75,6 +80,10 @@
   SourceLocation Loc,
   index::IndexDataConsumer::ASTNodeInfo ASTNode) override;
 
+  bool handleMacroOccurence(const IdentifierInfo *Name, const MacroInfo *MI,
+index::SymbolRoleSet Roles,
+SourceLocation Loc) override;
+
   SymbolSlab takeSymbols() { return std::move(Symbols).build(); }
 
   void finish() override;
@@ -90,8 +99,9 @@
   std::shared_ptr CompletionAllocator;
   std::unique_ptr CompletionTUInfo;
   Options Opts;
-  // Decls referenced from the current TU, flushed on finish().
+  // Symbols referenced from the current TU, flushed on finish().
   llvm::DenseSet ReferencedDecls;
+  llvm::DenseSet ReferencedMacros;
   // Maps canonical declaration provided by clang to canonical declaration for
   // an index symbol, if clangd prefers a different declaration than that
   // provided by clang. For example, friend declaration might be considered
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -183,22 +183,19 @@
   return toURI(SM, Header, Opts);
 }
 
-// Return the symbol location of the given declaration `D`.
-//
-// For symbols defined inside macros:
-//   * use expansion location, if the symbol is formed via macro concatenation.
-//   * use spelling location, otherwise.
-llvm::Optional getSymbolLocation(
-const NamedDecl &D, SourceManager &SM, const SymbolCollector::Options &Opts,
-const clang::LangOptions &LangOpts, std::string &FileURIStorage) {
-  SourceLocation NameLoc = findNameLoc(&D);
-  auto U = toURI(SM, SM.getFilename(NameLoc), Opts);
+// Return the symbol location of the token at \p Loc.
+llvm::Optional
+getTokenLocation(SourceLocation TokLoc, const SourceManager &SM,
+ const SymbolCollector::Options &Opts,
+ const clang::LangOptions &LangOpts,
+ std::string &FileURIStorage) {
+  auto U = toURI(SM, SM.getFilename(TokLoc), Opts);
   if (!U)
 return llvm::None;
   FileURIStorage = std::move(*U);
   SymbolLocation Result;
   Result.FileURI = FileURIStorage;
-  auto TokenLength = clang::Lexer::MeasureTokenLength(NameLoc, SM, LangOpts);
+  auto TokenLength = clang::Lexer::MeasureTokenLength(TokLoc, SM, LangOpts);
 
   auto CreatePosition = [&SM](SourceLocation Loc) {
 auto LSPLoc = sourceLocToPosition(SM, Loc);
@@ -208,8 +205,8 @@
 return Pos;
   };
 
-  Result.Start = CreatePosition(NameLoc);
-  auto EndLoc = NameLoc.getLocWithOffset(TokenLength);
+  Result.Start = CreatePosition(TokLoc);
+  auto EndLoc = TokLoc.getLocWithOffset(TokenLength);
   Result.End = CreatePo

[PATCH] D49085: [Sema] Emit a diagnostic for an invalid dependent function template specialization

2018-07-09 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington created this revision.
erik.pilkington added reviewers: rjmccall, rsmith.
Herald added a subscriber: dexonsmith.

Previously, clang marked a decl as invalid without emitting a diagnostic. This 
lead to an assert in CodeGen for the attached test case.

rdar://41806724

Thanks for taking a look!
Erik


Repository:
  rC Clang

https://reviews.llvm.org/D49085

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaTemplate.cpp
  clang/test/CXX/temp/temp.decls/temp.friend/p1.cpp


Index: clang/test/CXX/temp/temp.decls/temp.friend/p1.cpp
===
--- clang/test/CXX/temp/temp.decls/temp.friend/p1.cpp
+++ clang/test/CXX/temp/temp.decls/temp.friend/p1.cpp
@@ -359,3 +359,13 @@
   template void f2(X *);
   template void f2(X *); // expected-note{{in instantiation of 
function template specialization 'PR10913::f2' requested here}}
 }
+
+namespace test16 {
+namespace s {
+template  struct foo {};
+}
+using s::foo;
+template  class A {
+  friend void foo<>(T); // expected-error{{dependent function template 
specialization of unknown function}}
+};
+}
Index: clang/lib/Sema/SemaTemplate.cpp
===
--- clang/lib/Sema/SemaTemplate.cpp
+++ clang/lib/Sema/SemaTemplate.cpp
@@ -8023,8 +8023,10 @@
   }
   F.done();
 
-  // Should this be diagnosed here?
-  if (Previous.empty()) return true;
+  if (Previous.empty()) {
+Diag(FD->getLocation(), diag::err_dependent_func_spec_does_not_specialize);
+return true;
+  }
 
   FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
  ExplicitTemplateArgs);
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -4087,6 +4087,8 @@
 def err_explicit_specialization_inconsistent_storage_class : Error<
   "explicit specialization has extraneous, inconsistent storage class "
   "'%select{none|extern|static|__private_extern__|auto|register}0'">;
+def err_dependent_func_spec_does_not_specialize : Error<
+  "dependent function template specialization of unknown function">;
 
 // C++ class template specializations and out-of-line definitions
 def err_template_spec_needs_header : Error<


Index: clang/test/CXX/temp/temp.decls/temp.friend/p1.cpp
===
--- clang/test/CXX/temp/temp.decls/temp.friend/p1.cpp
+++ clang/test/CXX/temp/temp.decls/temp.friend/p1.cpp
@@ -359,3 +359,13 @@
   template void f2(X *);
   template void f2(X *); // expected-note{{in instantiation of function template specialization 'PR10913::f2' requested here}}
 }
+
+namespace test16 {
+namespace s {
+template  struct foo {};
+}
+using s::foo;
+template  class A {
+  friend void foo<>(T); // expected-error{{dependent function template specialization of unknown function}}
+};
+}
Index: clang/lib/Sema/SemaTemplate.cpp
===
--- clang/lib/Sema/SemaTemplate.cpp
+++ clang/lib/Sema/SemaTemplate.cpp
@@ -8023,8 +8023,10 @@
   }
   F.done();
 
-  // Should this be diagnosed here?
-  if (Previous.empty()) return true;
+  if (Previous.empty()) {
+Diag(FD->getLocation(), diag::err_dependent_func_spec_does_not_specialize);
+return true;
+  }
 
   FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
  ExplicitTemplateArgs);
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -4087,6 +4087,8 @@
 def err_explicit_specialization_inconsistent_storage_class : Error<
   "explicit specialization has extraneous, inconsistent storage class "
   "'%select{none|extern|static|__private_extern__|auto|register}0'">;
+def err_dependent_func_spec_does_not_specialize : Error<
+  "dependent function template specialization of unknown function">;
 
 // C++ class template specializations and out-of-line definitions
 def err_template_spec_needs_header : Error<
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

2018-07-09 Thread Russell McClellan via Phabricator via cfe-commits
russellmcc added a comment.

Bump!

Thanks again for your time.


https://reviews.llvm.org/D40988



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


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

2018-07-09 Thread Simon Marchi via Phabricator via cfe-commits
simark marked an inline comment as done.
simark added a comment.

In https://reviews.llvm.org/D48903#1155403, @ilya-biryukov wrote:

> In https://reviews.llvm.org/D48903#1154846, @simark wrote:
>
> > With the `InMemoryFileSystem`, this now returns a non-real path.  The 
> > result is that we fill `RealPathName` with that non-real path.  I see two 
> > options here:
> >
> > 1. Either the FileManager is wrong to assume that `File::getName` returns a 
> > real path, and should call `FS->getRealPath` to do the job.
> > 2. If the contract is that the ` File::getName` interface should return a 
> > real path, then we should fix the `File::getName` implementation to do that 
> > somehow.
> >
> >   I would opt for 1.  This way, we could compute the `RealPathName` field 
> > even if we don't open the file (unlike currently).
>
>
> I'd also say `FileManager` should use `FileSystem::getRealPath`. The code 
> that does it differently was there before `FileSystem::getRealPath` was added.
>  And `RealFile` should probably not do any magic in `getName`, we could add a 
> separate method for (`getRealName`?) if that's absolutely needed.


I made `FileManager::getFile` use `FileSystem::getRealPath` and see no 
regression in clang and clang-tools-extra.


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-09 Thread Simon Marchi via Phabricator via cfe-commits
simark updated this revision to Diff 154631.
simark added a comment.

- Use FileSystem::getRealPath in FileManager::getFile


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
@@ -794,7 +794,7 @@
 
   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");
@@ -919,6 +919,37 @@
   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);
+  ASSERT_EQ("../b/c", 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
===
--- lib/Basic/VirtualFileSystem.cpp
+++ lib/Basic/VirtualFileSystem.cpp
@@ -479,7 +479,13 @@
   : Stat(std::move(Stat)), Kind(Kind) {}
   virtual ~InMemoryNode() = default;
 
-  const Status &getStatus() const { return Stat; }
+  /// Return the \p Status for this node. \p RequestedName should be the name
+  /// through which the caller referred to this node. It will override
+  /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
+  Status getStatus(StringRef RequestedName) const {
+return Status::copyWithNewName(Stat, RequestedName);
+  }
+  StringRef getName() const { return Stat.getName(); }
   InMemoryNodeKind getKind() const { return Kind; }
   virtual std::string toString(unsigned Indent) const = 0;
 };
@@ -496,22 +502,30 @@
   llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
 
   std::string toString(unsigned Indent) const override {
-return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
+return (std::string(Indent, ' ') + getName() + "\n").str();
   }
 
   static bool classof(const InMemoryNode *N) {
 return N->getKind() == IME_File;
   }
 };
 
-/// Adapt a InMemoryFile for VFS' File interface.
+/// Adapt a InMemoryFile for VFS' File interface.  The goal is to make
+/// \p InMemoryFileAdaptor mimic as much as possible the behavior of
+/// \p RealFile.
 class InMemoryFileAdaptor : public File {
   InMemoryFile &Node;
 
+  /// The name to use when returning a Status for this file.
+  std::string RequestedName;
+
 public:
-  explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
+  explicit InMemoryFileAdaptor(InMemoryFile &Node, std::string RequestedName)
+  : Node(Node), RequestedName(std::move(RequestedName)) {}
 
-  llvm::ErrorOr status() override { return Node.getStatus(); }
+  llvm::ErrorOr status() override {
+retur

[PATCH] D48981: Add caching when looking up coroutine_traits

2018-07-09 Thread Tanoy Sinha via Phabricator via cfe-commits
tks2103 added a comment.

ping @modocache @GorNishanov


Repository:
  rC Clang

https://reviews.llvm.org/D48981



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


[PATCH] D48989: -fdebug-prefix-map option for cc1as

2018-07-09 Thread Paul Robinson via Phabricator via cfe-commits
probinson added a comment.

In https://reviews.llvm.org/D48989#1153957, @starsid wrote:

> In https://reviews.llvm.org/D48989#1153773, @compnerd wrote:
>
> > However, please add a test to ensure that the paths are mapped when 
> > invoking the assembler
>
>
> I added the tests to check the mapping logic through llvm-mc in 
> https://reviews.llvm.org/D48988. In this revision, I merely test if the 
> driver is passing the flags to cc1as. The only thing that is untested is if 
> cc1as_main is setting the options in MCContext correctly. If you want to see 
> a test for that, please can you guide me a little on an appropriate way to 
> test this within tools/clang/test.


That would be more of an integration test, which we don't generally have in the 
'lit' tests.  I think demonstrating correct mapping by llvm-mc is fine.

I have made a suggestion for the test in this patch, which helps show the 
option is being passed to cc1as as intended.




Comment at: test/Driver/debug-prefix-map.S:3
+
+// CHECK: fdebug-prefix-map=old=new
+

To show that the option is on the cc1as command line specifically:
CHECK: cc1as
CHECK-SAME: -fdebug-prefix-map=old=new



Repository:
  rC Clang

https://reviews.llvm.org/D48989



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


[PATCH] D49074: [Analyzer] [WIP] Basic support for multiplication and division in the constraint manager

2018-07-09 Thread George Karpenkov via Phabricator via cfe-commits
george.karpenkov added a comment.

@baloghadamsoftware @dkrupp @xazax.hun Interesting. What do you think about 
instead using Z3 cross-check functionality recently added, to solve this and 
all other similar problems instead?


https://reviews.llvm.org/D49074



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


r336567 - [OPENMP, NVPTX] Do not globalize local variables in parallel regions.

2018-07-09 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Mon Jul  9 10:43:58 2018
New Revision: 336567

URL: http://llvm.org/viewvc/llvm-project?rev=336567&view=rev
Log:
[OPENMP, NVPTX] Do not globalize local variables in parallel regions.

In generic data-sharing mode we are allowed to not globalize local
variables that escape their declaration context iff they are declared
inside of the parallel region. We can do this because L2 parallel
regions are executed sequentially and, thus, we do not need to put
shared local variables in the global memory.

Modified:
cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
cfe/trunk/test/OpenMP/declare_target_codegen_globalization.cpp
cfe/trunk/test/OpenMP/nvptx_data_sharing.cpp
cfe/trunk/test/OpenMP/nvptx_distribute_parallel_generic_mode_codegen.cpp

cfe/trunk/test/OpenMP/nvptx_target_teams_distribute_parallel_for_generic_mode_codegen.cpp

Modified: cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp?rev=336567&r1=336566&r2=336567&view=diff
==
--- cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp Mon Jul  9 10:43:58 2018
@@ -1554,29 +1554,22 @@ void CGOpenMPRuntimeNVPTX::emitNumTeamsC
 llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
-  SourceLocation Loc = D.getLocStart();
-
   // Emit target region as a standalone region.
   class NVPTXPrePostActionTy : public PrePostActionTy {
-SourceLocation &Loc;
 bool &IsInParallelRegion;
 bool PrevIsInParallelRegion;
 
   public:
-NVPTXPrePostActionTy(SourceLocation &Loc, bool &IsInParallelRegion)
-: Loc(Loc), IsInParallelRegion(IsInParallelRegion) {}
+NVPTXPrePostActionTy(bool &IsInParallelRegion)
+: IsInParallelRegion(IsInParallelRegion) {}
 void Enter(CodeGenFunction &CGF) override {
-  static_cast(CGF.CGM.getOpenMPRuntime())
-  .emitGenericVarsProlog(CGF, Loc);
   PrevIsInParallelRegion = IsInParallelRegion;
   IsInParallelRegion = true;
 }
 void Exit(CodeGenFunction &CGF) override {
   IsInParallelRegion = PrevIsInParallelRegion;
-  static_cast(CGF.CGM.getOpenMPRuntime())
-  .emitGenericVarsEpilog(CGF);
 }
-  } Action(Loc, IsInParallelRegion);
+  } Action(IsInParallelRegion);
   CodeGen.setAction(Action);
   bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
   IsInTargetMasterThreadRegion = false;

Modified: cfe/trunk/test/OpenMP/declare_target_codegen_globalization.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/OpenMP/declare_target_codegen_globalization.cpp?rev=336567&r1=336566&r2=336567&view=diff
==
--- cfe/trunk/test/OpenMP/declare_target_codegen_globalization.cpp (original)
+++ cfe/trunk/test/OpenMP/declare_target_codegen_globalization.cpp Mon Jul  9 
10:43:58 2018
@@ -24,12 +24,11 @@ int maini1() {
 
 // parallel region
 // CHECK: define {{.*}}void @{{.*}}(i32* noalias {{.*}}, i32* noalias {{.*}}, 
i32* dereferenceable{{.*}})
-// CHECK: [[RES:%.+]] = call i8* @__kmpc_data_sharing_push_stack(i64 4, i16 0)
-// CHECK: [[GLOBALS:%.+]] = bitcast i8* [[RES]] to [[GLOBAL_ST:%struct[.].*]]*
-// CHECK: [[B_ADDR:%.+]] = getelementptr inbounds [[GLOBAL_ST]], 
[[GLOBAL_ST]]* [[GLOBALS]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
+// CHECK-NOT: call i8* @__kmpc_data_sharing_push_stack(
+// CHECK: [[B_ADDR:%.+]] = alloca i32,
 // CHECK: call {{.*}}[[FOO:@.*foo.*]](i32* dereferenceable{{.*}} [[B_ADDR]])
 // CHECK: call {{.*}}[[BAR:@.*bar.*]]()
-// CHECK: call void @__kmpc_data_sharing_pop_stack(i8* [[RES]])
+// CHECK-NOT: call void @__kmpc_data_sharing_pop_stack(
 // CHECK: ret void
 
 // CHECK: define {{.*}}[[FOO]](i32* dereferenceable{{.*}})

Modified: cfe/trunk/test/OpenMP/nvptx_data_sharing.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/OpenMP/nvptx_data_sharing.cpp?rev=336567&r1=336566&r2=336567&view=diff
==
--- cfe/trunk/test/OpenMP/nvptx_data_sharing.cpp (original)
+++ cfe/trunk/test/OpenMP/nvptx_data_sharing.cpp Mon Jul  9 10:43:58 2018
@@ -83,11 +83,10 @@ void test_ds(){
 /// outlined function for the second parallel region ///
 
 // CK1: define internal void @{{.+}}(i32* noalias %{{.+}}, i32* noalias 
%{{.+}}, i32* dereferenceable{{.+}}, i32* dereferenceable{{.+}})
-// CK1: [[RES:%.+]] = call i8* @__kmpc_data_sharing_push_stack(i64 4, i16 0)
-// CK1: [[GLOBALS:%.+]] = bitcast i8* [[RES]] to [[GLOBAL_TY:%.+]]*
-// CK1: [[C_ADDR:%.+]] = getelementptr inbounds [[GLOBAL_TY]], [[GLOBAL_TY]]* 
[[GLOBALS]], i32 0, i32 0
+// CK1-NOT: call i8* @__kmpc_data_sharing_push_stack(
+// CK1: [[C_ADDR:%.+]] = alloca i32

[PATCH] D41376: [libcxx] Implement ABI for Clang/GCC vector extension, constructors, copy_from and copy_to.

2018-07-09 Thread Marshall Clow via Phabricator via cfe-commits
mclow.lists added a comment.

Looks good; a bunch of minor things.
Remember to target c++17.
You need to indulge your OCD when writing the tests.




Comment at: libcxx/include/__config:1329
 
+#if !defined(_LIBCPP_COMPILER_CLANG) && !defined(_LIBCPP_COMPILER_GCC)
+#define _LIBCPP_HAS_NO_VECTOR_EXTENSION

We ususally organize these into "chunks", one per compiler.
The "Clang chunk" starts on 159, and goes to 483.
The "GCC chunk" starts on 484 and goes to  575.

It would match the organization better if you put this line:
#define _LIBCPP_HAS_NO_VECTOR_EXTENSION
in the file twice - once in the Clang chunk and once in the GCC chunk.

See `_LIBCPP_HAS_UNIQUE_OBJECT_REPRESENTATIONS` for an example of this.



Comment at: libcxx/include/experimental/simd:726
+#if defined(_LIBCPP_COMPILER_CLANG)
+#define _SPECIALIZE_VEC_EXT(_TYPE, _NUM_ELEMENT)   
\
+  template <>  
\

When we define user-visible macros in libc++, we prepend them with _LIBCPP_ to 
avoid collisions.
Accordingly, `_SPECIALIZE_VEC_EXT` should be named `_LIBCPP_SPECIALIZE_VEC_EXT`




Comment at: libcxx/include/experimental/simd:936
 
+template 
+struct __nodeduce {

We got rid of this for N4755 - but I think you're fixing this in D44663.



Comment at: libcxx/include/experimental/simd:964
 template 
-using native = compatible<_Tp>;
+using native =
+#ifndef _LIBCPP_HAS_NO_VECTOR_EXTENSION

I have a weak preference for putting entire statements inside `#ifdef` blocks 
where possible.



Comment at: libcxx/include/experimental/simd:1341
 // [simd.class]
 // TODO: implement simd
 template 

Is this TODO still necessary?



Comment at: libcxx/test/std/experimental/simd/simd.cons/broadcast.pass.cpp:79
+}
+
+int main() { test_broadcast(); }

Again, do we care about other types than `native_simd` here?



Comment at: libcxx/test/std/experimental/simd/simd.cons/default.pass.cpp:21
+using namespace std::experimental::parallelism_v2;
+
+int main() { (void)native_simd(); }

Do we need any other ctors tested here? `fixed_size_simd` for 
example?
Are there any post-conditions on the object created?

calling `size()` for example?




Comment at: libcxx/test/std/experimental/simd/simd.mem/load.pass.cpp:22
+
+using namespace std::experimental::parallelism_v2;
+

I am unsure about the desirability of testing this by hoisting it all into the 
global namespace.

for the pmr stuff, we did:
namespace ex = std::experimental::pmr;

and then referred to things as `ex::XXX`.  That way, you don't have to do all 
the typing, but we don't hide any ADL issues.

Obviously, this applies to all the tests.



Comment at: libcxx/test/std/experimental/simd/simd.mem/store.pass.cpp:10
+
+// UNSUPPORTED: c++98, c++03
+

more unsupported :-)



Comment at: libcxx/test/std/experimental/simd/simd.mem/store.pass.cpp:51
+
+#if TEST_STD_VER > 14
+  {

Don't need this anymore.


https://reviews.llvm.org/D41376



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


[PATCH] D49091: Warn about usage of __has_include/__has_include_next in macro expansions

2018-07-09 Thread Alexander Richardson via Phabricator via cfe-commits
arichardson created this revision.
arichardson added a reviewer: rsmith.
Herald added a subscriber: cfe-commits.

The characters after '__has_include(' have special lexing rules that can't
possibly be applied when __has_include is generated by a macro. Instead of
wrapping __has_include in another macro the following should be used instead:

#ifndef __has_include
#define __has_include(...) 0
#endif

This warning should fix the underlying issue for https://llvm.org/pr37990


Repository:
  rC Clang

https://reviews.llvm.org/D49091

Files:
  include/clang/Basic/DiagnosticLexKinds.td
  lib/Lex/PPMacroExpansion.cpp
  test/Preprocessor/expr_has_include_expansion.c


Index: test/Preprocessor/expr_has_include_expansion.c
===
--- /dev/null
+++ test/Preprocessor/expr_has_include_expansion.c
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 %s -E -verify -o /dev/null
+
+#define __libcpp_has_include(x) __has_include(x)
+#if __libcpp_has_include() // expected-warning{{macro expansion 
producing '__has_include' has undefined behavior}}
+#endif
+
+#define QT_HAS_INCLUDE_NEXT(x) __has_include_next(x)
+#if QT_HAS_INCLUDE_NEXT() // expected-warning{{macro expansion 
producing '__has_include_next' has undefined behavior}} 
expected-warning{{#include_next in primary source file}}
+#endif
+
+#define HAS_CHRONO __has_include()
+#if HAS_CHRONO // expected-warning{{macro expansion producing '__has_include' 
has undefined behavior}}
+#endif
+
+#define HAS_QUOTED_NEXT __has_include_next("foo.h")
+#if HAS_QUOTED_NEXT // expected-warning{{macro expansion producing 
'__has_include_next' has undefined behavior}} expected-warning{{#include_next 
in primary source file}}
+#endif
+
+// check that this diagnostic doesn't warn on normal __has_include() usage
+#if __has_include("foo.h") || __has_include_next("bar.h") // 
expected-warning{{#include_next in primary source file}}
+#endif
Index: lib/Lex/PPMacroExpansion.cpp
===
--- lib/Lex/PPMacroExpansion.cpp
+++ lib/Lex/PPMacroExpansion.cpp
@@ -1182,6 +1182,12 @@
 }
   }
 
+  if (LParenLoc.isMacroID())
+// The characters after '__has_include(' have special lexing rules that
+// can't possibly be applied when __has_include is generated by a macro.
+// Diagnose this to avoid problems such as https://llvm.org/pr37990
+PP.Diag(LParenLoc, diag::warn_has_include_in_macro_expansion) << II;
+
   // Reserve a buffer to get the spelling.
   SmallString<128> FilenameBuffer;
   StringRef Filename;
Index: include/clang/Basic/DiagnosticLexKinds.td
===
--- include/clang/Basic/DiagnosticLexKinds.td
+++ include/clang/Basic/DiagnosticLexKinds.td
@@ -771,6 +771,11 @@
   "macro expansion producing 'defined' has undefined behavior">,
   InGroup;
 
+def warn_has_include_in_macro_expansion : Warning<
+  "macro expansion producing %0 has undefined behavior">,
+InGroup>;
+
+
 let CategoryName = "Nullability Issue" in {
 
 def err_pp_assume_nonnull_syntax : Error<"expected 'begin' or 'end'">;


Index: test/Preprocessor/expr_has_include_expansion.c
===
--- /dev/null
+++ test/Preprocessor/expr_has_include_expansion.c
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 %s -E -verify -o /dev/null
+
+#define __libcpp_has_include(x) __has_include(x)
+#if __libcpp_has_include() // expected-warning{{macro expansion producing '__has_include' has undefined behavior}}
+#endif
+
+#define QT_HAS_INCLUDE_NEXT(x) __has_include_next(x)
+#if QT_HAS_INCLUDE_NEXT() // expected-warning{{macro expansion producing '__has_include_next' has undefined behavior}} expected-warning{{#include_next in primary source file}}
+#endif
+
+#define HAS_CHRONO __has_include()
+#if HAS_CHRONO // expected-warning{{macro expansion producing '__has_include' has undefined behavior}}
+#endif
+
+#define HAS_QUOTED_NEXT __has_include_next("foo.h")
+#if HAS_QUOTED_NEXT // expected-warning{{macro expansion producing '__has_include_next' has undefined behavior}} expected-warning{{#include_next in primary source file}}
+#endif
+
+// check that this diagnostic doesn't warn on normal __has_include() usage
+#if __has_include("foo.h") || __has_include_next("bar.h") // expected-warning{{#include_next in primary source file}}
+#endif
Index: lib/Lex/PPMacroExpansion.cpp
===
--- lib/Lex/PPMacroExpansion.cpp
+++ lib/Lex/PPMacroExpansion.cpp
@@ -1182,6 +1182,12 @@
 }
   }
 
+  if (LParenLoc.isMacroID())
+// The characters after '__has_include(' have special lexing rules that
+// can't possibly be applied when __has_include is generated by a macro.
+// Diagnose this to avoid problems such as https://llvm.org/pr37990
+PP.Diag(LParenLoc, diag::warn_has_include_in_macro_expansion) << II;
+
   // Reserve a buffer to get the spelling.
   SmallString<128> File

[PATCH] D44663: [libcxx] Update with R9 changes

2018-07-09 Thread Marshall Clow via Phabricator via cfe-commits
mclow.lists added a comment.

A few comments; more to come after the earlier patches land.




Comment at: libcxx/include/experimental/simd:1429
+struct deduce<_Tp, _Np, __simd_abi<__kind, __old_size>...> {
+  using type = __simd_abi<__kind, _Np>;
+};

Is this deliberately incomplete?
Comparing to N4755 - I see:

The member type shall be present if and only if:
* T is a vectorizable type, and
* simd_abi::fixed_size is supported (see 9.2.1), and
* every type in the Abis pack is an ABI tag.

Will a later patch fix this up?



Comment at: libcxx/include/experimental/simd:1725
 
 // NOTE: P0820 extension
 template 

We don't need the comments any more that P0820 has been adopted.




Comment at: libcxx/include/experimental/simd:1732
   __array_size>>::type
 split_by(const simd<_Tp, _Abi>& __v) {
+  arrayhttps://reviews.llvm.org/D44663



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


[PATCH] D49074: [Analyzer] [WIP] Basic support for multiplication and division in the constraint manager

2018-07-09 Thread George Karpenkov via Phabricator via cfe-commits
george.karpenkov requested changes to this revision.
george.karpenkov added a comment.
This revision now requires changes to proceed.

Let's discuss alternatives first.


https://reviews.llvm.org/D49074



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


[PATCH] D49051: [libclang] check that the cursor is declaration before trying to evaluate the cursor like a declaration

2018-07-09 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman marked an inline comment as done.
arphaman added inline comments.



Comment at: tools/libclang/CIndex.cpp:3892-3922
 CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
-  const Decl *D = getCursorDecl(C);
-  if (D) {
-const Expr *expr = nullptr;
-if (auto *Var = dyn_cast(D)) {
-  expr = Var->getInit();
-} else if (auto *Field = dyn_cast(D)) {
-  expr = Field->getInClassInitializer();
+  if (clang_isDeclaration(C.kind)) {
+const Decl *D = getCursorDecl(C);
+if (D) {
+  const Expr *expr = nullptr;
+  if (auto *Var = dyn_cast(D)) {
+expr = Var->getInit();

dexonsmith wrote:
> There's unfortunate nesting here.  It would be nice if, either pre-commit or 
> post-commit, you could refactor this to be more straightline using early 
> returns.  E.g.:
> ```
> static CXEvalResult evaluateDeclExpr(const Decl *D) {
>   if (!D)
> return nullptr;
>   // ...
> }
> static CXEvalResult evaluateCompoundStmtExpr(const CompoundStmt *CS) {
>   if (!CS)
> return nullptr;
>   // ...
> }
> CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
>   if (clang_isDeclaration(C.kind)) {
> return evaluateDeclExpr(getCursorDecl(C));
>   return evaluateCompoundStmtExpr(
>   dyn_cast_or_null(getCursorStmt(C)));
> }
> ```
Thanks, will do post commit.


Repository:
  rC Clang

https://reviews.llvm.org/D49051



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


[PATCH] D48685: [PCH+Modules] Load -fmodule-map-file content before including PCHs

2018-07-09 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir accepted this revision.
benlangmuir added a comment.
This revision is now accepted and ready to land.

LGTM


https://reviews.llvm.org/D48685



___
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-09 Thread Simon Marchi via Phabricator via cfe-commits
simark updated this revision to Diff 154662.
simark added a comment.

- Change InMemoryNode::getName to InMemoryNode::getFileName, to reduce the risk

of mis-using it.  Make the Stat field protected, make the subclasses' toString
access it directly.


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
@@ -794,7 +794,7 @@
 
   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");
@@ -919,6 +919,37 @@
   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);
+  ASSERT_EQ("../b/c", 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
===
--- lib/Basic/VirtualFileSystem.cpp
+++ lib/Basic/VirtualFileSystem.cpp
@@ -471,15 +471,27 @@
 /// The in memory file system is a tree of Nodes. Every node can either be a
 /// file or a directory.
 class InMemoryNode {
-  Status Stat;
   InMemoryNodeKind Kind;
 
+protected:
+  Status Stat;
+
 public:
   InMemoryNode(Status Stat, InMemoryNodeKind Kind)
-  : Stat(std::move(Stat)), Kind(Kind) {}
+  : Kind(Kind), Stat(std::move(Stat)) {}
   virtual ~InMemoryNode() = default;
 
-  const Status &getStatus() const { return Stat; }
+  /// Return the \p Status for this node. \p RequestedName should be the name
+  /// through which the caller referred to this node. It will override
+  /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
+  Status getStatus(StringRef RequestedName) const {
+return Status::copyWithNewName(Stat, RequestedName);
+  }
+
+  /// Get the filename of this node (the name without the directory part).
+  StringRef getFileName() const {
+return llvm::sys::path::filename(Stat.getName());
+  }
   InMemoryNodeKind getKind() const { return Kind; }
   virtual std::string toString(unsigned Indent) const = 0;
 };
@@ -496,22 +508,30 @@
   llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
 
   std::string toString(unsigned Indent) const override {
-return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
+return (std::string(Indent, ' ') + Stat.getName() + "\n").str();
   }
 
   static bool classof(const InMemoryNode *N) {
 return N->getKind() == IME_File;
   }
 };
 
-/// Adapt a InMemoryFile for VFS' File interface.
+/// Adapt a InMemoryFile for VFS' File interface.  The goal is to make
+/// \p InMemoryFileAdaptor

r336579 - [Power9] Add __float128 builtins for Round To Odd

2018-07-09 Thread Stefan Pintilie via cfe-commits
Author: stefanp
Date: Mon Jul  9 11:50:40 2018
New Revision: 336579

URL: http://llvm.org/viewvc/llvm-project?rev=336579&view=rev
Log:
[Power9] Add __float128 builtins for Round To Odd

Add a number of builtins for __float128 Round To Odd.
This is the Clang portion of the builtins work.

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

Added:
cfe/trunk/test/CodeGen/builtins-ppc-p9-f128.c
Modified:
cfe/trunk/include/clang/Basic/BuiltinsPPC.def

Modified: cfe/trunk/include/clang/Basic/BuiltinsPPC.def
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/BuiltinsPPC.def?rev=336579&r1=336578&r2=336579&view=diff
==
--- cfe/trunk/include/clang/Basic/BuiltinsPPC.def (original)
+++ cfe/trunk/include/clang/Basic/BuiltinsPPC.def Mon Jul  9 11:50:40 2018
@@ -423,6 +423,14 @@ BUILTIN(__builtin_vsx_extractuword, "V2U
 BUILTIN(__builtin_vsx_xxpermdi, "v.", "t")
 BUILTIN(__builtin_vsx_xxsldwi, "v.", "t")
 
+// Float 128 built-ins
+BUILTIN(__builtin_sqrtf128_round_to_odd, "LLdLLd", "")
+BUILTIN(__builtin_addf128_round_to_odd, "LLdLLdLLd", "")
+BUILTIN(__builtin_subf128_round_to_odd, "LLdLLdLLd", "")
+BUILTIN(__builtin_mulf128_round_to_odd, "LLdLLdLLd", "")
+BUILTIN(__builtin_divf128_round_to_odd, "LLdLLdLLd", "")
+BUILTIN(__builtin_fmaf128_round_to_odd, "LLdLLdLLdLLd", "")
+
 // HTM builtins
 BUILTIN(__builtin_tbegin, "UiUIi", "")
 BUILTIN(__builtin_tend, "UiUIi", "")

Added: cfe/trunk/test/CodeGen/builtins-ppc-p9-f128.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/builtins-ppc-p9-f128.c?rev=336579&view=auto
==
--- cfe/trunk/test/CodeGen/builtins-ppc-p9-f128.c (added)
+++ cfe/trunk/test/CodeGen/builtins-ppc-p9-f128.c Mon Jul  9 11:50:40 2018
@@ -0,0 +1,45 @@
+// RUN: %clang_cc1 -triple powerpc64le-unknown-linux-gnu -emit-llvm \
+// RUN:   -target-cpu pwr9 -target-feature +float128 -o - %s | FileCheck %s
+
+__float128 A;
+__float128 B;
+__float128 C;
+
+
+__float128 testSqrtOdd() {
+  return __builtin_sqrtf128_round_to_odd(A);
+// CHECK: @llvm.ppc.sqrtf128.round.to.odd(fp128
+// CHECK-NEXT: ret fp128
+}
+
+__float128 testFMAOdd() {
+  return __builtin_fmaf128_round_to_odd(A, B, C);
+// CHECK: @llvm.ppc.fmaf128.round.to.odd(fp128 %{{.+}}, fp128 %{{.+}}, fp128
+// CHECK-NEXT: ret fp128
+}
+
+__float128 testAddOdd() {
+  return __builtin_addf128_round_to_odd(A, B);
+// CHECK: @llvm.ppc.addf128.round.to.odd(fp128 %{{.+}}, fp128
+// CHECK-NEXT: ret fp128
+}
+
+__float128 testSubOdd() {
+  return __builtin_subf128_round_to_odd(A, B);
+// CHECK: @llvm.ppc.subf128.round.to.odd(fp128 %{{.+}}, fp128
+// CHECK-NEXT: ret fp128
+}
+
+__float128 testMulOdd() {
+  return __builtin_mulf128_round_to_odd(A, B);
+// CHECK: @llvm.ppc.mulf128.round.to.odd(fp128 %{{.+}}, fp128
+// CHECK-NEXT: ret fp128
+}
+
+__float128 testDivOdd() {
+  return __builtin_divf128_round_to_odd(A, B);
+// CHECK: @llvm.ppc.divf128.round.to.odd(fp128 %{{.+}}, fp128
+// CHECK-NEXT: ret fp128
+}
+
+


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


[PATCH] D47548: [Power9] Add __float128 builtins for Round To Odd

2018-07-09 Thread Stefan Pintilie via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC336579: [Power9] Add __float128 builtins for Round To Odd 
(authored by stefanp, committed by ).
Herald added a subscriber: cfe-commits.

Repository:
  rC Clang

https://reviews.llvm.org/D47548

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


Index: include/clang/Basic/BuiltinsPPC.def
===
--- include/clang/Basic/BuiltinsPPC.def
+++ include/clang/Basic/BuiltinsPPC.def
@@ -423,6 +423,14 @@
 BUILTIN(__builtin_vsx_xxpermdi, "v.", "t")
 BUILTIN(__builtin_vsx_xxsldwi, "v.", "t")
 
+// Float 128 built-ins
+BUILTIN(__builtin_sqrtf128_round_to_odd, "LLdLLd", "")
+BUILTIN(__builtin_addf128_round_to_odd, "LLdLLdLLd", "")
+BUILTIN(__builtin_subf128_round_to_odd, "LLdLLdLLd", "")
+BUILTIN(__builtin_mulf128_round_to_odd, "LLdLLdLLd", "")
+BUILTIN(__builtin_divf128_round_to_odd, "LLdLLdLLd", "")
+BUILTIN(__builtin_fmaf128_round_to_odd, "LLdLLdLLdLLd", "")
+
 // HTM builtins
 BUILTIN(__builtin_tbegin, "UiUIi", "")
 BUILTIN(__builtin_tend, "UiUIi", "")
Index: test/CodeGen/builtins-ppc-p9-f128.c
===
--- test/CodeGen/builtins-ppc-p9-f128.c
+++ test/CodeGen/builtins-ppc-p9-f128.c
@@ -0,0 +1,45 @@
+// RUN: %clang_cc1 -triple powerpc64le-unknown-linux-gnu -emit-llvm \
+// RUN:   -target-cpu pwr9 -target-feature +float128 -o - %s | FileCheck %s
+
+__float128 A;
+__float128 B;
+__float128 C;
+
+
+__float128 testSqrtOdd() {
+  return __builtin_sqrtf128_round_to_odd(A);
+// CHECK: @llvm.ppc.sqrtf128.round.to.odd(fp128
+// CHECK-NEXT: ret fp128
+}
+
+__float128 testFMAOdd() {
+  return __builtin_fmaf128_round_to_odd(A, B, C);
+// CHECK: @llvm.ppc.fmaf128.round.to.odd(fp128 %{{.+}}, fp128 %{{.+}}, fp128
+// CHECK-NEXT: ret fp128
+}
+
+__float128 testAddOdd() {
+  return __builtin_addf128_round_to_odd(A, B);
+// CHECK: @llvm.ppc.addf128.round.to.odd(fp128 %{{.+}}, fp128
+// CHECK-NEXT: ret fp128
+}
+
+__float128 testSubOdd() {
+  return __builtin_subf128_round_to_odd(A, B);
+// CHECK: @llvm.ppc.subf128.round.to.odd(fp128 %{{.+}}, fp128
+// CHECK-NEXT: ret fp128
+}
+
+__float128 testMulOdd() {
+  return __builtin_mulf128_round_to_odd(A, B);
+// CHECK: @llvm.ppc.mulf128.round.to.odd(fp128 %{{.+}}, fp128
+// CHECK-NEXT: ret fp128
+}
+
+__float128 testDivOdd() {
+  return __builtin_divf128_round_to_odd(A, B);
+// CHECK: @llvm.ppc.divf128.round.to.odd(fp128 %{{.+}}, fp128
+// CHECK-NEXT: ret fp128
+}
+
+


Index: include/clang/Basic/BuiltinsPPC.def
===
--- include/clang/Basic/BuiltinsPPC.def
+++ include/clang/Basic/BuiltinsPPC.def
@@ -423,6 +423,14 @@
 BUILTIN(__builtin_vsx_xxpermdi, "v.", "t")
 BUILTIN(__builtin_vsx_xxsldwi, "v.", "t")
 
+// Float 128 built-ins
+BUILTIN(__builtin_sqrtf128_round_to_odd, "LLdLLd", "")
+BUILTIN(__builtin_addf128_round_to_odd, "LLdLLdLLd", "")
+BUILTIN(__builtin_subf128_round_to_odd, "LLdLLdLLd", "")
+BUILTIN(__builtin_mulf128_round_to_odd, "LLdLLdLLd", "")
+BUILTIN(__builtin_divf128_round_to_odd, "LLdLLdLLd", "")
+BUILTIN(__builtin_fmaf128_round_to_odd, "LLdLLdLLdLLd", "")
+
 // HTM builtins
 BUILTIN(__builtin_tbegin, "UiUIi", "")
 BUILTIN(__builtin_tend, "UiUIi", "")
Index: test/CodeGen/builtins-ppc-p9-f128.c
===
--- test/CodeGen/builtins-ppc-p9-f128.c
+++ test/CodeGen/builtins-ppc-p9-f128.c
@@ -0,0 +1,45 @@
+// RUN: %clang_cc1 -triple powerpc64le-unknown-linux-gnu -emit-llvm \
+// RUN:   -target-cpu pwr9 -target-feature +float128 -o - %s | FileCheck %s
+
+__float128 A;
+__float128 B;
+__float128 C;
+
+
+__float128 testSqrtOdd() {
+  return __builtin_sqrtf128_round_to_odd(A);
+// CHECK: @llvm.ppc.sqrtf128.round.to.odd(fp128
+// CHECK-NEXT: ret fp128
+}
+
+__float128 testFMAOdd() {
+  return __builtin_fmaf128_round_to_odd(A, B, C);
+// CHECK: @llvm.ppc.fmaf128.round.to.odd(fp128 %{{.+}}, fp128 %{{.+}}, fp128
+// CHECK-NEXT: ret fp128
+}
+
+__float128 testAddOdd() {
+  return __builtin_addf128_round_to_odd(A, B);
+// CHECK: @llvm.ppc.addf128.round.to.odd(fp128 %{{.+}}, fp128
+// CHECK-NEXT: ret fp128
+}
+
+__float128 testSubOdd() {
+  return __builtin_subf128_round_to_odd(A, B);
+// CHECK: @llvm.ppc.subf128.round.to.odd(fp128 %{{.+}}, fp128
+// CHECK-NEXT: ret fp128
+}
+
+__float128 testMulOdd() {
+  return __builtin_mulf128_round_to_odd(A, B);
+// CHECK: @llvm.ppc.mulf128.round.to.odd(fp128 %{{.+}}, fp128
+// CHECK-NEXT: ret fp128
+}
+
+__float128 testDivOdd() {
+  return __builtin_divf128_round_to_odd(A, B);
+// CHECK: @llvm.ppc.divf128.round.to.odd(fp128 %{{.+}}, fp128
+// CHECK-NEXT: ret fp128
+}
+
+
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r336581 - [clangd] Make sure macro information exists before increasing usage count.

2018-07-09 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Mon Jul  9 11:54:51 2018
New Revision: 336581

URL: http://llvm.org/viewvc/llvm-project?rev=336581&view=rev
Log:
[clangd] Make sure macro information exists before increasing usage count.

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

Modified: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp?rev=336581&r1=336580&r2=336581&view=diff
==
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp Mon Jul  9 
11:54:51 2018
@@ -371,7 +371,6 @@ bool SymbolCollector::handleMacroOccuren
 Roles & static_cast(index::SymbolRole::Definition)))
 return true;
 
-
   llvm::SmallString<128> USR;
   if (index::generateUSRForMacro(Name->getName(), MI->getDefinitionLoc(), SM,
  USR))
@@ -433,11 +432,10 @@ void SymbolCollector::finish() {
 assert(PP);
 for (const IdentifierInfo *II : ReferencedMacros) {
   llvm::SmallString<128> USR;
-  if (!index::generateUSRForMacro(
-  II->getName(),
-  PP->getMacroDefinition(II).getMacroInfo()->getDefinitionLoc(),
-  PP->getSourceManager(), USR))
-IncRef(SymbolID(USR));
+  if (const auto *MI = PP->getMacroDefinition(II).getMacroInfo())
+if (!index::generateUSRForMacro(II->getName(), MI->getDefinitionLoc(),
+PP->getSourceManager(), USR))
+  IncRef(SymbolID(USR));
 }
   }
   ReferencedDecls.clear();


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


[PATCH] D48989: -fdebug-prefix-map option for cc1as

2018-07-09 Thread Siddhartha Bagaria via Phabricator via cfe-commits
starsid updated this revision to Diff 154669.
starsid marked an inline comment as done.
starsid added a comment.

Test improvements


Repository:
  rC Clang

https://reviews.llvm.org/D48989

Files:
  include/clang/Driver/Options.td
  lib/Driver/ToolChains/Clang.cpp
  test/Driver/debug-prefix-map.S
  tools/driver/cc1as_main.cpp

Index: tools/driver/cc1as_main.cpp
===
--- tools/driver/cc1as_main.cpp
+++ tools/driver/cc1as_main.cpp
@@ -94,6 +94,7 @@
   std::string DwarfDebugFlags;
   std::string DwarfDebugProducer;
   std::string DebugCompilationDir;
+  std::map DebugPrefixMap;
   llvm::DebugCompressionType CompressDebugSections =
   llvm::DebugCompressionType::None;
   std::string MainFileName;
@@ -233,6 +234,9 @@
   Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
   Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
 
+  for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ))
+Opts.DebugPrefixMap.insert(StringRef(Arg).split('='));
+
   // Frontend Options
   if (Args.hasArg(OPT_INPUT)) {
 bool First = true;
@@ -377,6 +381,9 @@
 Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
   if (!Opts.DebugCompilationDir.empty())
 Ctx.setCompilationDir(Opts.DebugCompilationDir);
+  if (!Opts.DebugPrefixMap.empty())
+for (const auto &KV : Opts.DebugPrefixMap)
+  Ctx.addDebugPrefixMapEntry(KV.first, KV.second);
   if (!Opts.MainFileName.empty())
 Ctx.setMainFileName(StringRef(Opts.MainFileName));
   Ctx.setDwarfVersion(Opts.DwarfVersion);
Index: test/Driver/debug-prefix-map.S
===
--- /dev/null
+++ test/Driver/debug-prefix-map.S
@@ -0,0 +1,6 @@
+// RUN: %clang -### -g -fdebug-prefix-map=old=new %s 2>&1 | FileCheck %s
+
+// CHECK: cc1as
+// CHECK-SAME: -fdebug-prefix-map=old=new
+
+// More tests for this flag in debug-prefix-map.c.
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -600,6 +600,18 @@
   }
 }
 
+/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
+static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
+  for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
+StringRef Map = A->getValue();
+if (Map.find('=') == StringRef::npos)
+  D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
+else
+  CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
+A->claim();
+  }
+}
+
 /// Vectorize at all optimization levels greater than 1 except for -Oz.
 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
@@ -3800,14 +3812,7 @@
   // Add in -fdebug-compilation-dir if necessary.
   addDebugCompDirArg(Args, CmdArgs);
 
-  for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
-StringRef Map = A->getValue();
-if (Map.find('=') == StringRef::npos)
-  D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
-else
-  CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
-A->claim();
-  }
+  addDebugPrefixMapArg(D, Args, CmdArgs);
 
   if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
options::OPT_ftemplate_depth_EQ)) {
@@ -5352,6 +5357,8 @@
 // Add the -fdebug-compilation-dir flag if needed.
 addDebugCompDirArg(Args, CmdArgs);
 
+addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
+
 // Set the AT_producer to the clang version when using the integrated
 // assembler on assembly source files.
 CmdArgs.push_back("-dwarf-debug-producer");
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -1740,7 +1740,8 @@
 def fno_split_dwarf_inlining: Flag<["-"], "fno-split-dwarf-inlining">, Group,
   Flags<[CC1Option]>;
 def fdebug_prefix_map_EQ
-  : Joined<["-"], "fdebug-prefix-map=">, Group, Flags<[CC1Option]>,
+  : Joined<["-"], "fdebug-prefix-map=">, Group,
+Flags<[CC1Option,CC1AsOption]>,
 HelpText<"remap file source paths in debug info">;
 def g_Flag : Flag<["-"], "g">, Group,
   HelpText<"Generate source-level debug information">;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D48617: [Builtins][Attributes][X86] Tag all X86 builtins with their required vector width. Add a min_vector_width function attribute and tag all x86 instrinsics with it.

2018-07-09 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL336583: [Builtins][Attributes][X86] Tag all X86 builtins 
with their required vector… (authored by ctopper, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D48617?vs=153786&id=154671#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D48617

Files:
  cfe/trunk/include/clang/Basic/Attr.td
  cfe/trunk/include/clang/Basic/AttrDocs.td
  cfe/trunk/include/clang/Basic/Builtins.def
  cfe/trunk/include/clang/Basic/Builtins.h
  cfe/trunk/include/clang/Basic/BuiltinsX86.def
  cfe/trunk/include/clang/Basic/BuiltinsX86_64.def
  cfe/trunk/lib/Basic/Builtins.cpp
  cfe/trunk/lib/CodeGen/CGBuiltin.cpp
  cfe/trunk/lib/CodeGen/CodeGenFunction.cpp
  cfe/trunk/lib/CodeGen/CodeGenFunction.h
  cfe/trunk/lib/Headers/__wmmintrin_aes.h
  cfe/trunk/lib/Headers/ammintrin.h
  cfe/trunk/lib/Headers/avx2intrin.h
  cfe/trunk/lib/Headers/avx512bitalgintrin.h
  cfe/trunk/lib/Headers/avx512bwintrin.h
  cfe/trunk/lib/Headers/avx512cdintrin.h
  cfe/trunk/lib/Headers/avx512dqintrin.h
  cfe/trunk/lib/Headers/avx512fintrin.h
  cfe/trunk/lib/Headers/avx512ifmaintrin.h
  cfe/trunk/lib/Headers/avx512ifmavlintrin.h
  cfe/trunk/lib/Headers/avx512vbmi2intrin.h
  cfe/trunk/lib/Headers/avx512vbmiintrin.h
  cfe/trunk/lib/Headers/avx512vbmivlintrin.h
  cfe/trunk/lib/Headers/avx512vlbitalgintrin.h
  cfe/trunk/lib/Headers/avx512vlbwintrin.h
  cfe/trunk/lib/Headers/avx512vlcdintrin.h
  cfe/trunk/lib/Headers/avx512vldqintrin.h
  cfe/trunk/lib/Headers/avx512vlintrin.h
  cfe/trunk/lib/Headers/avx512vlvbmi2intrin.h
  cfe/trunk/lib/Headers/avx512vlvnniintrin.h
  cfe/trunk/lib/Headers/avx512vnniintrin.h
  cfe/trunk/lib/Headers/avx512vpopcntdqintrin.h
  cfe/trunk/lib/Headers/avx512vpopcntdqvlintrin.h
  cfe/trunk/lib/Headers/avxintrin.h
  cfe/trunk/lib/Headers/emmintrin.h
  cfe/trunk/lib/Headers/f16cintrin.h
  cfe/trunk/lib/Headers/fma4intrin.h
  cfe/trunk/lib/Headers/fmaintrin.h
  cfe/trunk/lib/Headers/gfniintrin.h
  cfe/trunk/lib/Headers/mm3dnow.h
  cfe/trunk/lib/Headers/mmintrin.h
  cfe/trunk/lib/Headers/pmmintrin.h
  cfe/trunk/lib/Headers/shaintrin.h
  cfe/trunk/lib/Headers/smmintrin.h
  cfe/trunk/lib/Headers/tmmintrin.h
  cfe/trunk/lib/Headers/vaesintrin.h
  cfe/trunk/lib/Headers/xmmintrin.h
  cfe/trunk/lib/Headers/xopintrin.h
  cfe/trunk/lib/Sema/SemaDeclAttr.cpp
  cfe/trunk/test/CodeGen/function-min-vector-width.c
  cfe/trunk/test/CodeGen/x86-builtins-vector-width.c
  cfe/trunk/test/Misc/pragma-attribute-supported-attributes-list.test
  cfe/trunk/test/Sema/attr-min-vector-width.c



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


r336584 - [Index] Ignore noop #undef's when handling macro occurrences.

2018-07-09 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Mon Jul  9 12:02:41 2018
New Revision: 336584

URL: http://llvm.org/viewvc/llvm-project?rev=336584&view=rev
Log:
[Index] Ignore noop #undef's when handling macro occurrences.

Modified:
cfe/trunk/lib/Index/IndexingAction.cpp

Modified: cfe/trunk/lib/Index/IndexingAction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Index/IndexingAction.cpp?rev=336584&r1=336583&r2=336584&view=diff
==
--- cfe/trunk/lib/Index/IndexingAction.cpp (original)
+++ cfe/trunk/lib/Index/IndexingAction.cpp Mon Jul  9 12:02:41 2018
@@ -98,6 +98,8 @@ public:
 
   void MacroUndefined(const Token &MacroNameTok, const MacroDefinition &MD,
   const MacroDirective *Undef) override {
+if (!MD.getMacroInfo())  // Ignore noop #undef.
+  return;
 IndexCtx->handleMacroUndefined(*MacroNameTok.getIdentifierInfo(),
MacroNameTok.getLocation(),
*MD.getMacroInfo());


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


[PATCH] D46317: [clang-tidy] New check bugprone-map-subscript-operator-lookup

2018-07-09 Thread Kalle Huttunen via Phabricator via cfe-commits
khuttun abandoned this revision.
khuttun added a comment.

Abandoning this. The false positive rate would be too high for this checker.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D46317



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


[PATCH] D48753: [libcxx] Use custom allocator's `construct` in C++03 when available.

2018-07-09 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai updated this revision to Diff 154678.
vsapsai added a comment.

- Allow allocator `construct` to return a value, not just have return type 
`void`.


https://reviews.llvm.org/D48753

Files:
  libcxx/include/memory
  
libcxx/test/std/containers/sequences/vector/vector.cons/construct_iter_iter.pass.cpp
  
libcxx/test/std/containers/sequences/vector/vector.cons/construct_iter_iter_alloc.pass.cpp
  libcxx/test/support/min_allocator.h

Index: libcxx/test/support/min_allocator.h
===
--- libcxx/test/support/min_allocator.h
+++ libcxx/test/support/min_allocator.h
@@ -14,6 +14,7 @@
 #include 
 #include 
 #include 
+#include 
 
 #include "test_macros.h"
 
@@ -131,6 +132,59 @@
 friend bool operator!=(malloc_allocator x, malloc_allocator y) {return !(x == y);}
 };
 
+template 
+struct cpp03_allocator : bare_allocator
+{
+typedef T value_type;
+typedef value_type* pointer;
+
+static bool construct_called;
+
+// Returned value is not used but it's not prohibited.
+pointer construct(pointer p, const value_type& val)
+{
+::new(p) value_type(val);
+construct_called = true;
+return p;
+}
+
+std::size_t max_size() const
+{
+return UINT_MAX / sizeof(T);
+}
+};
+template  bool cpp03_allocator::construct_called = false;
+
+template 
+struct cpp03_overload_allocator : bare_allocator
+{
+typedef T value_type;
+typedef value_type* pointer;
+
+static bool construct_called;
+
+void construct(pointer p, const value_type& val)
+{
+construct(p, val, std::is_class());
+}
+void construct(pointer p, const value_type& val, std::true_type)
+{
+::new(p) value_type(val);
+construct_called = true;
+}
+void construct(pointer p, const value_type& val, std::false_type)
+{
+::new(p) value_type(val);
+construct_called = true;
+}
+
+std::size_t max_size() const
+{
+return UINT_MAX / sizeof(T);
+}
+};
+template  bool cpp03_overload_allocator::construct_called = false;
+
 
 #if TEST_STD_VER >= 11
 
Index: libcxx/test/std/containers/sequences/vector/vector.cons/construct_iter_iter_alloc.pass.cpp
===
--- libcxx/test/std/containers/sequences/vector/vector.cons/construct_iter_iter_alloc.pass.cpp
+++ libcxx/test/std/containers/sequences/vector/vector.cons/construct_iter_iter_alloc.pass.cpp
@@ -129,9 +129,39 @@
 }
 
 void test_ctor_under_alloc() {
-#if TEST_STD_VER >= 11
   int arr1[] = {42};
   int arr2[] = {1, 101, 42};
+  {
+typedef std::vector > C;
+typedef C::allocator_type Alloc;
+Alloc a;
+{
+  Alloc::construct_called = false;
+  C v(arr1, arr1 + 1, a);
+  assert(Alloc::construct_called);
+}
+{
+  Alloc::construct_called = false;
+  C v(arr2, arr2 + 3, a);
+  assert(Alloc::construct_called);
+}
+  }
+  {
+typedef std::vector > C;
+typedef C::allocator_type Alloc;
+Alloc a;
+{
+  Alloc::construct_called = false;
+  C v(arr1, arr1 + 1, a);
+  assert(Alloc::construct_called);
+}
+{
+  Alloc::construct_called = false;
+  C v(arr2, arr2 + 3, a);
+  assert(Alloc::construct_called);
+}
+  }
+#if TEST_STD_VER >= 11
   {
 using C = TCT::vector<>;
 using T = typename C::value_type;
Index: libcxx/test/std/containers/sequences/vector/vector.cons/construct_iter_iter.pass.cpp
===
--- libcxx/test/std/containers/sequences/vector/vector.cons/construct_iter_iter.pass.cpp
+++ libcxx/test/std/containers/sequences/vector/vector.cons/construct_iter_iter.pass.cpp
@@ -116,9 +116,37 @@
 }
 
 void test_ctor_under_alloc() {
-#if TEST_STD_VER >= 11
   int arr1[] = {42};
   int arr2[] = {1, 101, 42};
+  {
+typedef std::vector > C;
+typedef C::allocator_type Alloc;
+{
+  Alloc::construct_called = false;
+  C v(arr1, arr1 + 1);
+  assert(Alloc::construct_called);
+}
+{
+  Alloc::construct_called = false;
+  C v(arr2, arr2 + 3);
+  assert(Alloc::construct_called);
+}
+  }
+  {
+typedef std::vector > C;
+typedef C::allocator_type Alloc;
+{
+  Alloc::construct_called = false;
+  C v(arr1, arr1 + 1);
+  assert(Alloc::construct_called);
+}
+{
+  Alloc::construct_called = false;
+  C v(arr2, arr2 + 3);
+  assert(Alloc::construct_called);
+}
+  }
+#if TEST_STD_VER >= 11
   {
 using C = TCT::vector<>;
 using T = typename C::value_type;
Index: libcxx/include/memory
===
--- libcxx/include/memory
+++ libcxx/include/memory
@@ -1459,23 +1459,18 @@
 
 #else  // _LIBCPP_CXX03_LANG
 
-#ifndef _LIBCPP_HAS_NO_VARIADICS
-
-template 
-struct __has_construct
-: false_type
-{
-};
-
-#else  // _LIBCPP_HAS_NO_VARIADICS
+template 
+struct __has_const

[PATCH] D45179: [libc++] Add _LIBCPP_FORCE_NODISCARD define to force-enable nodiscard in pre-C++17

2018-07-09 Thread Eric Fiselier via Phabricator via cfe-commits
EricWF commandeered this revision.
EricWF edited reviewers, added: lebedev.ri; removed: EricWF.
EricWF added a comment.

Hijacking with permission.


Repository:
  rL LLVM

https://reviews.llvm.org/D45179



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


[PATCH] D48786: [Preprocessor] Stop entering included files after hitting a fatal error.

2018-07-09 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added a comment.

Ping.


https://reviews.llvm.org/D48786



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


r336590 - [libclang] evalute compound statement cursors before trying to evaluate

2018-07-09 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Mon Jul  9 12:41:28 2018
New Revision: 336590

URL: http://llvm.org/viewvc/llvm-project?rev=336590&view=rev
Log:
[libclang] evalute compound statement cursors before trying to evaluate
the cursor like a declaration

This change fixes a bug in libclang in which it tries to evaluate a statement
cursor as a declaration cursor, because that statement still has a pointer to
the declaration parent.

rdar://3477

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

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

Modified: cfe/trunk/tools/libclang/CIndex.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/libclang/CIndex.cpp?rev=336590&r1=336589&r2=336590&view=diff
==
--- cfe/trunk/tools/libclang/CIndex.cpp (original)
+++ cfe/trunk/tools/libclang/CIndex.cpp Mon Jul  9 12:41:28 2018
@@ -3890,6 +3890,19 @@ static const ExprEvalResult* evaluateExp
 }
 
 CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
+  if (clang_getCursorKind(C) == CXCursor_CompoundStmt) {
+const CompoundStmt *compoundStmt = cast(getCursorStmt(C));
+Expr *expr = nullptr;
+for (auto *bodyIterator : compoundStmt->body()) {
+  if ((expr = dyn_cast(bodyIterator))) {
+break;
+  }
+}
+if (expr)
+  return const_cast(
+  reinterpret_cast(evaluateExpr(expr, C)));
+  }
+
   const Decl *D = getCursorDecl(C);
   if (D) {
 const Expr *expr = nullptr;
@@ -3903,19 +3916,6 @@ CXEvalResult clang_Cursor_Evaluate(CXCur
   evaluateExpr(const_cast(expr), C)));
 return nullptr;
   }
-
-  const CompoundStmt *compoundStmt = 
dyn_cast_or_null(getCursorStmt(C));
-  if (compoundStmt) {
-Expr *expr = nullptr;
-for (auto *bodyIterator : compoundStmt->body()) {
-  if ((expr = dyn_cast(bodyIterator))) {
-break;
-  }
-}
-if (expr)
-  return const_cast(
-  reinterpret_cast(evaluateExpr(expr, C)));
-  }
   return nullptr;
 }
 

Modified: cfe/trunk/unittests/libclang/LibclangTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/libclang/LibclangTest.cpp?rev=336590&r1=336589&r2=336590&view=diff
==
--- cfe/trunk/unittests/libclang/LibclangTest.cpp (original)
+++ cfe/trunk/unittests/libclang/LibclangTest.cpp Mon Jul  9 12:41:28 2018
@@ -461,6 +461,47 @@ TEST_F(LibclangParseTest, AllSkippedRang
   clang_disposeSourceRangeList(Ranges);
 }
 
+TEST_F(LibclangParseTest, EvaluateChildExpression) {
+  std::string Main = "main.m";
+  WriteFile(Main, "#define kFOO @\"foo\"\n"
+  "void foobar(void) {\n"
+  " {kFOO;}\n"
+  "}\n");
+  ClangTU = clang_parseTranslationUnit(Index, Main.c_str(), nullptr, 0, 
nullptr,
+   0, TUFlags);
+
+  CXCursor C = clang_getTranslationUnitCursor(ClangTU);
+  clang_visitChildren(
+  C,
+  [](CXCursor cursor, CXCursor parent,
+ CXClientData client_data) -> CXChildVisitResult {
+if (clang_getCursorKind(cursor) == CXCursor_FunctionDecl) {
+  int numberedStmt = 0;
+  clang_visitChildren(
+  cursor,
+  [](CXCursor cursor, CXCursor parent,
+ CXClientData client_data) -> CXChildVisitResult {
+int &numberedStmt = *((int *)client_data);
+if (clang_getCursorKind(cursor) == CXCursor_CompoundStmt) {
+  if (numberedStmt) {
+CXEvalResult RE = clang_Cursor_Evaluate(cursor);
+EXPECT_NE(RE, nullptr);
+EXPECT_EQ(clang_EvalResult_getKind(RE),
+  CXEval_ObjCStrLiteral);
+return CXChildVisit_Break;
+  }
+  numberedStmt++;
+}
+return CXChildVisit_Recurse;
+  },
+  &numberedStmt);
+  EXPECT_EQ(numberedStmt, 1);
+}
+return CXChildVisit_Continue;
+  },
+  nullptr);
+}
+
 class LibclangReparseTest : public LibclangParseTest {
 public:
   void DisplayDiagnostics() {


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


  1   2   >