[PATCH] D63856: [ObjC] Add a -Wtautological-compare warning for BOOL

2019-06-26 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

This only applies to relational operators, right?  I'm a little uncomfortable 
with calling this "tautological" since it's not like it's *undefined behavior* 
to have `(BOOL) 2`, it's just *unwise*.  But as long as we aren't warning about 
reasonable idioms that are intended to handle unfortunate situations — like 
other code that might have left a non-`{0,1}` value in the `BOOL` — I think 
this is fine.


Repository:
  rC Clang

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

https://reviews.llvm.org/D63856



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


[PATCH] D63753: [Sema] Instead of rejecting C unions with non-trivial fields, detect attempts to destruct/initialize/copy them.

2019-06-26 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: lib/Sema/SemaDecl.cpp:11085
+if (isa(I))
+  continue;
+if (auto E = dyn_cast(I))

ahatanak wrote:
> rjmccall wrote:
> > Why is this okay?  Don't we need to check default-initialization for these?
> I didn't consider an `ImplicitValueInitExpr` to be a default-initialization 
> since IRGen currently emits a memcpy to initialize the field instead of 
> calling a synthesized default-initialization function as it does when a local 
> variable that's a non-trivial C struct is declared without an initializer.
> 
> ```
> typedef struct {
>   id f0, f1;
> } S0 ;
> 
> typedef struct {
>   S0 s0;
>   int f2;
> } S;
> 
> void test(void) {
>   // emits a memcpy of a global constant.
>   S s = { .f2 = 1 };
> }
> ```
> 
> It's not clear to me whether this is a default-initialization, but if it is, 
> we should check default-initialization here and IRGen should be fixed to emit 
> a call to the default-initialization function.
C does not use the terms "default-initialization" and "value-initialization", 
but the the initialization performed for static/thread storage duration objects 
generally matches what C++ would call value-initialization.  These rules are 
laid out in section 6.7.9 of the standard, which also includes the following in 
its description of the rules for list-initializations of aggregates (regardless 
of their storage duration):

> p19: ...all subobjects that are not initialized explicitly shall be 
> initialized implicitly the same as objects that have static storage duration.

So `s.s0` must be initialized as if a static object (in C++ terms, 
value-initialized), not left with an indeterminate value like an object of 
automatic storage duration without an initializer would be (in C++ terms, 
default-initialized).

I assume that the default-initialization function for a non-trivial C struct 
only initializes the fields that have non-trivial default-initialization.  
That's not good enough for value-initialization, which is required to 
recursively value-initialize *all* of the fields (and even zero-initialize any 
padding).  Note that that's the *only* difference between these two kinds of 
initialization.  Furthermore, if you think about what default-initialization 
actually means for all our leaf non-trivial C types, it's just assigning a 
predictable bit-pattern (e.g. a null pointer for ARC's `__strong` and `__weak` 
references), not doing anything that requires executing tailored code at 
runtime.  So here's what that tells us:

- We can't call the default-initialization function because it might leave 
trivial fields uninitialized (in general, although `struct S0` in your example 
doesn't have any, so effectively it does a full value-initialization).

- `memcpy` from a global constant is always a valid implementation of 
value-initialization for non-trivial C types.  It's also a valid implementation 
for default-implementation; it just might do more than it really needs to.  (In 
the case of `struct S0`, it would be *more efficient* to use `memset`, but 
`memcpy` is still *valid*.)

  Now, maybe someday we'll add a non-trivial C type that really requires 
non-trivial code to initialize, but I doubt we'd want to, because we'd have to 
forbid e.g. declaring global variables of that type, and we wouldn't have a 
simple answer for telling people how to properly initialize a 
dynamically-allocated object.  Even if we do, we can wait until then to 
generalize.

- Regardless, yes, this is a value-initialization and so it should check 
whether we can value-initialize the type.  Since value-initialization just 
means default-initialization plus a bunch of zero-initialization (which we can 
assume we can always do), that just means checking whether we can 
default-initialize the type.


Repository:
  rC Clang

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

https://reviews.llvm.org/D63753



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


r364495 - [NFC] Return early for types with size zero

2019-06-26 Thread Vitaly Buka via cfe-commits
Author: vitalybuka
Date: Wed Jun 26 19:08:15 2019
New Revision: 364495

URL: http://llvm.org/viewvc/llvm-project?rev=364495=rev
Log:
[NFC] Return early for types with size zero

Modified:
cfe/trunk/lib/CodeGen/CGDecl.cpp

Modified: cfe/trunk/lib/CodeGen/CGDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDecl.cpp?rev=364495=364494=364495=diff
==
--- cfe/trunk/lib/CodeGen/CGDecl.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGDecl.cpp Wed Jun 26 19:08:15 2019
@@ -1145,6 +1145,10 @@ static void emitStoresForConstant(CodeGe
   CGBuilderTy ,
   llvm::Constant *constant) {
   auto *Ty = constant->getType();
+  uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
+  if (!ConstantSize)
+return;
+
   bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
   Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
   if (canDoSingleStore) {
@@ -1152,9 +1156,6 @@ static void emitStoresForConstant(CodeGe
 return;
   }
 
-  uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
-  if (!ConstantSize)
-return;
   auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize);
 
   // If the initializer is all or mostly the same, codegen with bzero / memset


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


r364492 - [NFC] Remove unneeded local variables

2019-06-26 Thread Vitaly Buka via cfe-commits
Author: vitalybuka
Date: Wed Jun 26 18:34:21 2019
New Revision: 364492

URL: http://llvm.org/viewvc/llvm-project?rev=364492=rev
Log:
[NFC] Remove unneeded local variables

Modified:
cfe/trunk/lib/CodeGen/CGDecl.cpp

Modified: cfe/trunk/lib/CodeGen/CGDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDecl.cpp?rev=364492=364491=364492=diff
==
--- cfe/trunk/lib/CodeGen/CGDecl.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGDecl.cpp Wed Jun 26 18:34:21 2019
@@ -1152,18 +1152,15 @@ static void emitStoresForConstant(CodeGe
 return;
   }
 
-  auto *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
-  auto *IntPtrTy = CGM.getDataLayout().getIntPtrType(CGM.getLLVMContext());
-
   uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
   if (!ConstantSize)
 return;
-  auto *SizeVal = llvm::ConstantInt::get(IntPtrTy, ConstantSize);
+  auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize);
 
   // If the initializer is all or mostly the same, codegen with bzero / memset
   // then do a few stores afterward.
   if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
-Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
+Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0), SizeVal,
  isVolatile);
 
 bool valueAlreadyCorrect =
@@ -1184,7 +1181,7 @@ static void emitStoresForConstant(CodeGe
   assert(AP.getBitWidth() <= 8);
   Value = AP.getLimitedValue();
 }
-Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, Value), SizeVal,
+Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), 
SizeVal,
  isVolatile);
 return;
   }
@@ -1672,8 +1669,6 @@ void CodeGenFunction::EmitAutoVarInit(co
   auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, 
D.getLocation());
   QualType type = D.getType();
 
-  bool isVolatile = type.isVolatileQualified();
-
   // If this local has an initializer, emit it now.
   const Expr *Init = D.getInit();
 
@@ -1728,6 +1723,7 @@ void CodeGenFunction::EmitAutoVarInit(co
 if (emission.IsEscapingByRef && !locIsByrefHeader)
   Loc = emitBlockByrefAddress(Loc, , /*follow=*/false);
 
+bool isVolatile = type.isVolatileQualified();
 CharUnits Size = getContext().getTypeSizeInChars(type);
 if (!Size.isZero()) {
   switch (trivialAutoVarInit) {
@@ -1849,7 +1845,7 @@ void CodeGenFunction::EmitAutoVarInit(co
   llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
   emitStoresForConstant(
   CGM, D, (Loc.getType() == BP) ? Loc : Builder.CreateBitCast(Loc, BP),
-  isVolatile, Builder, constant);
+  type.isVolatileQualified(), Builder, constant);
 }
 
 /// Emit an expression as an initializer for an object (variable, field, etc.)


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


[PATCH] D63753: [Sema] Instead of rejecting C unions with non-trivial fields, detect attempts to destruct/initialize/copy them.

2019-06-26 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak marked 2 inline comments as done.
ahatanak added inline comments.



Comment at: include/clang/Sema/Sema.h:2126
+NTCUC_AutoVar,
+// Initializer expression for object with automatic storage duration.
+NTCUC_AutoObjInit,

rjmccall wrote:
> Please expand this comment to clarify that this it's only used when we (might 
> be) initializing an object by copying another.
> 
> Why is this specific to automatic storage duration?  Just because C doesn't 
> allow other initializers to be non-constant in the first place?
Yes, that was my reasoning. We want to reject copy initializations of 
non-trivial C unions with automatic storage duration since the compiler doesn't 
know how to do the copy, but I don't think variables with static duration have 
that problem since the initializers are constant, which enables them to be 
initialized according to the rules described in the C standard.



Comment at: lib/Sema/SemaDecl.cpp:11085
+if (isa(I))
+  continue;
+if (auto E = dyn_cast(I))

rjmccall wrote:
> Why is this okay?  Don't we need to check default-initialization for these?
I didn't consider an `ImplicitValueInitExpr` to be a default-initialization 
since IRGen currently emits a memcpy to initialize the field instead of calling 
a synthesized default-initialization function as it does when a local variable 
that's a non-trivial C struct is declared without an initializer.

```
typedef struct {
  id f0, f1;
} S0 ;

typedef struct {
  S0 s0;
  int f2;
} S;

void test(void) {
  // emits a memcpy of a global constant.
  S s = { .f2 = 1 };
}
```

It's not clear to me whether this is a default-initialization, but if it is, we 
should check default-initialization here and IRGen should be fixed to emit a 
call to the default-initialization function.


Repository:
  rC Clang

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

https://reviews.llvm.org/D63753



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


[PATCH] D63857: [clang-doc] Structured HTML generator

2019-06-26 Thread Julie Hockett via Phabricator via cfe-commits
juliehockett added inline comments.



Comment at: clang-tools-extra/clang-doc/HTMLGenerator.cpp:21
 
+class HTMLTag {
+public:

Put the class definitions in an anonymous namespace 
(https://llvm.org/docs/CodingStandards.html#anonymous-namespaces)



Comment at: clang-tools-extra/clang-doc/HTMLGenerator.cpp:24
+  // Any other tag can be added if required
+  enum Tag {
+meta,

Use `TagType` or some such to avoid confusion with the containing class



Comment at: clang-tools-extra/clang-doc/HTMLGenerator.cpp:25-33
+meta,
+title,
+div,
+h1,
+h2,
+h3,
+p,

Enum values should be capitalized, and probably prefixed with HTML_ or TAG_ or 
some such useful prefix (e.g. TAG_META)



Comment at: clang-tools-extra/clang-doc/HTMLGenerator.cpp:42
+
+  bool IsSelfClosing() const {
+switch (Value) {

For this and other functions, separate the implementation from the definition.



Comment at: clang-tools-extra/clang-doc/HTMLGenerator.cpp:121
+struct TagNode : public HTMLNode {
+  TagNode(HTMLTag Tag) : Tag(Tag) {
+InlineChildren = Tag.HasInlineChildren();

```TagNode(HTMLTag Tag) : Tag(Tag), InlineChildren(Tag.HasInlineChildren), 
SelfClosing(Tag.SelfClosing) {}```



Comment at: clang-tools-extra/clang-doc/HTMLGenerator.cpp:412
+
+  F.Children.push_back(llvm::make_unique(HTMLTag::title, InfoTitle));
+  F.Children.push_back(std::move(MainContentNode));

use `emplace_back` here for instantiation



Comment at: clang-tools-extra/clang-doc/MDGenerator.cpp:31
 
-static void writeLine(const Twine , raw_ostream ) {
+void writeLine(const Twine , raw_ostream ) {
   OS << Text << "\n\n";

Can you re-static these?


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

https://reviews.llvm.org/D63857



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


[PATCH] D63180: [clang-doc] Adds HTML generator

2019-06-26 Thread Diego Astiazarán via Phabricator via cfe-commits
DiegoAstiazaran marked 4 inline comments as done.
DiegoAstiazaran added inline comments.



Comment at: clang-tools-extra/clang-doc/HTMLGenerator.cpp:106-107
+
+  std::string Buffer;
+  llvm::raw_string_ostream Members(Buffer);
+  if (!I.Members.empty())

jakehehrlich wrote:
> This is a generally bad pattern.
Some of the uses of an intermediate ostream have been deleted but I consider 
that some are still useful.
One of them is the when rendering the list of Enum Members, after generating a 
list of 's, we require the intermediate ostream to put it between the ul 
tags. I consider that's better than:

```
OS << "\n";
for (...)
  OS << ...;
OS << "\n";
```


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

https://reviews.llvm.org/D63180



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


[PATCH] D63857: [clang-doc] Structured HTML generator

2019-06-26 Thread Diego Astiazarán via Phabricator via cfe-commits
DiegoAstiazaran created this revision.
DiegoAstiazaran added reviewers: juliehockett, jakehehrlich, lebedev.ri.
DiegoAstiazaran added a project: clang-tools-extra.

Nodes are used to represent each part of the HTML file. There are TagNodes that 
represent every HTML tag (p, h1, div, ...) and they have children nodes, which 
can be TagNodes or TextNodes (these nodes only have text).
Proper indentation is now rendered within the file.

Depends on D63180 .


https://reviews.llvm.org/D63857

Files:
  clang-tools-extra/clang-doc/HTMLGenerator.cpp
  clang-tools-extra/clang-doc/MDGenerator.cpp
  clang-tools-extra/unittests/clang-doc/HTMLGeneratorTest.cpp

Index: clang-tools-extra/unittests/clang-doc/HTMLGeneratorTest.cpp
===
--- clang-tools-extra/unittests/clang-doc/HTMLGeneratorTest.cpp
+++ clang-tools-extra/unittests/clang-doc/HTMLGeneratorTest.cpp
@@ -40,16 +40,31 @@
   llvm::raw_string_ostream Actual(Buffer);
   auto Err = G->generateDocForInfo(, Actual);
   assert(!Err);
-  std::string Expected = R"raw(namespace Namespace
-Namespaces
-ChildNamespace
-Records
-ChildStruct
-Functions
-OneFunction
- OneFunction()
-Enums
-enum OneEnum
+  std::string Expected = R"raw(
+
+namespace Namespace
+
+  namespace Namespace
+  Namespaces
+  
+ChildNamespace
+  
+  Records
+  
+ChildStruct
+  
+  Functions
+  
+OneFunction
+
+   OneFunction()
+
+  
+  Enums
+  
+enum OneEnum
+  
+
 )raw";
 
   EXPECT_EQ(Expected, Actual.str());
@@ -80,18 +95,37 @@
   llvm::raw_string_ostream Actual(Buffer);
   auto Err = G->generateDocForInfo(, Actual);
   assert(!Err);
-  std::string Expected = R"raw(class r
-Defined at line 10 of test.cpp
-Inherits from F, G
-Members
-private int X
-Records
-ChildStruct
-Functions
-OneFunction
- OneFunction()
-Enums
-enum OneEnum
+  std::string Expected = R"raw(
+
+class r
+
+  class r
+  
+Defined at line 10 of test.cpp
+  
+  
+Inherits from F, G
+  
+  Members
+  
+private int X
+  
+  Records
+  
+ChildStruct
+  
+  Functions
+  
+OneFunction
+
+   OneFunction()
+
+  
+  Enums
+  
+enum OneEnum
+  
+
 )raw";
 
   EXPECT_EQ(Expected, Actual.str());
@@ -116,9 +150,18 @@
   llvm::raw_string_ostream Actual(Buffer);
   auto Err = G->generateDocForInfo(, Actual);
   assert(!Err);
-  std::string Expected = R"raw(f
-void f(int P)
-Defined at line 10 of test.cpp
+  std::string Expected = R"raw(
+
+
+
+  f
+  
+void f(int P)
+  
+  
+Defined at line 10 of test.cpp
+  
+
 )raw";
 
   EXPECT_EQ(Expected, Actual.str());
@@ -141,11 +184,18 @@
   llvm::raw_string_ostream Actual(Buffer);
   auto Err = G->generateDocForInfo(, Actual);
   assert(!Err);
-  std::string Expected = R"raw(enum class e
-
-X
-
-Defined at line 10 of test.cpp
+  std::string Expected = R"raw(
+
+
+
+  enum class e
+  
+X
+  
+  
+Defined at line 10 of test.cpp
+  
+
 )raw";
 
   EXPECT_EQ(Expected, Actual.str());
@@ -194,12 +244,29 @@
   llvm::raw_string_ostream Actual(Buffer);
   auto Err = G->generateDocForInfo(, Actual);
   assert(!Err);
-  std::string Expected = R"raw(f
-void f(int I, int J)
-Defined at line 10 of test.cpp
-
- Brief description.
- Extended description that continues onto the next line.
+  std::string Expected = R"raw(
+
+
+
+  f
+  
+void f(int I, int J)
+  
+  
+Defined at line 10 of test.cpp
+  
+  
+
+  
+ Brief description.
+  
+  
+ Extended description that
+ continues onto the next line.
+  
+
+  
+
 )raw";
 
   EXPECT_EQ(Expected, Actual.str());
Index: clang-tools-extra/clang-doc/MDGenerator.cpp
===
--- clang-tools-extra/clang-doc/MDGenerator.cpp
+++ clang-tools-extra/clang-doc/MDGenerator.cpp
@@ -28,23 +28,23 @@
   return "[" + Text.str() + "](" + Link.str() + ")";
 }
 
-static void writeLine(const Twine , raw_ostream ) {
+void writeLine(const Twine , raw_ostream ) {
   OS << Text << "\n\n";
 }
 
-static void writeNewLine(raw_ostream ) { OS << "\n\n"; }
+void writeNewLine(raw_ostream ) { OS << "\n\n"; }
 
-static void writeHeader(const Twine , unsigned int Num, raw_ostream ) {
+void writeHeader(const Twine , unsigned int Num, raw_ostream ) {
   OS << std::string(Num, '#') + " " + Text << "\n\n";
 }
 
-static void writeFileDefinition(const Location , raw_ostream ) {
+void writeFileDefinition(const Location , raw_ostream ) {
   OS << genItalic("Defined at line " + std::to_string(L.LineNumber) + " of " +
   L.Filename)
  << "\n\n";
 }
 
-static void writeDescription(const CommentInfo , raw_ostream ) {
+void writeDescription(const CommentInfo , raw_ostream ) {
   if (I.Kind == "FullComment") {
 for (const auto  : I.Children)
   writeDescription(*Child, OS);
Index: clang-tools-extra/clang-doc/HTMLGenerator.cpp
===
--- 

[PATCH] D63856: [ObjC] Add a -Wtautological-compare warning for BOOL

2019-06-26 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington created this revision.
erik.pilkington added reviewers: rjmccall, steven_wu, rsmith.
Herald added subscribers: dexonsmith, jkorous.
Herald added a project: clang.

On macOS, BOOL is a typedef for signed char, but it should never hold a value 
that isn't 1 or 0. Any code that expects a different value in their BOOL should 
be fixed.

rdar://problem/51954400 ObjC: Add diagnostics to catch incorrect usage of BOOL


Repository:
  rC Clang

https://reviews.llvm.org/D63856

Files:
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/tautological-objc-bool-compare.m

Index: clang/test/Sema/tautological-objc-bool-compare.m
===
--- /dev/null
+++ clang/test/Sema/tautological-objc-bool-compare.m
@@ -0,0 +1,24 @@
+// RUN: %clang_cc1 %s -verify
+
+typedef signed char BOOL;
+#define YES __objc_yes
+#define NO __objc_no
+
+BOOL B;
+
+void test() {
+  int r;
+  r = B > 0;
+  r = B > 1; // expected-warning {{result of comparison of constant 1 with expression of type BOOL is always false, as the only well defined values for BOOL are YES and NO}}
+  r = B < 1;
+  r = B < 0; // expected-warning {{result of comparison of constant 0 with expression of type BOOL is always false, as the only well defined values for BOOL are YES and NO}}
+  r = B >= 0; // expected-warning {{result of comparison of constant 0 with expression of type BOOL is always true, as the only well defined values for BOOL are YES and NO}}
+  r = B <= 0;
+
+  r = B > YES; // expected-warning {{result of comparison of constant YES with expression of type BOOL is always false, as the only well defined values for BOOL are YES and NO}}
+  r = B > NO;
+  r = B < NO; // expected-warning {{result of comparison of constant NO with expression of type BOOL is always false, as the only well defined values for BOOL are YES and NO}}
+  r = B < YES;
+  r = B >= NO; // expected-warning {{result of comparison of constant NO with expression of type BOOL is always true, as the only well defined values for BOOL are YES and NO}}
+  r = B <= NO;
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -10193,9 +10193,16 @@
 if (isa(DR->getDecl()))
   return true;
 
-  // Suppress cases where the '0' value is expanded from a macro.
-  if (E->getBeginLoc().isMacroID())
-return true;
+  // Suppress cases where the value is expanded from a macro, unless that macro
+  // is how a language represents a boolean literal. This is the case in both C
+  // and Objective-C.
+  SourceLocation BeginLoc = E->getBeginLoc();
+  if (BeginLoc.isMacroID()) {
+StringRef MacroName = Lexer::getImmediateMacroName(
+BeginLoc, S.getSourceManager(), S.getLangOpts());
+return MacroName != "YES" && MacroName != "NO" &&
+   MacroName != "true" && MacroName != "false";
+  }
 
   return false;
 }
@@ -10387,11 +10394,17 @@
 OtherT = AT->getValueType();
   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
 
+  // Special case for ObjC BOOL on targets where its a typedef for a signed char
+  // (Namely, macOS).
+  bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
+  S.NSAPIObj->isObjCBOOLType(OtherT) &&
+  OtherT->isSpecificBuiltinType(BuiltinType::SChar);
+
   // Whether we're treating Other as being a bool because of the form of
   // expression despite it having another type (typically 'int' in C).
   bool OtherIsBooleanDespiteType =
   !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
-  if (OtherIsBooleanDespiteType)
+  if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
 OtherRange = IntRange::forBoolType();
 
   // Determine the promoted range of the other type and see if a comparison of
@@ -10422,10 +10435,21 @@
   // Should be enough for uint128 (39 decimal digits)
   SmallString<64> PrettySourceValue;
   llvm::raw_svector_ostream OS(PrettySourceValue);
-  if (ED)
+  if (ED) {
 OS << '\'' << *ED << "' (" << Value << ")";
-  else
+  } else if (auto *BL = dyn_cast(
+   Constant->IgnoreParenImpCasts())) {
+OS << (BL->getValue() ? "YES" : "NO");
+  } else {
 OS << Value;
+  }
+
+  if (IsObjCSignedCharBool) {
+S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
+  S.PDiag(diag::warn_tautological_compare_objc_bool)
+  << OS.str() << *Result);
+return true;
+  }
 
   // FIXME: We use a somewhat different formatting for the in-range cases and
   // cases involving boolean values for historical reasons. We should pick a
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ 

[PATCH] D63854: [NFC] Convert large lambda into method

2019-06-26 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka updated this revision to Diff 206771.
vitalybuka added a comment.

remove unrelated file


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63854

Files:
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CodeGenFunction.h

Index: clang/lib/CodeGen/CodeGenFunction.h
===
--- clang/lib/CodeGen/CodeGenFunction.h
+++ clang/lib/CodeGen/CodeGenFunction.h
@@ -4195,6 +4195,9 @@
  llvm::Value *EmittedE,
  bool IsDynamic);
 
+  void emitZeroOrPatternForAutoVarInit(QualType type, const VarDecl ,
+   Address Loc);
+
 public:
 #ifndef NDEBUG
   // Determine whether the given argument is an Objective-C method
Index: clang/lib/CodeGen/CGDecl.cpp
===
--- clang/lib/CodeGen/CGDecl.cpp
+++ clang/lib/CodeGen/CGDecl.cpp
@@ -1662,6 +1662,87 @@
   return false;
 }
 
+void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
+  const VarDecl ,
+  Address Loc) {
+  auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
+  CharUnits Size = getContext().getTypeSizeInChars(type);
+  bool isVolatile = type.isVolatileQualified();
+  if (!Size.isZero()) {
+switch (trivialAutoVarInit) {
+case LangOptions::TrivialAutoVarInitKind::Uninitialized:
+  llvm_unreachable("Uninitialized handled by caller");
+case LangOptions::TrivialAutoVarInitKind::Zero:
+  emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
+  break;
+case LangOptions::TrivialAutoVarInitKind::Pattern:
+  emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
+  break;
+}
+return;
+  }
+
+  // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
+  // them, so emit a memcpy with the VLA size to initialize each element.
+  // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
+  // will catch that code, but there exists code which generates zero-sized
+  // VLAs. Be nice and initialize whatever they requested.
+  const auto *VlaType = getContext().getAsVariableArrayType(type);
+  if (!VlaType)
+return;
+  auto VlaSize = getVLASize(VlaType);
+  auto SizeVal = VlaSize.NumElts;
+  CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
+  switch (trivialAutoVarInit) {
+  case LangOptions::TrivialAutoVarInitKind::Uninitialized:
+llvm_unreachable("Uninitialized handled by caller");
+
+  case LangOptions::TrivialAutoVarInitKind::Zero:
+if (!EltSize.isOne())
+  SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
+Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
+ isVolatile);
+break;
+
+  case LangOptions::TrivialAutoVarInitKind::Pattern: {
+llvm::Type *ElTy = Loc.getElementType();
+llvm::Constant *Constant = constWithPadding(
+CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
+CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
+llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
+llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
+llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
+llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
+SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
+"vla.iszerosized");
+Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
+EmitBlock(SetupBB);
+if (!EltSize.isOne())
+  SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
+llvm::Value *BaseSizeInChars =
+llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
+Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin");
+llvm::Value *End =
+Builder.CreateInBoundsGEP(Begin.getPointer(), SizeVal, "vla.end");
+llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
+EmitBlock(LoopBB);
+llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
+Cur->addIncoming(Begin.getPointer(), OriginBB);
+CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
+Builder.CreateMemCpy(Address(Cur, CurAlign),
+ createUnnamedGlobalForMemcpyFrom(
+ CGM, D, Builder, Constant, ConstantAlign),
+ BaseSizeInChars, isVolatile);
+llvm::Value *Next =
+Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
+llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
+Builder.CreateCondBr(Done, ContBB, LoopBB);
+Cur->addIncoming(Next, LoopBB);
+EmitBlock(ContBB);
+  } break;
+  }
+};
+
 void CodeGenFunction::EmitAutoVarInit(const 

[PATCH] D63854: [NFC] Convert large lambda into method

2019-06-26 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka created this revision.
vitalybuka added a reviewer: pcc.
Herald added projects: clang, LLDB.
Herald added subscribers: lldb-commits, cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D63854

Files:
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  lldb/source/Symbol/LocateSymbolFileMacOSX.cpp

Index: lldb/source/Symbol/LocateSymbolFileMacOSX.cpp
===
--- lldb/source/Symbol/LocateSymbolFileMacOSX.cpp
+++ lldb/source/Symbol/LocateSymbolFileMacOSX.cpp
@@ -9,7 +9,6 @@
 #include "lldb/Symbol/LocateSymbolFile.h"
 
 #include 
-#include 
 #include 
 
 #include 
@@ -38,8 +37,14 @@
 using namespace lldb;
 using namespace lldb_private;
 
-static CFURLRef (*g_dlsym_DBGCopyFullDSYMURLForUUID)(CFUUIDRef uuid, CFURLRef exec_url) = nullptr;
-static CFDictionaryRef (*g_dlsym_DBGCopyDSYMPropertyLists)(CFURLRef dsym_url) = nullptr;
+#if !defined(__arm__) && !defined(__arm64__) &&\
+!defined(__aarch64__) // No DebugSymbols on the iOS devices
+extern "C" {
+
+CFURLRef DBGCopyFullDSYMURLForUUID(CFUUIDRef uuid, CFURLRef exec_url);
+CFDictionaryRef DBGCopyDSYMPropertyLists(CFURLRef dsym_url);
+}
+#endif
 
 int LocateMacOSXFilesUsingDebugSymbols(const ModuleSpec _spec,
ModuleSpec _module_spec) {
@@ -56,19 +61,8 @@
 
   int items_found = 0;
 
-  if (g_dlsym_DBGCopyFullDSYMURLForUUID == nullptr ||
-  g_dlsym_DBGCopyDSYMPropertyLists == nullptr) {
-void *handle = dlopen ("/System/Library/PrivateFrameworks/DebugSymbols.framework/DebugSymbols", RTLD_LAZY | RTLD_LOCAL);
-if (handle) {
-  g_dlsym_DBGCopyFullDSYMURLForUUID = (CFURLRef (*)(CFUUIDRef, CFURLRef)) dlsym (handle, "DBGCopyFullDSYMURLForUUID");
-  g_dlsym_DBGCopyDSYMPropertyLists = (CFDictionaryRef (*)(CFURLRef)) dlsym (handle, "DBGCopyDSYMPropertyLists");
-}
-  }
-
-  if (g_dlsym_DBGCopyFullDSYMURLForUUID == nullptr ||
-  g_dlsym_DBGCopyDSYMPropertyLists == nullptr) {
-return items_found;
-  }
+#if !defined(__arm__) && !defined(__arm64__) &&\
+!defined(__aarch64__) // No DebugSymbols on the iOS devices
 
   const UUID *uuid = module_spec.GetUUIDPtr();
   const ArchSpec *arch = module_spec.GetArchitecturePtr();
@@ -95,7 +89,7 @@
 }
 
 CFCReleaser dsym_url(
-g_dlsym_DBGCopyFullDSYMURLForUUID(module_uuid_ref.get(), exec_url.get()));
+::DBGCopyFullDSYMURLForUUID(module_uuid_ref.get(), exec_url.get()));
 char path[PATH_MAX];
 
 if (dsym_url.get()) {
@@ -131,7 +125,7 @@
   }
 
   CFCReleaser dict(
-  g_dlsym_DBGCopyDSYMPropertyLists(dsym_url.get()));
+  ::DBGCopyDSYMPropertyLists(dsym_url.get()));
   CFDictionaryRef uuid_dict = NULL;
   if (dict.get()) {
 CFCString uuid_cfstr(uuid->GetAsString().c_str());
@@ -242,6 +236,8 @@
   }
 }
   }
+#endif // #if !defined (__arm__) && !defined (__arm64__) && !defined
+   // (__aarch64__)
 
   return items_found;
 }
Index: clang/lib/CodeGen/CodeGenFunction.h
===
--- clang/lib/CodeGen/CodeGenFunction.h
+++ clang/lib/CodeGen/CodeGenFunction.h
@@ -4195,6 +4195,9 @@
  llvm::Value *EmittedE,
  bool IsDynamic);
 
+  void emitZeroOrPatternForAutoVarInit(QualType type, const VarDecl ,
+   Address Loc);
+
 public:
 #ifndef NDEBUG
   // Determine whether the given argument is an Objective-C method
Index: clang/lib/CodeGen/CGDecl.cpp
===
--- clang/lib/CodeGen/CGDecl.cpp
+++ clang/lib/CodeGen/CGDecl.cpp
@@ -1662,6 +1662,87 @@
   return false;
 }
 
+void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
+  const VarDecl ,
+  Address Loc) {
+  auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
+  CharUnits Size = getContext().getTypeSizeInChars(type);
+  bool isVolatile = type.isVolatileQualified();
+  if (!Size.isZero()) {
+switch (trivialAutoVarInit) {
+case LangOptions::TrivialAutoVarInitKind::Uninitialized:
+  llvm_unreachable("Uninitialized handled by caller");
+case LangOptions::TrivialAutoVarInitKind::Zero:
+  emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
+  break;
+case LangOptions::TrivialAutoVarInitKind::Pattern:
+  emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
+  break;
+}
+return;
+  }
+
+  // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
+  // them, so emit a memcpy with the VLA size to initialize each element.
+  // Technically zero-sized or negative-sized VLAs are undefined, and 

[PATCH] D63852: [Clang] Move assembler into a separate file

2019-06-26 Thread Ayke via Phabricator via cfe-commits
aykevl updated this revision to Diff 206769.
aykevl added a comment.

- removed useless anonymous namespace


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63852

Files:
  clang/include/clang/Frontend/AssemblerInvocation.h
  clang/lib/Frontend/AssemblerInvocation.cpp
  clang/lib/Frontend/CMakeLists.txt
  clang/tools/driver/cc1as_main.cpp

Index: clang/tools/driver/cc1as_main.cpp
===
--- clang/tools/driver/cc1as_main.cpp
+++ clang/tools/driver/cc1as_main.cpp
@@ -15,6 +15,7 @@
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Driver/Options.h"
+#include "clang/Frontend/AssemblerInvocation.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
 #include "clang/Frontend/TextDiagnosticPrinter.h"
 #include "clang/Frontend/Utils.h"
@@ -55,485 +56,8 @@
 #include 
 #include 
 using namespace clang;
-using namespace clang::driver;
-using namespace clang::driver::options;
-using namespace llvm;
 using namespace llvm::opt;
 
-namespace {
-
-/// Helper class for representing a single invocation of the assembler.
-struct AssemblerInvocation {
-  /// @name Target Options
-  /// @{
-
-  /// The name of the target triple to assemble for.
-  std::string Triple;
-
-  /// If given, the name of the target CPU to determine which instructions
-  /// are legal.
-  std::string CPU;
-
-  /// The list of target specific features to enable or disable -- this should
-  /// be a list of strings starting with '+' or '-'.
-  std::vector Features;
-
-  /// The list of symbol definitions.
-  std::vector SymbolDefs;
-
-  /// @}
-  /// @name Language Options
-  /// @{
-
-  std::vector IncludePaths;
-  unsigned NoInitialTextSection : 1;
-  unsigned SaveTemporaryLabels : 1;
-  unsigned GenDwarfForAssembly : 1;
-  unsigned RelaxELFRelocations : 1;
-  unsigned DwarfVersion;
-  std::string DwarfDebugFlags;
-  std::string DwarfDebugProducer;
-  std::string DebugCompilationDir;
-  std::map DebugPrefixMap;
-  llvm::DebugCompressionType CompressDebugSections =
-  llvm::DebugCompressionType::None;
-  std::string MainFileName;
-  std::string SplitDwarfOutput;
-
-  /// @}
-  /// @name Frontend Options
-  /// @{
-
-  std::string InputFile;
-  std::vector LLVMArgs;
-  std::string OutputPath;
-  enum FileType {
-FT_Asm,  ///< Assembly (.s) output, transliterate mode.
-FT_Null, ///< No output, for timing purposes.
-FT_Obj   ///< Object file output.
-  };
-  FileType OutputType;
-  unsigned ShowHelp : 1;
-  unsigned ShowVersion : 1;
-
-  /// @}
-  /// @name Transliterate Options
-  /// @{
-
-  unsigned OutputAsmVariant;
-  unsigned ShowEncoding : 1;
-  unsigned ShowInst : 1;
-
-  /// @}
-  /// @name Assembler Options
-  /// @{
-
-  unsigned RelaxAll : 1;
-  unsigned NoExecStack : 1;
-  unsigned FatalWarnings : 1;
-  unsigned IncrementalLinkerCompatible : 1;
-  unsigned EmbedBitcode : 1;
-
-  /// The name of the relocation model to use.
-  std::string RelocationModel;
-
-  /// The ABI targeted by the backend. Specified using -target-abi. Empty
-  /// otherwise.
-  std::string TargetABI;
-
-  /// @}
-
-public:
-  AssemblerInvocation() {
-Triple = "";
-NoInitialTextSection = 0;
-InputFile = "-";
-OutputPath = "-";
-OutputType = FT_Asm;
-OutputAsmVariant = 0;
-ShowInst = 0;
-ShowEncoding = 0;
-RelaxAll = 0;
-NoExecStack = 0;
-FatalWarnings = 0;
-IncrementalLinkerCompatible = 0;
-DwarfVersion = 0;
-EmbedBitcode = 0;
-  }
-
-  static bool CreateFromArgs(AssemblerInvocation ,
- ArrayRef Argv,
- DiagnosticsEngine );
-};
-
-}
-
-bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation ,
- ArrayRef Argv,
- DiagnosticsEngine ) {
-  bool Success = true;
-
-  // Parse the arguments.
-  std::unique_ptr OptTbl(createDriverOptTable());
-
-  const unsigned IncludedFlagsBitmask = options::CC1AsOption;
-  unsigned MissingArgIndex, MissingArgCount;
-  InputArgList Args = OptTbl->ParseArgs(Argv, MissingArgIndex, MissingArgCount,
-IncludedFlagsBitmask);
-
-  // Check for missing argument error.
-  if (MissingArgCount) {
-Diags.Report(diag::err_drv_missing_argument)
-<< Args.getArgString(MissingArgIndex) << MissingArgCount;
-Success = false;
-  }
-
-  // Issue errors on unknown arguments.
-  for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
-auto ArgString = A->getAsString(Args);
-std::string Nearest;
-if (OptTbl->findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
-  Diags.Report(diag::err_drv_unknown_argument) << ArgString;
-else
-  Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
-  << ArgString << Nearest;
-Success = false;
-  }
-
-  // Construct the invocation.

[PATCH] D63852: [Clang] Move assembler into a separate file

2019-06-26 Thread Ayke via Phabricator via cfe-commits
aykevl created this revision.
aykevl added a reviewer: chandlerc.
Herald added subscribers: cfe-commits, mgorny.
Herald added a project: clang.

This change adds an AssemblerInvocation class, similar to the 
CompilerInvocation class. It can be used to invoke cc1as directly.

The project I'm working on wants to compile Clang and use it as a static 
library. For that to work, there must be a way to invoke the assembler 
programmatically, using the same arguments as you would otherwise pass to cc1as.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D63852

Files:
  clang/include/clang/Frontend/AssemblerInvocation.h
  clang/lib/Frontend/AssemblerInvocation.cpp
  clang/lib/Frontend/CMakeLists.txt
  clang/tools/driver/cc1as_main.cpp

Index: clang/tools/driver/cc1as_main.cpp
===
--- clang/tools/driver/cc1as_main.cpp
+++ clang/tools/driver/cc1as_main.cpp
@@ -15,6 +15,7 @@
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Driver/Options.h"
+#include "clang/Frontend/AssemblerInvocation.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
 #include "clang/Frontend/TextDiagnosticPrinter.h"
 #include "clang/Frontend/Utils.h"
@@ -55,485 +56,10 @@
 #include 
 #include 
 using namespace clang;
-using namespace clang::driver;
-using namespace clang::driver::options;
-using namespace llvm;
 using namespace llvm::opt;
 
 namespace {
 
-/// Helper class for representing a single invocation of the assembler.
-struct AssemblerInvocation {
-  /// @name Target Options
-  /// @{
-
-  /// The name of the target triple to assemble for.
-  std::string Triple;
-
-  /// If given, the name of the target CPU to determine which instructions
-  /// are legal.
-  std::string CPU;
-
-  /// The list of target specific features to enable or disable -- this should
-  /// be a list of strings starting with '+' or '-'.
-  std::vector Features;
-
-  /// The list of symbol definitions.
-  std::vector SymbolDefs;
-
-  /// @}
-  /// @name Language Options
-  /// @{
-
-  std::vector IncludePaths;
-  unsigned NoInitialTextSection : 1;
-  unsigned SaveTemporaryLabels : 1;
-  unsigned GenDwarfForAssembly : 1;
-  unsigned RelaxELFRelocations : 1;
-  unsigned DwarfVersion;
-  std::string DwarfDebugFlags;
-  std::string DwarfDebugProducer;
-  std::string DebugCompilationDir;
-  std::map DebugPrefixMap;
-  llvm::DebugCompressionType CompressDebugSections =
-  llvm::DebugCompressionType::None;
-  std::string MainFileName;
-  std::string SplitDwarfOutput;
-
-  /// @}
-  /// @name Frontend Options
-  /// @{
-
-  std::string InputFile;
-  std::vector LLVMArgs;
-  std::string OutputPath;
-  enum FileType {
-FT_Asm,  ///< Assembly (.s) output, transliterate mode.
-FT_Null, ///< No output, for timing purposes.
-FT_Obj   ///< Object file output.
-  };
-  FileType OutputType;
-  unsigned ShowHelp : 1;
-  unsigned ShowVersion : 1;
-
-  /// @}
-  /// @name Transliterate Options
-  /// @{
-
-  unsigned OutputAsmVariant;
-  unsigned ShowEncoding : 1;
-  unsigned ShowInst : 1;
-
-  /// @}
-  /// @name Assembler Options
-  /// @{
-
-  unsigned RelaxAll : 1;
-  unsigned NoExecStack : 1;
-  unsigned FatalWarnings : 1;
-  unsigned IncrementalLinkerCompatible : 1;
-  unsigned EmbedBitcode : 1;
-
-  /// The name of the relocation model to use.
-  std::string RelocationModel;
-
-  /// The ABI targeted by the backend. Specified using -target-abi. Empty
-  /// otherwise.
-  std::string TargetABI;
-
-  /// @}
-
-public:
-  AssemblerInvocation() {
-Triple = "";
-NoInitialTextSection = 0;
-InputFile = "-";
-OutputPath = "-";
-OutputType = FT_Asm;
-OutputAsmVariant = 0;
-ShowInst = 0;
-ShowEncoding = 0;
-RelaxAll = 0;
-NoExecStack = 0;
-FatalWarnings = 0;
-IncrementalLinkerCompatible = 0;
-DwarfVersion = 0;
-EmbedBitcode = 0;
-  }
-
-  static bool CreateFromArgs(AssemblerInvocation ,
- ArrayRef Argv,
- DiagnosticsEngine );
-};
-
-}
-
-bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation ,
- ArrayRef Argv,
- DiagnosticsEngine ) {
-  bool Success = true;
-
-  // Parse the arguments.
-  std::unique_ptr OptTbl(createDriverOptTable());
-
-  const unsigned IncludedFlagsBitmask = options::CC1AsOption;
-  unsigned MissingArgIndex, MissingArgCount;
-  InputArgList Args = OptTbl->ParseArgs(Argv, MissingArgIndex, MissingArgCount,
-IncludedFlagsBitmask);
-
-  // Check for missing argument error.
-  if (MissingArgCount) {
-Diags.Report(diag::err_drv_missing_argument)
-<< Args.getArgString(MissingArgIndex) << MissingArgCount;
-Success = false;
-  }
-
-  // Issue errors on unknown arguments.
-  for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
-auto ArgString = A->getAsString(Args);
-

r364489 - [ObjC] Improve error message for a malformed objc-type-name

2019-06-26 Thread Erik Pilkington via cfe-commits
Author: epilk
Date: Wed Jun 26 16:39:23 2019
New Revision: 364489

URL: http://llvm.org/viewvc/llvm-project?rev=364489=rev
Log:
[ObjC] Improve error message for a malformed objc-type-name

If the type didn't exist, we used to emit a really bad error:

t.m:3:12: error: expected ')'
-(nullable NoSuchType)foo3;
   ^

rdar://50925632

Modified:
cfe/trunk/lib/Parse/ParseObjc.cpp
cfe/trunk/test/Parser/objc-interfaces.m
cfe/trunk/test/SemaObjC/invalid-typename.m

Modified: cfe/trunk/lib/Parse/ParseObjc.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseObjc.cpp?rev=364489=364488=364489=diff
==
--- cfe/trunk/lib/Parse/ParseObjc.cpp (original)
+++ cfe/trunk/lib/Parse/ParseObjc.cpp Wed Jun 26 16:39:23 2019
@@ -1247,11 +1247,11 @@ ParsedType Parser::ParseObjCTypeName(Obj
   BalancedDelimiterTracker T(*this, tok::l_paren);
   T.consumeOpen();
 
-  SourceLocation TypeStartLoc = Tok.getLocation();
   ObjCDeclContextSwitch ObjCDC(*this);
 
   // Parse type qualifiers, in, inout, etc.
   ParseObjCTypeQualifierList(DS, context);
+  SourceLocation TypeStartLoc = Tok.getLocation();
 
   ParsedType Ty;
   if (isTypeSpecifierQualifier() || isObjCInstancetype()) {

Modified: cfe/trunk/test/Parser/objc-interfaces.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Parser/objc-interfaces.m?rev=364489=364488=364489=diff
==
--- cfe/trunk/test/Parser/objc-interfaces.m (original)
+++ cfe/trunk/test/Parser/objc-interfaces.m Wed Jun 26 16:39:23 2019
@@ -6,3 +6,6 @@
 - (int*) foo2  __attribute__((deprecated)) : (int) x1 
__attribute__((deprecated)); // expected-error {{expected ';' after method 
prototype}} expected-error {{method type specifier must start with '-' or '+'}}
 @end
 
+@interface X
+-(nullable NoSuchType)foo3; // expected-error {{expected a type}}
+@end

Modified: cfe/trunk/test/SemaObjC/invalid-typename.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaObjC/invalid-typename.m?rev=364489=364488=364489=diff
==
--- cfe/trunk/test/SemaObjC/invalid-typename.m (original)
+++ cfe/trunk/test/SemaObjC/invalid-typename.m Wed Jun 26 16:39:23 2019
@@ -7,6 +7,6 @@
canBeginSyncingPlanWithId:(bycopy NSString *)planId
syncModes:(bycopy NSArray /* ISDSyncState */ *)syncModes
entities:(bycopy NSArray /* ISDEntity */ *)entities
-   truthPullers:(bycopy NSDictionary /* NSString -> [NSString] 
*/ *)truthPullers; // expected-error{{expected ')'}} expected-note {{to match 
this '('}}
+   truthPullers:(bycopy NSDictionary /* NSString -> [NSString] 
*/ *)truthPullers; // expected-error {{expected a type}}
 @end
 


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


[PATCH] D63845: [WIP] Create a clang attribute that lets users specify LLVM attributes

2019-06-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

What's the target use-case here? What can't be solved with normal attributes?
I wonder if this should go to cfe+llvm -dev lists first, it's kinda intrusive.
I also wonder if all these should cause a clang diagnostic, at least under 
`-Wall`.
How is versioning expected to be handled? New attribute vs old clang, and vice 
versa.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63845



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


[PATCH] D63845: [WIP] Create a clang attribute that lets users specify LLVM attributes

2019-06-26 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

Please add full context to the patches 
(http://llvm.org/docs/Phabricator.html#requesting-a-review-via-the-web-interface)
Also, some general comments inlined.




Comment at: clang/include/clang/Basic/Attr.td:1652
+  let Args = [StringArgument<"AttrName">];
+  let Documentation = [Undocumented];
+}

You will eventually need to add documentation for all three.



Comment at: clang/lib/CodeGen/CodeGenFunction.cpp:761
+}
+  }
+

Variable names: `VarName`
Comments and clang-format, please.
`assert` needs a text
Can we merge the common argument and return attribute code?
Why don't we need to parse the AttrKind for FnAttr?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63845



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


[PATCH] D63846: [clang] Preserve names of addrspacecast'ed values.

2019-06-26 Thread Vyacheslav Zakharin via Phabricator via cfe-commits
vzakhari created this revision.
vzakhari added a reviewer: rjmccall.
Herald added subscribers: cfe-commits, jfb, jvesely.
Herald added a project: clang.

Attach ".ascast" suffix to a value name when generating addrspacecast for it.  
This improves IR readability, e.g. for alloca variables, since all users of the 
variable will be using the addrspacecast value instead of the original alloca.


Repository:
  rC Clang

https://reviews.llvm.org/D63846

Files:
  clang/lib/CodeGen/TargetInfo.cpp
  clang/test/CodeGenCUDA/builtins-amdgcn.cu
  clang/test/CodeGenOpenCL/address-spaces-conversions.cl
  clang/test/CodeGenOpenCL/atomic-ops-libcall.cl
  clang/test/CodeGenOpenCLCXX/address-space-deduction.cl
  clang/test/CodeGenOpenCLCXX/addrspace-of-this.cl
  clang/test/CodeGenOpenCLCXX/addrspace-operators.cl
  clang/test/CodeGenOpenCLCXX/addrspace-references.cl
  clang/test/CodeGenOpenCLCXX/template-address-spaces.cl

Index: clang/test/CodeGenOpenCLCXX/template-address-spaces.cl
===
--- clang/test/CodeGenOpenCLCXX/template-address-spaces.cl
+++ clang/test/CodeGenOpenCLCXX/template-address-spaces.cl
@@ -13,12 +13,12 @@
 // CHECK: %struct.S.0 = type { i32 addrspace(4)* }
 // CHECK: %struct.S.1 = type { i32 addrspace(1)* }
 
-// CHECK:  %0 = addrspacecast %struct.S* %sint to %struct.S addrspace(4)*
-// CHECK:  %call = call i32 @_ZNU3AS41SIiE3fooEv(%struct.S addrspace(4)* %0) #1
-// CHECK:  %1 = addrspacecast %struct.S.0* %sintptr to %struct.S.0 addrspace(4)*
-// CHECK:  %call1 = call i32 addrspace(4)* @_ZNU3AS41SIPU3AS4iE3fooEv(%struct.S.0 addrspace(4)* %1) #1
-// CHECK:  %2 = addrspacecast %struct.S.1* %sintptrgl to %struct.S.1 addrspace(4)*
-// CHECK:  %call2 = call i32 addrspace(1)* @_ZNU3AS41SIPU3AS1iE3fooEv(%struct.S.1 addrspace(4)* %2) #1
+// CHECK:  [[A1:%sint.ascast[0-9]*]] = addrspacecast %struct.S* %sint to %struct.S addrspace(4)*
+// CHECK:  %call = call i32 @_ZNU3AS41SIiE3fooEv(%struct.S addrspace(4)* [[A1]]) #1
+// CHECK:  [[A2:%sintptr.ascast[0-9]*]] = addrspacecast %struct.S.0* %sintptr to %struct.S.0 addrspace(4)*
+// CHECK:  %call1 = call i32 addrspace(4)* @_ZNU3AS41SIPU3AS4iE3fooEv(%struct.S.0 addrspace(4)* [[A2]]) #1
+// CHECK:  [[A3:%sintptrgl.ascast[0-9]*]] = addrspacecast %struct.S.1* %sintptrgl to %struct.S.1 addrspace(4)*
+// CHECK:  %call2 = call i32 addrspace(1)* @_ZNU3AS41SIPU3AS1iE3fooEv(%struct.S.1 addrspace(4)* [[A3]]) #1
 
 void bar(){
   S sint;
Index: clang/test/CodeGenOpenCLCXX/addrspace-references.cl
===
--- clang/test/CodeGenOpenCLCXX/addrspace-references.cl
+++ clang/test/CodeGenOpenCLCXX/addrspace-references.cl
@@ -8,7 +8,7 @@
   // addrspacecast before passing the value to the function.
   // CHECK: [[REF:%.*]] = alloca i32
   // CHECK: store i32 1, i32* [[REF]]
-  // CHECK: [[REG:%[0-9]+]] = addrspacecast i32* [[REF]] to i32 addrspace(4)*
+  // CHECK: [[REG:%[.a-z0-9]+]] = addrspacecast i32* [[REF]] to i32 addrspace(4)*
   // CHECK: call spir_func i32 @_Z3barRU3AS4Kj(i32 addrspace(4)* dereferenceable(4) [[REG]])
   bar(1);
 }
Index: clang/test/CodeGenOpenCLCXX/addrspace-operators.cl
===
--- clang/test/CodeGenOpenCLCXX/addrspace-operators.cl
+++ clang/test/CodeGenOpenCLCXX/addrspace-operators.cl
@@ -19,11 +19,11 @@
 //CHECK-LABEL: define spir_func void @_Z3barv()
 void bar() {
   C c;
-  //CHECK: addrspacecast %class.C* %c to %class.C addrspace(4)*
-  //CHECK: call void @_ZNU3AS41C6AssignE1E(%class.C addrspace(4)* %{{[0-9]+}}, i32 0)
+  //CHECK: [[A1:%c.ascast[0-9]*]] = addrspacecast %class.C* %c to %class.C addrspace(4)*
+  //CHECK: call void @_ZNU3AS41C6AssignE1E(%class.C addrspace(4)* [[A1]], i32 0)
   c.Assign(a);
-  //CHECK: addrspacecast %class.C* %c to %class.C addrspace(4)*
-  //CHECK: call void @_ZNU3AS41C8OrAssignE1E(%class.C addrspace(4)* %{{[0-9]+}}, i32 0)
+  //CHECK: [[A2:%c.ascast[0-9]*]] = addrspacecast %class.C* %c to %class.C addrspace(4)*
+  //CHECK: call void @_ZNU3AS41C8OrAssignE1E(%class.C addrspace(4)* [[A2]], i32 0)
   c.OrAssign(a);
 
   E e;
Index: clang/test/CodeGenOpenCLCXX/addrspace-of-this.cl
===
--- clang/test/CodeGenOpenCLCXX/addrspace-of-this.cl
+++ clang/test/CodeGenOpenCLCXX/addrspace-of-this.cl
@@ -94,30 +94,30 @@
 // COMMON: call i32 @_ZNU3AS41C7outsideEv(%class.C addrspace(4)* addrspacecast (%class.C addrspace(1)* @c to %class.C addrspace(4)*))
 
 // Test the address space of 'this' when invoking copy-constructor.
-// COMMON: [[C1GEN:%[0-9]+]] = addrspacecast %class.C* %c1 to %class.C addrspace(4)*
+// COMMON: [[C1GEN:%c1.ascast[0-9]*]] = addrspacecast %class.C* %c1 to %class.C addrspace(4)*
 // IMPL: [[C1VOID:%[0-9]+]] = bitcast %class.C* %c1 to i8*
 // IMPL: call void @llvm.memcpy.p0i8.p4i8.i32(i8* {{.*}}[[C1VOID]], i8 addrspace(4)* {{.*}}addrspacecast (i8 addrspace(1)* bitcast (%class.C 

[PATCH] D63167: [Clang] Remove unused -split-dwarf and obsolete -enable-split-dwarf

2019-06-26 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert added a comment.

Thanks for the reviews!


Repository:
  rL LLVM

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

https://reviews.llvm.org/D63167



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


r364480 - Fix formatting after r364479

2019-06-26 Thread Aaron Puchert via cfe-commits
Author: aaronpuchert
Date: Wed Jun 26 14:39:19 2019
New Revision: 364480

URL: http://llvm.org/viewvc/llvm-project?rev=364480=rev
Log:
Fix formatting after r364479

The reflowing obscurs the functional changes, so here is a separate
commit.

Modified:
cfe/trunk/lib/CodeGen/CGDebugInfo.cpp

Modified: cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDebugInfo.cpp?rev=364480=364479=364480=diff
==
--- cfe/trunk/lib/CodeGen/CGDebugInfo.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.cpp Wed Jun 26 14:39:19 2019
@@ -614,10 +614,8 @@ void CGDebugInfo::CreateCompileUnit() {
   TheCU = DBuilder.createCompileUnit(
   LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? Producer : "",
   LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
-  CGOpts.DwarfDebugFlags, RuntimeVers,
-  CGOpts.SplitDwarfFile,
-  EmissionKind, DwoId, CGOpts.SplitDwarfInlining,
-  CGOpts.DebugInfoForProfiling,
+  CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
+  DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
   CGM.getTarget().getTriple().isNVPTX()
   ? llvm::DICompileUnit::DebugNameTableKind::None
   : static_cast(


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


[PATCH] D63845: [WIP] Create a clang attribute that lets users specify LLVM attributes

2019-06-26 Thread William Moses via Phabricator via cfe-commits
wsmoses updated this revision to Diff 206751.
wsmoses added a comment.
Herald added subscribers: llvm-commits, hiraditya.
Herald added a project: LLVM.

Actually upload full patch so far (and not just the last commit).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63845

Files:
  clang/include/clang/Basic/Attr.td
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/utils/TableGen/ClangAttrEmitter.cpp
  llvm/include/llvm/IR/Attributes.h
  llvm/lib/IR/Attributes.cpp
  llvm/lib/Transforms/IPO/ForceFunctionAttrs.cpp

Index: llvm/lib/Transforms/IPO/ForceFunctionAttrs.cpp
===
--- llvm/lib/Transforms/IPO/ForceFunctionAttrs.cpp
+++ llvm/lib/Transforms/IPO/ForceFunctionAttrs.cpp
@@ -24,48 +24,6 @@
  "example -force-attribute=foo:noinline. This "
  "option can be specified multiple times."));
 
-static Attribute::AttrKind parseAttrKind(StringRef Kind) {
-  return StringSwitch(Kind)
-  .Case("alwaysinline", Attribute::AlwaysInline)
-  .Case("builtin", Attribute::Builtin)
-  .Case("cold", Attribute::Cold)
-  .Case("convergent", Attribute::Convergent)
-  .Case("inlinehint", Attribute::InlineHint)
-  .Case("jumptable", Attribute::JumpTable)
-  .Case("minsize", Attribute::MinSize)
-  .Case("naked", Attribute::Naked)
-  .Case("nobuiltin", Attribute::NoBuiltin)
-  .Case("noduplicate", Attribute::NoDuplicate)
-  .Case("noimplicitfloat", Attribute::NoImplicitFloat)
-  .Case("noinline", Attribute::NoInline)
-  .Case("nonlazybind", Attribute::NonLazyBind)
-  .Case("noredzone", Attribute::NoRedZone)
-  .Case("noreturn", Attribute::NoReturn)
-  .Case("nocf_check", Attribute::NoCfCheck)
-  .Case("norecurse", Attribute::NoRecurse)
-  .Case("nounwind", Attribute::NoUnwind)
-  .Case("optforfuzzing", Attribute::OptForFuzzing)
-  .Case("optnone", Attribute::OptimizeNone)
-  .Case("optsize", Attribute::OptimizeForSize)
-  .Case("readnone", Attribute::ReadNone)
-  .Case("readonly", Attribute::ReadOnly)
-  .Case("argmemonly", Attribute::ArgMemOnly)
-  .Case("returns_twice", Attribute::ReturnsTwice)
-  .Case("safestack", Attribute::SafeStack)
-  .Case("shadowcallstack", Attribute::ShadowCallStack)
-  .Case("sanitize_address", Attribute::SanitizeAddress)
-  .Case("sanitize_hwaddress", Attribute::SanitizeHWAddress)
-  .Case("sanitize_memory", Attribute::SanitizeMemory)
-  .Case("sanitize_thread", Attribute::SanitizeThread)
-  .Case("speculative_load_hardening", Attribute::SpeculativeLoadHardening)
-  .Case("ssp", Attribute::StackProtect)
-  .Case("sspreq", Attribute::StackProtectReq)
-  .Case("sspstrong", Attribute::StackProtectStrong)
-  .Case("strictfp", Attribute::StrictFP)
-  .Case("uwtable", Attribute::UWTable)
-  .Default(Attribute::None);
-}
-
 /// If F has any forced attributes given on the command line, add them.
 static void addForcedAttributes(Function ) {
   for (auto  : ForceAttributes) {
@@ -73,7 +31,7 @@
 if (KV.first != F.getName())
   continue;
 
-auto Kind = parseAttrKind(KV.second);
+auto Kind = Attribute::parseAttrKind(KV.second);
 if (Kind == Attribute::None) {
   LLVM_DEBUG(dbgs() << "ForcedAttribute: " << KV.second
 << " unknown or not handled!\n");
Index: llvm/lib/IR/Attributes.cpp
===
--- llvm/lib/IR/Attributes.cpp
+++ llvm/lib/IR/Attributes.cpp
@@ -479,6 +479,48 @@
   llvm_unreachable("Unknown attribute");
 }
 
+Attribute::AttrKind Attribute::parseAttrKind(StringRef Kind) {
+  return StringSwitch(Kind)
+  .Case("alwaysinline", Attribute::AlwaysInline)
+  .Case("builtin", Attribute::Builtin)
+  .Case("cold", Attribute::Cold)
+  .Case("convergent", Attribute::Convergent)
+  .Case("inlinehint", Attribute::InlineHint)
+  .Case("jumptable", Attribute::JumpTable)
+  .Case("minsize", Attribute::MinSize)
+  .Case("naked", Attribute::Naked)
+  .Case("nobuiltin", Attribute::NoBuiltin)
+  .Case("noduplicate", Attribute::NoDuplicate)
+  .Case("noimplicitfloat", Attribute::NoImplicitFloat)
+  .Case("noinline", Attribute::NoInline)
+  .Case("nonlazybind", Attribute::NonLazyBind)
+  .Case("noredzone", Attribute::NoRedZone)
+  .Case("noreturn", Attribute::NoReturn)
+  .Case("nocf_check", Attribute::NoCfCheck)
+  .Case("norecurse", Attribute::NoRecurse)
+  .Case("nounwind", Attribute::NoUnwind)
+  .Case("optforfuzzing", Attribute::OptForFuzzing)
+  .Case("optnone", Attribute::OptimizeNone)
+  .Case("optsize", Attribute::OptimizeForSize)
+  .Case("readnone", Attribute::ReadNone)
+  .Case("readonly", Attribute::ReadOnly)
+  .Case("argmemonly", 

[PATCH] D63167: [Clang] Remove unused -split-dwarf and obsolete -enable-split-dwarf

2019-06-26 Thread Aaron Puchert via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL364479: [Clang] Remove unused -split-dwarf and obsolete 
-enable-split-dwarf (authored by aaronpuchert, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D63167?vs=204928=206750#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D63167

Files:
  cfe/trunk/include/clang/Basic/CodeGenOptions.def
  cfe/trunk/include/clang/Basic/CodeGenOptions.h
  cfe/trunk/include/clang/Driver/CC1Options.td
  cfe/trunk/lib/CodeGen/BackendUtil.cpp
  cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
  cfe/trunk/lib/Driver/ToolChains/Clang.cpp
  cfe/trunk/lib/Frontend/CompilerInvocation.cpp
  cfe/trunk/test/CodeGen/split-debug-filename.c
  cfe/trunk/test/CodeGen/split-debug-output.c
  cfe/trunk/test/CodeGen/split-debug-single-file.c
  cfe/trunk/test/Driver/split-debug.c

Index: cfe/trunk/include/clang/Driver/CC1Options.td
===
--- cfe/trunk/include/clang/Driver/CC1Options.td
+++ cfe/trunk/include/clang/Driver/CC1Options.td
@@ -230,8 +230,6 @@
   HelpText<"Do not emit code that uses the red zone.">;
 def dwarf_column_info : Flag<["-"], "dwarf-column-info">,
   HelpText<"Turn on column location information.">;
-def split_dwarf : Flag<["-"], "split-dwarf">,
-  HelpText<"Split out the dwarf .dwo sections">;
 def dwarf_ext_refs : Flag<["-"], "dwarf-ext-refs">,
   HelpText<"Generate debug info with external references to clang modules"
" or precompiled headers">;
@@ -694,10 +692,6 @@
   HelpText<"Weakly link in the blocks runtime">;
 def fexternc_nounwind : Flag<["-"], "fexternc-nounwind">,
   HelpText<"Assume all functions with C linkage do not unwind">;
-def enable_split_dwarf : Flag<["-"], "enable-split-dwarf">,
-  HelpText<"Use DWARF fission in 'split' mode">;
-def enable_split_dwarf_EQ : Joined<["-"], "enable-split-dwarf=">,
-  HelpText<"Set DWARF fission mode to either 'split' or 'single'">, Values<"split,single">;
 def split_dwarf_file : Separate<["-"], "split-dwarf-file">,
   HelpText<"Name of the split dwarf debug info file to encode in the object file">;
 def fno_wchar : Flag<["-"], "fno-wchar">,
Index: cfe/trunk/include/clang/Basic/CodeGenOptions.h
===
--- cfe/trunk/include/clang/Basic/CodeGenOptions.h
+++ cfe/trunk/include/clang/Basic/CodeGenOptions.h
@@ -71,8 +71,6 @@
 LocalExecTLSModel
   };
 
-  enum DwarfFissionKind { NoFission, SplitFileFission, SingleFileFission };
-
   /// Clang versions with different platform ABI conformance.
   enum class ClangABI {
 /// Attempt to be ABI-compatible with code generated by Clang 3.8.x
Index: cfe/trunk/include/clang/Basic/CodeGenOptions.def
===
--- cfe/trunk/include/clang/Basic/CodeGenOptions.def
+++ cfe/trunk/include/clang/Basic/CodeGenOptions.def
@@ -261,8 +261,6 @@
///< contain explicit imports for
///< anonymous namespaces
 
-ENUM_CODEGENOPT(SplitDwarfMode, DwarfFissionKind, 2, NoFission) ///< DWARF fission mode to use.
-
 CODEGENOPT(SplitDwarfInlining, 1, 1) ///< Whether to include inlining info in the
  ///< skeleton CU to allow for symbolication
  ///< of inline stack frames without .dwo files.
Index: cfe/trunk/test/Driver/split-debug.c
===
--- cfe/trunk/test/Driver/split-debug.c
+++ cfe/trunk/test/Driver/split-debug.c
@@ -13,7 +13,6 @@
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf=single -c -### %s 2> %t
 // RUN: FileCheck -check-prefix=CHECK-ACTIONS-SINGLE-SPLIT < %t %s
 //
-// CHECK-ACTIONS-SINGLE-SPLIT: "-enable-split-dwarf=single"
 // CHECK-ACTIONS-SINGLE-SPLIT: "-split-dwarf-file" "split-debug.o"
 // CHECK-ACTIONS-SINGLE-SPLIT-NOT: "-split-dwarf-output"
 
@@ -58,7 +57,6 @@
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -gmlt -fno-split-dwarf-inlining -S -### %s 2> %t
 // RUN: FileCheck -check-prefix=CHECK-GMLT-WITH-SPLIT < %t %s
 //
-// CHECK-GMLT-WITH-SPLIT: "-enable-split-dwarf"
 // CHECK-GMLT-WITH-SPLIT: "-debug-info-kind=line-tables-only"
 // CHECK-GMLT-WITH-SPLIT: "-split-dwarf-file"
 // CHECK-GMLT-WITH-SPLIT: "-split-dwarf-output"
@@ -66,28 +64,24 @@
 // RUN: %clang -target x86_64-unknown-linux-gnu -g -fno-split-dwarf-inlining -S -### %s 2> %t
 // RUN: FileCheck -check-prefix=CHECK-NOINLINE-WITHOUT-SPLIT < %t %s
 //
-// CHECK-NOINLINE-WITHOUT-SPLIT-NOT: "-enable-split-dwarf"
 // CHECK-NOINLINE-WITHOUT-SPLIT: "-fno-split-dwarf-inlining"
 // CHECK-NOINLINE-WITHOUT-SPLIT: "-debug-info-kind=limited"
 
 // RUN: %clang -target x86_64-unknown-linux-gnu -gmlt -gsplit-dwarf 

[PATCH] D63789: [ODRHash] Fix null pointer dereference for ObjC selectors with empty slots.

2019-06-26 Thread Richard Trieu via Phabricator via cfe-commits
rtrieu added inline comments.



Comment at: clang/lib/AST/ODRHash.cpp:73
 AddBoolean(S.isUnarySelector());
 unsigned NumArgs = S.getNumArgs();
 for (unsigned i = 0; i < NumArgs; ++i) {

vsapsai wrote:
> rtrieu wrote:
> > There's actually a second bug here as well.  When processing an arbitrary 
> > number of elements, the number of elements needs to placed before the list. 
> >  This line should be added before the for-loop:
> > 
> > ```
> > ID.AddInteger(NumArgs);
> > 
> > ```
> > This change isn't directly related to your original patch, so feel free to 
> > skip it.
> Thanks for the review, Richard. What would be the way to test the suggested 
> changes? I was mostly thinking about making sure we treat as different
> * `-foo:` and `-foo::`
> * `-foo:bar::` and `-foo::bar:`
> 
> Does it sound reasonable? Maybe you have some test examples for C++ that I 
> can adopt for Objective-C.
Yes, checking things close to each other sounds reasonable.   I did pretty much 
the same thing testing in C++, find things (usually types) that are close to 
others and making sure the ODRHash can tell them apart.  The ObjC testing is a 
little sparse since I was focusing on the C++ part.  Thanks for helping fill it 
out.


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

https://reviews.llvm.org/D63789



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


r364479 - [Clang] Remove unused -split-dwarf and obsolete -enable-split-dwarf

2019-06-26 Thread Aaron Puchert via cfe-commits
Author: aaronpuchert
Date: Wed Jun 26 14:36:35 2019
New Revision: 364479

URL: http://llvm.org/viewvc/llvm-project?rev=364479=rev
Log:
[Clang] Remove unused -split-dwarf and obsolete -enable-split-dwarf

Summary:
The changes in D59673 made the choice redundant, since we can achieve
single-file split DWARF just by not setting an output file name.
Like llc we can also derive whether to enable Split DWARF from whether
-split-dwarf-file is set, so we don't need the flag at all anymore.

The test CodeGen/split-debug-filename.c distinguished between having set
or not set -enable-split-dwarf with -split-dwarf-file, but we can
probably just always emit the metadata into the IR.

The flag -split-dwarf wasn't used at all anymore.

Reviewers: dblaikie, echristo

Reviewed By: dblaikie

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

Modified:
cfe/trunk/include/clang/Basic/CodeGenOptions.def
cfe/trunk/include/clang/Basic/CodeGenOptions.h
cfe/trunk/include/clang/Driver/CC1Options.td
cfe/trunk/lib/CodeGen/BackendUtil.cpp
cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
cfe/trunk/lib/Driver/ToolChains/Clang.cpp
cfe/trunk/lib/Frontend/CompilerInvocation.cpp
cfe/trunk/test/CodeGen/split-debug-filename.c
cfe/trunk/test/CodeGen/split-debug-output.c
cfe/trunk/test/CodeGen/split-debug-single-file.c
cfe/trunk/test/Driver/split-debug.c

Modified: cfe/trunk/include/clang/Basic/CodeGenOptions.def
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/CodeGenOptions.def?rev=364479=364478=364479=diff
==
--- cfe/trunk/include/clang/Basic/CodeGenOptions.def (original)
+++ cfe/trunk/include/clang/Basic/CodeGenOptions.def Wed Jun 26 14:36:35 2019
@@ -261,8 +261,6 @@ CODEGENOPT(DebugExplicitImport, 1, 0)  /
///< contain explicit imports for
///< anonymous namespaces
 
-ENUM_CODEGENOPT(SplitDwarfMode, DwarfFissionKind, 2, NoFission) ///< DWARF 
fission mode to use.
-
 CODEGENOPT(SplitDwarfInlining, 1, 1) ///< Whether to include inlining info in 
the
  ///< skeleton CU to allow for 
symbolication
  ///< of inline stack frames without .dwo 
files.

Modified: cfe/trunk/include/clang/Basic/CodeGenOptions.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/CodeGenOptions.h?rev=364479=364478=364479=diff
==
--- cfe/trunk/include/clang/Basic/CodeGenOptions.h (original)
+++ cfe/trunk/include/clang/Basic/CodeGenOptions.h Wed Jun 26 14:36:35 2019
@@ -71,8 +71,6 @@ public:
 LocalExecTLSModel
   };
 
-  enum DwarfFissionKind { NoFission, SplitFileFission, SingleFileFission };
-
   /// Clang versions with different platform ABI conformance.
   enum class ClangABI {
 /// Attempt to be ABI-compatible with code generated by Clang 3.8.x

Modified: cfe/trunk/include/clang/Driver/CC1Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/CC1Options.td?rev=364479=364478=364479=diff
==
--- cfe/trunk/include/clang/Driver/CC1Options.td (original)
+++ cfe/trunk/include/clang/Driver/CC1Options.td Wed Jun 26 14:36:35 2019
@@ -230,8 +230,6 @@ def disable_red_zone : Flag<["-"], "disa
   HelpText<"Do not emit code that uses the red zone.">;
 def dwarf_column_info : Flag<["-"], "dwarf-column-info">,
   HelpText<"Turn on column location information.">;
-def split_dwarf : Flag<["-"], "split-dwarf">,
-  HelpText<"Split out the dwarf .dwo sections">;
 def dwarf_ext_refs : Flag<["-"], "dwarf-ext-refs">,
   HelpText<"Generate debug info with external references to clang modules"
" or precompiled headers">;
@@ -694,10 +692,6 @@ def fblocks_runtime_optional : Flag<["-"
   HelpText<"Weakly link in the blocks runtime">;
 def fexternc_nounwind : Flag<["-"], "fexternc-nounwind">,
   HelpText<"Assume all functions with C linkage do not unwind">;
-def enable_split_dwarf : Flag<["-"], "enable-split-dwarf">,
-  HelpText<"Use DWARF fission in 'split' mode">;
-def enable_split_dwarf_EQ : Joined<["-"], "enable-split-dwarf=">,
-  HelpText<"Set DWARF fission mode to either 'split' or 'single'">, 
Values<"split,single">;
 def split_dwarf_file : Separate<["-"], "split-dwarf-file">,
   HelpText<"Name of the split dwarf debug info file to encode in the object 
file">;
 def fno_wchar : Flag<["-"], "fno-wchar">,

Modified: cfe/trunk/lib/CodeGen/BackendUtil.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/BackendUtil.cpp?rev=364479=364478=364479=diff
==
--- cfe/trunk/lib/CodeGen/BackendUtil.cpp (original)
+++ cfe/trunk/lib/CodeGen/BackendUtil.cpp Wed Jun 26 14:36:35 2019
@@ -473,8 +473,7 @@ static void 

[PATCH] D63048: Update __VERSION__ to remove the hardcoded 4.2.1 version

2019-06-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In D63048#1559894 , @lebedev.ri wrote:

> In D63048#1559880 , @dexonsmith 
> wrote:
>
> > In D63048#1558806 , 
> > @sylvestre.ledru wrote:
> >
> > > @dexonsmith ping?
> >
> >
> > ...
>
>
>
>
> > FWIW, I feel similarly about `-dumpversion` (better to remove it than 
> > change it).
>
> What does CMake use to detect compiler (well, clang) version?


Spoke too soon, clearly not that.


Repository:
  rC Clang

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

https://reviews.llvm.org/D63048



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


[PATCH] D63845: [WIP] Create a clang attribute that lets users specify LLVM attributes

2019-06-26 Thread William Moses via Phabricator via cfe-commits
wsmoses created this revision.
wsmoses added a reviewer: jdoerfert.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This (work in progress) diff adds three new attributes to clang 
(__attribute__((LLVMFN(string))), __attribute__((LLVMARG(paramidx, string))), 
__attribute__((LLVMRET(paramidx, string))) ) for passing attributes down to 
LLVM.

This is useful for allowing users, tools, or test cases to specify LLVM 
attributes that may not have a representation in clang.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D63845

Files:
  clang/include/clang/Basic/Attr.td
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/utils/TableGen/ClangAttrEmitter.cpp

Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -1290,6 +1290,8 @@
 Ptr = llvm::make_unique(Arg, Attr);
   else if (ArgName == "VariadicParamOrParamIdxArgument")
 Ptr = llvm::make_unique(Arg, Attr);
+  else if (ArgName == "ParamOrParamIdxArgument")
+Ptr = llvm::make_unique(Arg, Attr, "int");
   else if (ArgName == "ParamIdxArgument")
 Ptr = llvm::make_unique(Arg, Attr, "ParamIdx");
   else if (ArgName == "VariadicIdentifierArgument")
@@ -2184,6 +2186,7 @@
  llvm::StringSwitch(
  Arg->getSuperClasses().back().first->getName())
  .Case("VariadicParamOrParamIdxArgument", true)
+ .Case("ParamOrParamIdxArgument", true)
  .Default(false);
 }
 
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -3456,20 +3456,9 @@
 D->addAttr(NewAttr);
 }
 
-/// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
-static void handleCallbackAttr(Sema , Decl *D, const ParsedAttr ) {
-  // The index that identifies the callback callee is mandatory.
-  if (AL.getNumArgs() == 0) {
-S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
-<< AL.getRange();
-return;
-  }
-
-  bool HasImplicitThisParam = isInstanceMethod(D);
-  int32_t NumArgs = getFunctionOrMethodNumParams(D);
-
-  FunctionDecl *FD = D->getAsFunction();
-  assert(FD && "Expected a function declaration!");
+static int32_t getParamFromNameOrIndex(Sema , FunctionDecl *FD, const ParsedAttr , unsigned I) {
+  bool HasImplicitThisParam = isInstanceMethod(FD);
+  int32_t NumArgs = getFunctionOrMethodNumParams(FD);
 
   llvm::StringMap NameIdxMapping;
   NameIdxMapping["__"] = -1;
@@ -3482,8 +3471,6 @@
 
   auto UnknownName = NameIdxMapping.end();
 
-  SmallVector EncodingIndices;
-  for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
 SourceRange SR;
 int32_t ArgIdx;
 
@@ -3493,7 +3480,7 @@
   if (It == UnknownName) {
 S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
 << IdLoc->Ident << IdLoc->Loc;
-return;
+return -1;
   }
 
   SR = SourceRange(IdLoc->Loc);
@@ -3506,14 +3493,14 @@
false)) {
 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
 << AL << (I + 1) << IdxExpr->getSourceRange();
-return;
+return -1;
   }
 
   // Check oob, excluding the special values, 0 and -1.
   if (ArgIdx < -1 || ArgIdx > NumArgs) {
 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
 << AL << (I + 1) << IdxExpr->getSourceRange();
-return;
+return -1;
   }
 
   SR = IdxExpr->getSourceRange();
@@ -3524,7 +3511,7 @@
 if (ArgIdx == 0 && !HasImplicitThisParam) {
   S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
   << (I + 1) << SR;
-  return;
+  return -1;
 }
 
 // Adjust for the case we do not have an implicit "this" parameter. In this
@@ -3532,9 +3519,31 @@
 if (!HasImplicitThisParam && ArgIdx > 0)
   ArgIdx -= 1;
 
+return ArgIdx;
+}
+
+/// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
+static void handleCallbackAttr(Sema , Decl *D, const ParsedAttr ) {
+  // The index that identifies the callback callee is mandatory.
+  if (AL.getNumArgs() == 0) {
+S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
+<< AL.getRange();
+return;
+  }
+
+
+  FunctionDecl *FD = D->getAsFunction();
+  assert(FD && "Expected a function declaration!");
+
+
+  SmallVector EncodingIndices;
+  for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
+int32_t ArgIdx = getParamFromNameOrIndex(S, FD, AL, I);
+if (ArgIdx == -1) return;
 EncodingIndices.push_back(ArgIdx);
   }
 
+  bool HasImplicitThisParam = isInstanceMethod(FD);
   int CalleeIdx = EncodingIndices.front();
   // Check if the callee index is proper, thus not "this" and not "unknown".
   

[PATCH] D63048: Update __VERSION__ to remove the hardcoded 4.2.1 version

2019-06-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In D63048#1559880 , @dexonsmith wrote:

> In D63048#1558806 , @sylvestre.ledru 
> wrote:
>
> > @dexonsmith ping?
>
>
> ...




> FWIW, I feel similarly about `-dumpversion` (better to remove it than change 
> it).

What does CMake use to detect compiler (well, clang) version?


Repository:
  rC Clang

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

https://reviews.llvm.org/D63048



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


[PATCH] D63048: Update __VERSION__ to remove the hardcoded 4.2.1 version

2019-06-26 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added a comment.

In D63048#1558806 , @sylvestre.ledru 
wrote:

> @dexonsmith ping?


I think I'd be a little more comfortable dropping `__VERSION__` entirely.  
There's already a way to access the clang version, and anyone with code that 
relies on `"4.2.1"` can just add a `-D__VERSION__=...` to their build rules to 
keep existing behaviour.

FWIW, I feel similarly about `-dumpversion` (better to remove it than change 
it).


Repository:
  rC Clang

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

https://reviews.llvm.org/D63048



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


r364476 - Revert r363191 "[MS] Pretend constexpr variable template specializations are inline"

2019-06-26 Thread Reid Kleckner via cfe-commits
Author: rnk
Date: Wed Jun 26 14:16:51 2019
New Revision: 364476

URL: http://llvm.org/viewvc/llvm-project?rev=364476=rev
Log:
Revert r363191 "[MS] Pretend constexpr variable template specializations are 
inline"

The next Visual Studio update will fix this issue, and it doesn't make
sense to implement this non-conforming behavior going forward.

Removed:
cfe/trunk/test/CodeGenCXX/ms-constexpr-var-template.cpp
Modified:
cfe/trunk/lib/AST/ASTContext.cpp

Modified: cfe/trunk/lib/AST/ASTContext.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTContext.cpp?rev=364476=364475=364476=diff
==
--- cfe/trunk/lib/AST/ASTContext.cpp (original)
+++ cfe/trunk/lib/AST/ASTContext.cpp Wed Jun 26 14:16:51 2019
@@ -9809,25 +9809,10 @@ static GVALinkage basicGVALinkageForVari
 return StrongLinkage;
 
   case TSK_ExplicitSpecialization:
-if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
-  // If this is a fully specialized constexpr variable template, pretend it
-  // was marked inline. MSVC 14.21.27702 headers define _Is_integral in a
-  // header this way, and we don't want to emit non-discardable definitions
-  // of these variables in every TU that includes . This
-  // behavior is non-conforming, since another TU could use an extern
-  // template declaration for this variable, but for constexpr variables,
-  // it's unlikely for a user to want to do that. This behavior can be
-  // removed if the headers change to explicitly mark such variable 
template
-  // specializations inline.
-  if (isa(VD) && VD->isConstexpr())
-return GVA_DiscardableODR;
-
-  // Use ODR linkage for static data members of fully specialized templates
-  // to prevent duplicate definition errors with MSVC.
-  if (VD->isStaticDataMember())
-return GVA_StrongODR;
-}
-return StrongLinkage;
+return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
+   VD->isStaticDataMember()
+   ? GVA_StrongODR
+   : StrongLinkage;
 
   case TSK_ExplicitInstantiationDefinition:
 return GVA_StrongODR;

Removed: cfe/trunk/test/CodeGenCXX/ms-constexpr-var-template.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/ms-constexpr-var-template.cpp?rev=364475=auto
==
--- cfe/trunk/test/CodeGenCXX/ms-constexpr-var-template.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/ms-constexpr-var-template.cpp (removed)
@@ -1,11 +0,0 @@
-// RUN: %clang_cc1 -emit-llvm -triple=x86_64-windows-msvc -fms-compatibility 
%s -o - | FileCheck %s
-
-template  constexpr bool _Is_integer = false;
-template <> constexpr bool _Is_integer = true;
-template <> constexpr bool _Is_integer = false;
-extern "C" const bool *escape = &_Is_integer;
-
-// CHECK: @"??$_Is_integer@H@@3_NB" = linkonce_odr dso_local constant i8 1, 
comdat, align 1
-//   Should not emit _Is_integer, since it's not referenced.
-// CHECK-NOT: @"??$_Is_integer@D@@3_NB"
-// CHECK: @escape = dso_local global i8* @"??$_Is_integer@H@@3_NB", align 8


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


[PATCH] D63681: [clang-scan-deps] Introduce the DependencyScanning library with the thread worker code and better error handling

2019-06-26 Thread Alex Lorenz via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL364474: [clang-scan-deps] Introduce the DependencyScanning 
library with the (authored by arphaman, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D63681?vs=206100=206744#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D63681

Files:
  cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h
  cfe/trunk/include/clang/Tooling/Tooling.h
  cfe/trunk/lib/Tooling/CMakeLists.txt
  cfe/trunk/lib/Tooling/DependencyScanning/CMakeLists.txt
  cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
  cfe/trunk/lib/Tooling/Tooling.cpp
  cfe/trunk/test/ClangScanDeps/Inputs/regular_cdb.json
  cfe/trunk/test/ClangScanDeps/error.cpp
  cfe/trunk/tools/clang-scan-deps/CMakeLists.txt
  cfe/trunk/tools/clang-scan-deps/ClangScanDeps.cpp

Index: cfe/trunk/test/ClangScanDeps/Inputs/regular_cdb.json
===
--- cfe/trunk/test/ClangScanDeps/Inputs/regular_cdb.json
+++ cfe/trunk/test/ClangScanDeps/Inputs/regular_cdb.json
@@ -6,7 +6,7 @@
 },
 {
   "directory": "DIR",
-  "command": "clang -E -fsyntax-only DIR/regular_cdb.cpp -IInputs",
+  "command": "clang -E DIR/regular_cdb.cpp -IInputs",
   "file": "DIR/regular_cdb.cpp"
 }
 ]
Index: cfe/trunk/test/ClangScanDeps/error.cpp
===
--- cfe/trunk/test/ClangScanDeps/error.cpp
+++ cfe/trunk/test/ClangScanDeps/error.cpp
@@ -0,0 +1,21 @@
+// RUN: rm -rf %t.dir
+// RUN: rm -rf %t.cdb
+// RUN: mkdir -p %t.dir
+// RUN: cp %s %t.dir/regular_cdb.cpp
+// RUN: sed -e "s|DIR|%/t.dir|g" %S/Inputs/regular_cdb.json > %t.cdb
+//
+// RUN: not clang-scan-deps -compilation-database %t.cdb -j 1 2>%t.dir/errs
+// RUN: echo EOF >> %t.dir/errs
+// RUN: FileCheck %s --input-file %t.dir/errs
+
+#include "missing.h"
+
+// CHECK: Error while scanning dependencies
+// CHECK-NEXT: error: no such file or directory:
+// CHECK-NEXT: error: no input files
+// CHECK-NEXT: error:
+// CHECK-NEXT: Error while scanning dependencies
+// CHECK-NEXT: fatal error: 'missing.h' file not found
+// CHECK-NEXT: "missing.h"
+// CHECK-NEXT: ^
+// CHECK-NEXT: EOF
Index: cfe/trunk/lib/Tooling/DependencyScanning/CMakeLists.txt
===
--- cfe/trunk/lib/Tooling/DependencyScanning/CMakeLists.txt
+++ cfe/trunk/lib/Tooling/DependencyScanning/CMakeLists.txt
@@ -0,0 +1,22 @@
+set(LLVM_LINK_COMPONENTS
+  Core
+  Support
+  )
+
+add_clang_library(clangDependencyScanning
+  DependencyScanningWorker.cpp
+
+  DEPENDS
+  ClangDriverOptions
+
+  LINK_LIBS
+  clangAST
+  clangBasic
+  clangDriver
+  clangFrontend
+  clangFrontendTool
+  clangLex
+  clangParse
+  clangSerialization
+  clangTooling
+)
Index: cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
===
--- cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -0,0 +1,149 @@
+//===- DependencyScanningWorker.cpp - clang-scan-deps worker --===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningWorker.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/FrontendActions.h"
+#include "clang/Frontend/TextDiagnosticPrinter.h"
+#include "clang/Frontend/Utils.h"
+#include "clang/Tooling/Tooling.h"
+
+using namespace clang;
+using namespace tooling;
+using namespace dependencies;
+
+namespace {
+
+/// Prints out all of the gathered dependencies into a string.
+class DependencyPrinter : public DependencyFileGenerator {
+public:
+  DependencyPrinter(std::unique_ptr Opts,
+std::string )
+  : DependencyFileGenerator(*Opts), Opts(std::move(Opts)), S(S) {}
+
+  void finishedMainFile(DiagnosticsEngine ) override {
+llvm::raw_string_ostream OS(S);
+outputDependencyFile(OS);
+  }
+
+private:
+  std::unique_ptr Opts;
+  std::string 
+};
+
+/// A proxy file system that doesn't call `chdir` when changing the working
+/// directory of a clang tool.
+class ProxyFileSystemWithoutChdir : public llvm::vfs::ProxyFileSystem {
+public:
+  ProxyFileSystemWithoutChdir(
+  llvm::IntrusiveRefCntPtr FS)
+  : ProxyFileSystem(std::move(FS)) {}
+
+  llvm::ErrorOr getCurrentWorkingDirectory() const override {
+assert(!CWD.empty() && "empty CWD");
+return CWD;
+  }
+
+  std::error_code 

r364474 - [clang-scan-deps] Introduce the DependencyScanning library with the

2019-06-26 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Wed Jun 26 14:11:51 2019
New Revision: 364474

URL: http://llvm.org/viewvc/llvm-project?rev=364474=rev
Log:
[clang-scan-deps] Introduce the DependencyScanning library with the
thread worker code and better error handling

This commit extracts out the code that will powers the fast scanning
worker into a new file in a new DependencyScanning library. The error
and output handling is improved so that the clients can gather
errors/results from the worker directly.

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

Added:
cfe/trunk/include/clang/Tooling/DependencyScanning/

cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h
cfe/trunk/lib/Tooling/DependencyScanning/
cfe/trunk/lib/Tooling/DependencyScanning/CMakeLists.txt
cfe/trunk/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
cfe/trunk/test/ClangScanDeps/error.cpp
Modified:
cfe/trunk/include/clang/Tooling/Tooling.h
cfe/trunk/lib/Tooling/CMakeLists.txt
cfe/trunk/lib/Tooling/Tooling.cpp
cfe/trunk/test/ClangScanDeps/Inputs/regular_cdb.json
cfe/trunk/tools/clang-scan-deps/CMakeLists.txt
cfe/trunk/tools/clang-scan-deps/ClangScanDeps.cpp

Added: 
cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h?rev=364474=auto
==
--- 
cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h 
(added)
+++ 
cfe/trunk/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h 
Wed Jun 26 14:11:51 2019
@@ -0,0 +1,58 @@
+//===- DependencyScanningWorker.h - clang-scan-deps worker ===---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLING_DEPENDENCY_SCANNING_WORKER_H
+#define LLVM_CLANG_TOOLING_DEPENDENCY_SCANNING_WORKER_H
+
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Basic/LLVM.h"
+#include "clang/Frontend/PCHContainerOperations.h"
+#include "clang/Tooling/CompilationDatabase.h"
+#include "llvm/Support/Error.h"
+#include "llvm/Support/FileSystem.h"
+#include 
+
+namespace clang {
+namespace tooling {
+namespace dependencies {
+
+/// An individual dependency scanning worker that is able to run on its own
+/// thread.
+///
+/// The worker computes the dependencies for the input files by preprocessing
+/// sources either using a fast mode where the source files are minimized, or
+/// using the regular processing run.
+class DependencyScanningWorker {
+public:
+  DependencyScanningWorker();
+
+  /// Print out the dependency information into a string using the dependency
+  /// file format that is specified in the options (-MD is the default) and
+  /// return it.
+  ///
+  /// \returns A \c StringError with the diagnostic output if clang errors
+  /// occurred, dependency file contents otherwise.
+  llvm::Expected getDependencyFile(const std::string ,
+StringRef WorkingDirectory,
+const CompilationDatabase 
);
+
+private:
+  IntrusiveRefCntPtr DiagOpts;
+  std::shared_ptr PCHContainerOps;
+
+  /// The file system that is used by each worker when scanning for
+  /// dependencies. This filesystem persists accross multiple compiler
+  /// invocations.
+  llvm::IntrusiveRefCntPtr WorkerFS;
+};
+
+} // end namespace dependencies
+} // end namespace tooling
+} // end namespace clang
+
+#endif // LLVM_CLANG_TOOLING_DEPENDENCY_SCANNING_WORKER_H

Modified: cfe/trunk/include/clang/Tooling/Tooling.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/Tooling.h?rev=364474=364473=364474=diff
==
--- cfe/trunk/include/clang/Tooling/Tooling.h (original)
+++ cfe/trunk/include/clang/Tooling/Tooling.h Wed Jun 26 14:11:51 2019
@@ -360,6 +360,10 @@ public:
   /// turn this off when running on multiple threads to avoid the raciness.
   void setRestoreWorkingDir(bool RestoreCWD);
 
+  /// Sets whether an error message should be printed out if an action fails. 
By
+  /// default, if an action fails, a message is printed out to stderr.
+  void setPrintErrorMessage(bool PrintErrorMessage);
+
   /// Returns the file manager used in the tool.
   ///
   /// The file manager is shared between all translation units.
@@ -386,6 +390,7 @@ private:
   DiagnosticConsumer *DiagConsumer = nullptr;
 
   bool RestoreCWD = true;
+  bool PrintErrorMessage = true;
 };
 
 template 

Modified: cfe/trunk/lib/Tooling/CMakeLists.txt
URL: 

[PATCH] D63681: [clang-scan-deps] Introduce the DependencyScanning library with the thread worker code and better error handling

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

@aganea The FS `status` and most of file reads will be cached with the shared 
FS. Hopefully I can put up a patch for it this week.


Repository:
  rC Clang

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

https://reviews.llvm.org/D63681



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


[PATCH] D63681: [clang-scan-deps] Introduce the DependencyScanning library with the thread worker code and better error handling

2019-06-26 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman marked an inline comment as done.
arphaman added inline comments.



Comment at: 
clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h:29
+/// sources either using a fast mode where the source files are minimized, or
+/// using the regular processing run.
+class DependencyScanningWorker {

aganea wrote:
> How do you actually select between the fast mode or the regular preprocess?
You can't select it yet, as it's not yet implemented :)
A couple more follow-up patches, and it will be usable.


Repository:
  rC Clang

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

https://reviews.llvm.org/D63681



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


[PATCH] D62648: [Sema][Typo] Fix assertion failure for expressions with multiple typos

2019-06-26 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

Thanks, this looks good; just some nits.




Comment at: lib/Sema/SemaExprCXX.cpp:7616
   /// anything (having been passed an empty TypoCorrection).
-  void EmitAllDiagnostics() {
+  void EmitAllDiagnostics(bool isAmbiguous) {
 for (TypoExpr *TE : TypoExprs) {

Please capitalize this parameter name to match the surrounding code style.



Comment at: lib/Sema/SemaExprCXX.cpp:7620-7621
   if (State.DiagHandler) {
-TypoCorrection TC = State.Consumer->getCurrentCorrection();
-ExprResult Replacement = TransformCache[TE];
+TypoCorrection TC = isAmbiguous ? TypoCorrection() : 
State.Consumer->getCurrentCorrection();
+ExprResult Replacement = isAmbiguous ? ExprError() : 
TransformCache[TE];
 

Reflow to 80 columns.



Comment at: lib/Sema/SemaExprCXX.cpp:7686
+  // only succeed if it is able to correct all typos in the given expression.
+  ExprResult CheckForRecursiveTypos(ExprResult Res, bool ) {
+if (Res.isInvalid()) {

`outIsAmbiguous` -> `IsAmbiguous` (we don't use an `out` prefix for output 
parameters).



Comment at: lib/Sema/SemaExprCXX.cpp:7694-7695
+
+auto SavedTypoExprs = TypoExprs;
+auto SavedAmbiguousTypoExprs = AmbiguousTypoExprs;
+llvm::SmallSetVector

Use `std::move` here.



Comment at: lib/Sema/SemaExprCXX.cpp:7696-7699
+llvm::SmallSetVector
+RecursiveTypoExprs, RecursiveAmbiguousTypoExprs;
+TypoExprs = RecursiveTypoExprs;
+AmbiguousTypoExprs = RecursiveAmbiguousTypoExprs;

Call `TypoExprs.clear()` rather than copying from a default-constructed object.



Comment at: lib/Sema/SemaExprCXX.cpp:7723-7724
+
+TypoExprs = SavedTypoExprs;
+AmbiguousTypoExprs = SavedAmbiguousTypoExprs;
+

And `std::move` here too.



Comment at: lib/Sema/SemaExprCXX.cpp:7778-7779
+  }
+} while((Next = State.Consumer->peekNextCorrection()) &&
+Next.getEditDistance(false) == TC.getEditDistance(false));
+

Apply clang-format here. (Or: add space after `while` on the first line, and 
indent the second line so it begins in the same column as `(Next =[...]`).



Comment at: lib/Sema/SemaExprCXX.cpp:7781-7785
+if (!outIsAmbiguous) {
+  AmbiguousTypoExprs.remove(TE);
+  State.Consumer->restoreSavedPosition();
+} else
+  break;

Reverse the condition of this `if` so you can early-exit from the loop and 
remove the `else`.



Comment at: lib/Sema/SemaExprCXX.cpp:7819
   ExprResult Transform(Expr *E) {
-ExprResult Res;
-while (true) {
-  Res = TryTransform(E);
-
-  // Exit if either the transform was valid or if there were no TypoExprs
-  // to transform that still have any untried correction candidates..
-  if (!Res.isInvalid() ||
-  !CheckAndAdvanceTypoExprCorrectionStreams())
-break;
-}
-
-// Ensure none of the TypoExprs have multiple typo correction candidates
-// with the same edit length that pass all the checks and filters.
-// TODO: Properly handle various permutations of possible corrections when
-// there is more than one potentially ambiguous typo correction.
-// Also, disable typo correction while attempting the transform when
-// handling potentially ambiguous typo corrections as any new TypoExprs 
will
-// have been introduced by the application of one of the correction
-// candidates and add little to no value if corrected.
-SemaRef.DisableTypoCorrection = true;
-while (!AmbiguousTypoExprs.empty()) {
-  auto TE  = AmbiguousTypoExprs.back();
-  auto Cached = TransformCache[TE];
-  auto  = SemaRef.getTypoExprState(TE);
-  State.Consumer->saveCurrentPosition();
-  TransformCache.erase(TE);
-  if (!TryTransform(E).isInvalid()) {
-State.Consumer->resetCorrectionStream();
-TransformCache.erase(TE);
-Res = ExprError();
-break;
-  }
-  AmbiguousTypoExprs.remove(TE);
-  State.Consumer->restoreSavedPosition();
-  TransformCache[TE] = Cached;
-}
-SemaRef.DisableTypoCorrection = false;
+bool isAmbiguous = false;
+ExprResult Res = RecursiveTransformLoop(E, isAmbiguous);

`isAmbiguous` -> `IsAmbiguous`.


Repository:
  rC Clang

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

https://reviews.llvm.org/D62648



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


[PATCH] D63753: [Sema] Instead of rejecting C unions with non-trivial fields, detect attempts to destruct/initialize/copy them.

2019-06-26 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: include/clang/Basic/DiagnosticSemaKinds.td:633
+  "capture a variable of type %1}3 "
+  "since it %select{contains a union that |}2is non-trivial to "
+  "%select{default-initialize|destruct|copy}0">;

Should this be "`%select{contains|is}2 a union that is non-trivial to..."?  
None of these situations bans non-trivial types, just unions containing them 
(and aggregates containing such unions).



Comment at: include/clang/Sema/Sema.h:2116
 
+  // Contexts where using non-trivial C union types can be disallowed.
+  enum NonTrivialCUnionContext {

If this is parallel with the diagnostic, I'd suggest mentioning that in the 
comment.



Comment at: include/clang/Sema/Sema.h:2121
+// Function return.
+NTCUC_FuncitonReturn,
+// Uninialized variable with automatic storage duration.

Same typo in both of these.



Comment at: include/clang/Sema/Sema.h:2126
+NTCUC_AutoVar,
+// Initializer expression for object with automatic storage duration.
+NTCUC_AutoObjInit,

Please expand this comment to clarify that this it's only used when we (might 
be) initializing an object by copying another.

Why is this specific to automatic storage duration?  Just because C doesn't 
allow other initializers to be non-constant in the first place?



Comment at: lib/Sema/SemaDecl.cpp:11085
+if (isa(I))
+  continue;
+if (auto E = dyn_cast(I))

Why is this okay?  Don't we need to check default-initialization for these?



Comment at: lib/Sema/SemaDecl.cpp:11089
+else
+  checkNonTrivialCUnion(I->getType(), I->getExprLoc(), NTCUC_AutoObjInit);
+  }

Please include a comment like:

```
  // Assume all other initializers involving copying some existing object.
  // TODO: ignore any initializers where we can guarantee copy-elision
```


Repository:
  rC Clang

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

https://reviews.llvm.org/D63753



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


[PATCH] D63638: [clang][NewPM] Add new pass manager RUN lines to avx512f-builtins.c

2019-06-26 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

@chandlerc ping


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

https://reviews.llvm.org/D63638



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


[PATCH] D59474: [OpenMP 5.0] Codegen support for user-defined mappers

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



Comment at: lib/CodeGen/CGOpenMPRuntime.cpp:8739
+/// // For each component specified by this mapper:
+/// if (currentComponent.hasMapper())
+///   (*currentComponent.Mapper())(rt_mapper_handle, arg_base, arg_begin,

lildmh wrote:
> ABataev wrote:
> > lildmh wrote:
> > > ABataev wrote:
> > > > lildmh wrote:
> > > > > ABataev wrote:
> > > > > > lildmh wrote:
> > > > > > > ABataev wrote:
> > > > > > > > lildmh wrote:
> > > > > > > > > ABataev wrote:
> > > > > > > > > > lildmh wrote:
> > > > > > > > > > > ABataev wrote:
> > > > > > > > > > > > lildmh wrote:
> > > > > > > > > > > > > ABataev wrote:
> > > > > > > > > > > > > > lildmh wrote:
> > > > > > > > > > > > > > > ABataev wrote:
> > > > > > > > > > > > > > > > lildmh wrote:
> > > > > > > > > > > > > > > > > ABataev wrote:
> > > > > > > > > > > > > > > > > > Currently `currentComponent` is generated 
> > > > > > > > > > > > > > > > > > by the compiler. But can we instead pass 
> > > > > > > > > > > > > > > > > > this data as an extra parameter to this 
> > > > > > > > > > > > > > > > > > `omp_mapper` function.
> > > > > > > > > > > > > > > > > Emm, I think this scheme will be very 
> > > > > > > > > > > > > > > > > difficult and inefficient. If we pass 
> > > > > > > > > > > > > > > > > components as an argument of `omp_mapper` 
> > > > > > > > > > > > > > > > > function, it means that the runtime needs to 
> > > > > > > > > > > > > > > > > generate all components related to a map 
> > > > > > > > > > > > > > > > > clause. I don't think the runtime is able to 
> > > > > > > > > > > > > > > > > do that efficiently. On the other hand, in 
> > > > > > > > > > > > > > > > > the current scheme, these components are 
> > > > > > > > > > > > > > > > > naturally generated by the compiler, and the 
> > > > > > > > > > > > > > > > > runtime only needs to know the base pointer, 
> > > > > > > > > > > > > > > > > pointer, type, size. etc.
> > > > > > > > > > > > > > > > With the current scheme, we may end with the 
> > > > > > > > > > > > > > > > code blowout. We need to generate very similar 
> > > > > > > > > > > > > > > > code for different types and variables. The 
> > > > > > > > > > > > > > > > worst thing here is that we will be unable to 
> > > > > > > > > > > > > > > > optimize this huge amount of code because the 
> > > > > > > > > > > > > > > > codegen relies on the runtime functions and the 
> > > > > > > > > > > > > > > > code cannot be inlined. That's why I would like 
> > > > > > > > > > > > > > > > to move as much as possible code to the runtime 
> > > > > > > > > > > > > > > > rather than to emit it in the compiler. 
> > > > > > > > > > > > > > > I understand your concerns. I think this is the 
> > > > > > > > > > > > > > > best we can do right now.
> > > > > > > > > > > > > > > 
> > > > > > > > > > > > > > > The most worrisome case will be when we have 
> > > > > > > > > > > > > > > nested mappers within each other. In this case, a 
> > > > > > > > > > > > > > > mapper function will call another mapper 
> > > > > > > > > > > > > > > function. We can inline the inner mapper 
> > > > > > > > > > > > > > > functions in this scenario, so that these mapper 
> > > > > > > > > > > > > > > function can be properly optimized. As a result, 
> > > > > > > > > > > > > > > I think the performance should be fine.
> > > > > > > > > > > > > > Instead, we can use indirect function calls passed 
> > > > > > > > > > > > > > in the array to the runtime. Do you think it is 
> > > > > > > > > > > > > > going to be slower? In your current scheme, we 
> > > > > > > > > > > > > > generate many runtime calls instead. Could you try 
> > > > > > > > > > > > > > to estimate the number of calls in cases if we'll 
> > > > > > > > > > > > > > call the mappers through the indirect function 
> > > > > > > > > > > > > > calls and in your cuurent scheme, where we need to 
> > > > > > > > > > > > > > call the runtime functions many times in each 
> > > > > > > > > > > > > > particular mapper?
> > > > > > > > > > > > > Hi Alexey,
> > > > > > > > > > > > > 
> > > > > > > > > > > > > Sorry I don't understand your idea. What indirect 
> > > > > > > > > > > > > function calls do you propose to be passed to the 
> > > > > > > > > > > > > runtime? What are these functions supposed to do?
> > > > > > > > > > > > > 
> > > > > > > > > > > > > The number of function calls will be exactly equal to 
> > > > > > > > > > > > > the number of components mapped, no matter whether 
> > > > > > > > > > > > > there are nested mappers or not. The number of 
> > > > > > > > > > > > > components depend on the program. E.g., if we map a 
> > > > > > > > > > > > > large array section, then there will be many more 
> > > > > > > > > > > > > function calls.
> > > > > > > > > > > > I mean the pointers to the mapper function, generated 
> > > > > > > > > > > > by the compiler. In your comment, it is `c.Mapper()`
> > > > > > > > > > > If 

[PATCH] D63638: [clang][NewPM] Add new pass manager RUN lines to avx512f-builtins.c

2019-06-26 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan added a comment.

Any updates on this? I'm thinking that in the meantime maybe we could commit 
D63174  and work on this while that lands. If 
so, we could get an upstream new PM buildbot that can catch any new PM 
regressions.


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

https://reviews.llvm.org/D63638



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


[PATCH] D59474: [OpenMP 5.0] Codegen support for user-defined mappers

2019-06-26 Thread Lingda Li via Phabricator via cfe-commits
lildmh marked an inline comment as done.
lildmh added inline comments.



Comment at: lib/CodeGen/CGOpenMPRuntime.cpp:8739
+/// // For each component specified by this mapper:
+/// if (currentComponent.hasMapper())
+///   (*currentComponent.Mapper())(rt_mapper_handle, arg_base, arg_begin,

ABataev wrote:
> lildmh wrote:
> > ABataev wrote:
> > > lildmh wrote:
> > > > ABataev wrote:
> > > > > lildmh wrote:
> > > > > > ABataev wrote:
> > > > > > > lildmh wrote:
> > > > > > > > ABataev wrote:
> > > > > > > > > lildmh wrote:
> > > > > > > > > > ABataev wrote:
> > > > > > > > > > > lildmh wrote:
> > > > > > > > > > > > ABataev wrote:
> > > > > > > > > > > > > lildmh wrote:
> > > > > > > > > > > > > > ABataev wrote:
> > > > > > > > > > > > > > > lildmh wrote:
> > > > > > > > > > > > > > > > ABataev wrote:
> > > > > > > > > > > > > > > > > Currently `currentComponent` is generated by 
> > > > > > > > > > > > > > > > > the compiler. But can we instead pass this 
> > > > > > > > > > > > > > > > > data as an extra parameter to this 
> > > > > > > > > > > > > > > > > `omp_mapper` function.
> > > > > > > > > > > > > > > > Emm, I think this scheme will be very difficult 
> > > > > > > > > > > > > > > > and inefficient. If we pass components as an 
> > > > > > > > > > > > > > > > argument of `omp_mapper` function, it means 
> > > > > > > > > > > > > > > > that the runtime needs to generate all 
> > > > > > > > > > > > > > > > components related to a map clause. I don't 
> > > > > > > > > > > > > > > > think the runtime is able to do that 
> > > > > > > > > > > > > > > > efficiently. On the other hand, in the current 
> > > > > > > > > > > > > > > > scheme, these components are naturally 
> > > > > > > > > > > > > > > > generated by the compiler, and the runtime only 
> > > > > > > > > > > > > > > > needs to know the base pointer, pointer, type, 
> > > > > > > > > > > > > > > > size. etc.
> > > > > > > > > > > > > > > With the current scheme, we may end with the code 
> > > > > > > > > > > > > > > blowout. We need to generate very similar code 
> > > > > > > > > > > > > > > for different types and variables. The worst 
> > > > > > > > > > > > > > > thing here is that we will be unable to optimize 
> > > > > > > > > > > > > > > this huge amount of code because the codegen 
> > > > > > > > > > > > > > > relies on the runtime functions and the code 
> > > > > > > > > > > > > > > cannot be inlined. That's why I would like to 
> > > > > > > > > > > > > > > move as much as possible code to the runtime 
> > > > > > > > > > > > > > > rather than to emit it in the compiler. 
> > > > > > > > > > > > > > I understand your concerns. I think this is the 
> > > > > > > > > > > > > > best we can do right now.
> > > > > > > > > > > > > > 
> > > > > > > > > > > > > > The most worrisome case will be when we have nested 
> > > > > > > > > > > > > > mappers within each other. In this case, a mapper 
> > > > > > > > > > > > > > function will call another mapper function. We can 
> > > > > > > > > > > > > > inline the inner mapper functions in this scenario, 
> > > > > > > > > > > > > > so that these mapper function can be properly 
> > > > > > > > > > > > > > optimized. As a result, I think the performance 
> > > > > > > > > > > > > > should be fine.
> > > > > > > > > > > > > Instead, we can use indirect function calls passed in 
> > > > > > > > > > > > > the array to the runtime. Do you think it is going to 
> > > > > > > > > > > > > be slower? In your current scheme, we generate many 
> > > > > > > > > > > > > runtime calls instead. Could you try to estimate the 
> > > > > > > > > > > > > number of calls in cases if we'll call the mappers 
> > > > > > > > > > > > > through the indirect function calls and in your 
> > > > > > > > > > > > > cuurent scheme, where we need to call the runtime 
> > > > > > > > > > > > > functions many times in each particular mapper?
> > > > > > > > > > > > Hi Alexey,
> > > > > > > > > > > > 
> > > > > > > > > > > > Sorry I don't understand your idea. What indirect 
> > > > > > > > > > > > function calls do you propose to be passed to the 
> > > > > > > > > > > > runtime? What are these functions supposed to do?
> > > > > > > > > > > > 
> > > > > > > > > > > > The number of function calls will be exactly equal to 
> > > > > > > > > > > > the number of components mapped, no matter whether 
> > > > > > > > > > > > there are nested mappers or not. The number of 
> > > > > > > > > > > > components depend on the program. E.g., if we map a 
> > > > > > > > > > > > large array section, then there will be many more 
> > > > > > > > > > > > function calls.
> > > > > > > > > > > I mean the pointers to the mapper function, generated by 
> > > > > > > > > > > the compiler. In your comment, it is `c.Mapper()`
> > > > > > > > > > If we pass nested mapper functions to the runtime, I think 
> > > > > > > > > > it will slow down execution because of the extra level of 
> > > > > > > > 

[PATCH] D59474: [OpenMP 5.0] Codegen support for user-defined mappers

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



Comment at: lib/CodeGen/CGOpenMPRuntime.cpp:8739
+/// // For each component specified by this mapper:
+/// if (currentComponent.hasMapper())
+///   (*currentComponent.Mapper())(rt_mapper_handle, arg_base, arg_begin,

lildmh wrote:
> ABataev wrote:
> > lildmh wrote:
> > > ABataev wrote:
> > > > lildmh wrote:
> > > > > ABataev wrote:
> > > > > > lildmh wrote:
> > > > > > > ABataev wrote:
> > > > > > > > lildmh wrote:
> > > > > > > > > ABataev wrote:
> > > > > > > > > > lildmh wrote:
> > > > > > > > > > > ABataev wrote:
> > > > > > > > > > > > lildmh wrote:
> > > > > > > > > > > > > ABataev wrote:
> > > > > > > > > > > > > > lildmh wrote:
> > > > > > > > > > > > > > > ABataev wrote:
> > > > > > > > > > > > > > > > Currently `currentComponent` is generated by 
> > > > > > > > > > > > > > > > the compiler. But can we instead pass this data 
> > > > > > > > > > > > > > > > as an extra parameter to this `omp_mapper` 
> > > > > > > > > > > > > > > > function.
> > > > > > > > > > > > > > > Emm, I think this scheme will be very difficult 
> > > > > > > > > > > > > > > and inefficient. If we pass components as an 
> > > > > > > > > > > > > > > argument of `omp_mapper` function, it means that 
> > > > > > > > > > > > > > > the runtime needs to generate all components 
> > > > > > > > > > > > > > > related to a map clause. I don't think the 
> > > > > > > > > > > > > > > runtime is able to do that efficiently. On the 
> > > > > > > > > > > > > > > other hand, in the current scheme, these 
> > > > > > > > > > > > > > > components are naturally generated by the 
> > > > > > > > > > > > > > > compiler, and the runtime only needs to know the 
> > > > > > > > > > > > > > > base pointer, pointer, type, size. etc.
> > > > > > > > > > > > > > With the current scheme, we may end with the code 
> > > > > > > > > > > > > > blowout. We need to generate very similar code for 
> > > > > > > > > > > > > > different types and variables. The worst thing here 
> > > > > > > > > > > > > > is that we will be unable to optimize this huge 
> > > > > > > > > > > > > > amount of code because the codegen relies on the 
> > > > > > > > > > > > > > runtime functions and the code cannot be inlined. 
> > > > > > > > > > > > > > That's why I would like to move as much as possible 
> > > > > > > > > > > > > > code to the runtime rather than to emit it in the 
> > > > > > > > > > > > > > compiler. 
> > > > > > > > > > > > > I understand your concerns. I think this is the best 
> > > > > > > > > > > > > we can do right now.
> > > > > > > > > > > > > 
> > > > > > > > > > > > > The most worrisome case will be when we have nested 
> > > > > > > > > > > > > mappers within each other. In this case, a mapper 
> > > > > > > > > > > > > function will call another mapper function. We can 
> > > > > > > > > > > > > inline the inner mapper functions in this scenario, 
> > > > > > > > > > > > > so that these mapper function can be properly 
> > > > > > > > > > > > > optimized. As a result, I think the performance 
> > > > > > > > > > > > > should be fine.
> > > > > > > > > > > > Instead, we can use indirect function calls passed in 
> > > > > > > > > > > > the array to the runtime. Do you think it is going to 
> > > > > > > > > > > > be slower? In your current scheme, we generate many 
> > > > > > > > > > > > runtime calls instead. Could you try to estimate the 
> > > > > > > > > > > > number of calls in cases if we'll call the mappers 
> > > > > > > > > > > > through the indirect function calls and in your cuurent 
> > > > > > > > > > > > scheme, where we need to call the runtime functions 
> > > > > > > > > > > > many times in each particular mapper?
> > > > > > > > > > > Hi Alexey,
> > > > > > > > > > > 
> > > > > > > > > > > Sorry I don't understand your idea. What indirect 
> > > > > > > > > > > function calls do you propose to be passed to the 
> > > > > > > > > > > runtime? What are these functions supposed to do?
> > > > > > > > > > > 
> > > > > > > > > > > The number of function calls will be exactly equal to the 
> > > > > > > > > > > number of components mapped, no matter whether there are 
> > > > > > > > > > > nested mappers or not. The number of components depend on 
> > > > > > > > > > > the program. E.g., if we map a large array section, then 
> > > > > > > > > > > there will be many more function calls.
> > > > > > > > > > I mean the pointers to the mapper function, generated by 
> > > > > > > > > > the compiler. In your comment, it is `c.Mapper()`
> > > > > > > > > If we pass nested mapper functions to the runtime, I think it 
> > > > > > > > > will slow down execution because of the extra level of 
> > > > > > > > > indirect function calls. E.g., the runtime will call 
> > > > > > > > > `omp_mapper1`, which calls the runtime back, which calls 
> > > > > > > > > `omp_mapper2`,  This can result in a deep call stack.
> > > > > > > > > 
> > > > > > > > > I think the 

[PATCH] D63742: [WebAssembly] Implement Address Sanitizer for Emscripten

2019-06-26 Thread Guanzhong Chen via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL364468: [WebAssembly] Implement Address Sanitizer for 
Emscripten (authored by quantum, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D63742?vs=206719=206732#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D63742

Files:
  cfe/trunk/lib/Driver/ToolChains/WebAssembly.cpp
  cfe/trunk/test/Driver/wasm-toolchain.c
  llvm/trunk/lib/Transforms/Instrumentation/AddressSanitizer.cpp


Index: llvm/trunk/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/trunk/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/trunk/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -109,6 +109,7 @@
 static const uint64_t kNetBSDKasan_ShadowOffset64 = 0xdfff9000;
 static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
 static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
+static const uint64_t kEmscriptenShadowOffset = 0;
 
 static const uint64_t kMyriadShadowScale = 5;
 static const uint64_t kMyriadMemoryOffset32 = 0x8000ULL;
@@ -433,6 +434,7 @@
   bool IsWindows = TargetTriple.isOSWindows();
   bool IsFuchsia = TargetTriple.isOSFuchsia();
   bool IsMyriad = TargetTriple.getVendor() == llvm::Triple::Myriad;
+  bool IsEmscripten = TargetTriple.isOSEmscripten();
 
   ShadowMapping Mapping;
 
@@ -454,6 +456,8 @@
   Mapping.Offset = kDynamicShadowSentinel;
 else if (IsWindows)
   Mapping.Offset = kWindowsShadowOffset32;
+else if (IsEmscripten)
+  Mapping.Offset = kEmscriptenShadowOffset;
 else if (IsMyriad) {
   uint64_t ShadowOffset = (kMyriadMemoryOffset32 + kMyriadMemorySize32 -
(kMyriadMemorySize32 >> Mapping.Scale));
Index: cfe/trunk/test/Driver/wasm-toolchain.c
===
--- cfe/trunk/test/Driver/wasm-toolchain.c
+++ cfe/trunk/test/Driver/wasm-toolchain.c
@@ -60,3 +60,7 @@
 // RUN: --sysroot=/foo %s -pthread -mno-atomics 2>&1 \
 // RUN:   | FileCheck -check-prefix=PTHREAD_NO_ATOMICS %s
 // PTHREAD_NO_ATOMICS: invalid argument '-pthread' not allowed with 
'-mno-atomics'
+
+// RUN: %clang %s -### -fsanitize=address -target wasm32-unknown-emscripten 
2>&1 | FileCheck -check-prefix=CHECK-ASAN-EMSCRIPTEN %s
+// CHECK-ASAN-EMSCRIPTEN: "-fsanitize=address"
+// CHECK-ASAN-EMSCRIPTEN: "-fsanitize-address-globals-dead-stripping"
Index: cfe/trunk/lib/Driver/ToolChains/WebAssembly.cpp
===
--- cfe/trunk/lib/Driver/ToolChains/WebAssembly.cpp
+++ cfe/trunk/lib/Driver/ToolChains/WebAssembly.cpp
@@ -238,7 +238,7 @@
 SanitizerMask WebAssembly::getSupportedSanitizers() const {
   SanitizerMask Res = ToolChain::getSupportedSanitizers();
   if (getTriple().isOSEmscripten()) {
-Res |= SanitizerKind::Vptr | SanitizerKind::Leak;
+Res |= SanitizerKind::Vptr | SanitizerKind::Leak | SanitizerKind::Address;
   }
   return Res;
 }


Index: llvm/trunk/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/trunk/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/trunk/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -109,6 +109,7 @@
 static const uint64_t kNetBSDKasan_ShadowOffset64 = 0xdfff9000;
 static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
 static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
+static const uint64_t kEmscriptenShadowOffset = 0;
 
 static const uint64_t kMyriadShadowScale = 5;
 static const uint64_t kMyriadMemoryOffset32 = 0x8000ULL;
@@ -433,6 +434,7 @@
   bool IsWindows = TargetTriple.isOSWindows();
   bool IsFuchsia = TargetTriple.isOSFuchsia();
   bool IsMyriad = TargetTriple.getVendor() == llvm::Triple::Myriad;
+  bool IsEmscripten = TargetTriple.isOSEmscripten();
 
   ShadowMapping Mapping;
 
@@ -454,6 +456,8 @@
   Mapping.Offset = kDynamicShadowSentinel;
 else if (IsWindows)
   Mapping.Offset = kWindowsShadowOffset32;
+else if (IsEmscripten)
+  Mapping.Offset = kEmscriptenShadowOffset;
 else if (IsMyriad) {
   uint64_t ShadowOffset = (kMyriadMemoryOffset32 + kMyriadMemorySize32 -
(kMyriadMemorySize32 >> Mapping.Scale));
Index: cfe/trunk/test/Driver/wasm-toolchain.c
===
--- cfe/trunk/test/Driver/wasm-toolchain.c
+++ cfe/trunk/test/Driver/wasm-toolchain.c
@@ -60,3 +60,7 @@
 // RUN: --sysroot=/foo %s -pthread -mno-atomics 2>&1 \
 // RUN:   | FileCheck -check-prefix=PTHREAD_NO_ATOMICS %s
 // PTHREAD_NO_ATOMICS: invalid argument '-pthread' not allowed with '-mno-atomics'
+
+// RUN: %clang %s -### -fsanitize=address -target wasm32-unknown-emscripten 2>&1 | FileCheck -check-prefix=CHECK-ASAN-EMSCRIPTEN %s
+// 

[PATCH] D63753: [Sema] Instead of rejecting C unions with non-trivial fields, detect attempts to destruct/initialize/copy them.

2019-06-26 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak planned changes to this revision.
ahatanak added a comment.

This patch should diagnose lvalue-to-rvalue conversion of volatile non-trivial 
C unions too, but it currently doesn't.

  void test(volatile union U0 *a) {
(void)*a;
  }


Repository:
  rC Clang

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

https://reviews.llvm.org/D63753



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


[PATCH] D59474: [OpenMP 5.0] Codegen support for user-defined mappers

2019-06-26 Thread Lingda Li via Phabricator via cfe-commits
lildmh marked an inline comment as done.
lildmh added inline comments.



Comment at: lib/CodeGen/CGOpenMPRuntime.cpp:8739
+/// // For each component specified by this mapper:
+/// if (currentComponent.hasMapper())
+///   (*currentComponent.Mapper())(rt_mapper_handle, arg_base, arg_begin,

ABataev wrote:
> lildmh wrote:
> > ABataev wrote:
> > > lildmh wrote:
> > > > ABataev wrote:
> > > > > lildmh wrote:
> > > > > > ABataev wrote:
> > > > > > > lildmh wrote:
> > > > > > > > ABataev wrote:
> > > > > > > > > lildmh wrote:
> > > > > > > > > > ABataev wrote:
> > > > > > > > > > > lildmh wrote:
> > > > > > > > > > > > ABataev wrote:
> > > > > > > > > > > > > lildmh wrote:
> > > > > > > > > > > > > > ABataev wrote:
> > > > > > > > > > > > > > > Currently `currentComponent` is generated by the 
> > > > > > > > > > > > > > > compiler. But can we instead pass this data as an 
> > > > > > > > > > > > > > > extra parameter to this `omp_mapper` function.
> > > > > > > > > > > > > > Emm, I think this scheme will be very difficult and 
> > > > > > > > > > > > > > inefficient. If we pass components as an argument 
> > > > > > > > > > > > > > of `omp_mapper` function, it means that the runtime 
> > > > > > > > > > > > > > needs to generate all components related to a map 
> > > > > > > > > > > > > > clause. I don't think the runtime is able to do 
> > > > > > > > > > > > > > that efficiently. On the other hand, in the current 
> > > > > > > > > > > > > > scheme, these components are naturally generated by 
> > > > > > > > > > > > > > the compiler, and the runtime only needs to know 
> > > > > > > > > > > > > > the base pointer, pointer, type, size. etc.
> > > > > > > > > > > > > With the current scheme, we may end with the code 
> > > > > > > > > > > > > blowout. We need to generate very similar code for 
> > > > > > > > > > > > > different types and variables. The worst thing here 
> > > > > > > > > > > > > is that we will be unable to optimize this huge 
> > > > > > > > > > > > > amount of code because the codegen relies on the 
> > > > > > > > > > > > > runtime functions and the code cannot be inlined. 
> > > > > > > > > > > > > That's why I would like to move as much as possible 
> > > > > > > > > > > > > code to the runtime rather than to emit it in the 
> > > > > > > > > > > > > compiler. 
> > > > > > > > > > > > I understand your concerns. I think this is the best we 
> > > > > > > > > > > > can do right now.
> > > > > > > > > > > > 
> > > > > > > > > > > > The most worrisome case will be when we have nested 
> > > > > > > > > > > > mappers within each other. In this case, a mapper 
> > > > > > > > > > > > function will call another mapper function. We can 
> > > > > > > > > > > > inline the inner mapper functions in this scenario, so 
> > > > > > > > > > > > that these mapper function can be properly optimized. 
> > > > > > > > > > > > As a result, I think the performance should be fine.
> > > > > > > > > > > Instead, we can use indirect function calls passed in the 
> > > > > > > > > > > array to the runtime. Do you think it is going to be 
> > > > > > > > > > > slower? In your current scheme, we generate many runtime 
> > > > > > > > > > > calls instead. Could you try to estimate the number of 
> > > > > > > > > > > calls in cases if we'll call the mappers through the 
> > > > > > > > > > > indirect function calls and in your cuurent scheme, where 
> > > > > > > > > > > we need to call the runtime functions many times in each 
> > > > > > > > > > > particular mapper?
> > > > > > > > > > Hi Alexey,
> > > > > > > > > > 
> > > > > > > > > > Sorry I don't understand your idea. What indirect function 
> > > > > > > > > > calls do you propose to be passed to the runtime? What are 
> > > > > > > > > > these functions supposed to do?
> > > > > > > > > > 
> > > > > > > > > > The number of function calls will be exactly equal to the 
> > > > > > > > > > number of components mapped, no matter whether there are 
> > > > > > > > > > nested mappers or not. The number of components depend on 
> > > > > > > > > > the program. E.g., if we map a large array section, then 
> > > > > > > > > > there will be many more function calls.
> > > > > > > > > I mean the pointers to the mapper function, generated by the 
> > > > > > > > > compiler. In your comment, it is `c.Mapper()`
> > > > > > > > If we pass nested mapper functions to the runtime, I think it 
> > > > > > > > will slow down execution because of the extra level of indirect 
> > > > > > > > function calls. E.g., the runtime will call `omp_mapper1`, 
> > > > > > > > which calls the runtime back, which calls `omp_mapper2`,  
> > > > > > > > This can result in a deep call stack.
> > > > > > > > 
> > > > > > > > I think the current implementation will be more efficient, 
> > > > > > > > which doesn't pass nested mappers to the runtime. One call to 
> > > > > > > > the outer most mapper function will have all data mapping done. 
> > 

[PATCH] D59474: [OpenMP 5.0] Codegen support for user-defined mappers

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



Comment at: lib/CodeGen/CGOpenMPRuntime.cpp:8739
+/// // For each component specified by this mapper:
+/// if (currentComponent.hasMapper())
+///   (*currentComponent.Mapper())(rt_mapper_handle, arg_base, arg_begin,

lildmh wrote:
> ABataev wrote:
> > lildmh wrote:
> > > ABataev wrote:
> > > > lildmh wrote:
> > > > > ABataev wrote:
> > > > > > lildmh wrote:
> > > > > > > ABataev wrote:
> > > > > > > > lildmh wrote:
> > > > > > > > > ABataev wrote:
> > > > > > > > > > lildmh wrote:
> > > > > > > > > > > ABataev wrote:
> > > > > > > > > > > > lildmh wrote:
> > > > > > > > > > > > > ABataev wrote:
> > > > > > > > > > > > > > Currently `currentComponent` is generated by the 
> > > > > > > > > > > > > > compiler. But can we instead pass this data as an 
> > > > > > > > > > > > > > extra parameter to this `omp_mapper` function.
> > > > > > > > > > > > > Emm, I think this scheme will be very difficult and 
> > > > > > > > > > > > > inefficient. If we pass components as an argument of 
> > > > > > > > > > > > > `omp_mapper` function, it means that the runtime 
> > > > > > > > > > > > > needs to generate all components related to a map 
> > > > > > > > > > > > > clause. I don't think the runtime is able to do that 
> > > > > > > > > > > > > efficiently. On the other hand, in the current 
> > > > > > > > > > > > > scheme, these components are naturally generated by 
> > > > > > > > > > > > > the compiler, and the runtime only needs to know the 
> > > > > > > > > > > > > base pointer, pointer, type, size. etc.
> > > > > > > > > > > > With the current scheme, we may end with the code 
> > > > > > > > > > > > blowout. We need to generate very similar code for 
> > > > > > > > > > > > different types and variables. The worst thing here is 
> > > > > > > > > > > > that we will be unable to optimize this huge amount of 
> > > > > > > > > > > > code because the codegen relies on the runtime 
> > > > > > > > > > > > functions and the code cannot be inlined. That's why I 
> > > > > > > > > > > > would like to move as much as possible code to the 
> > > > > > > > > > > > runtime rather than to emit it in the compiler. 
> > > > > > > > > > > I understand your concerns. I think this is the best we 
> > > > > > > > > > > can do right now.
> > > > > > > > > > > 
> > > > > > > > > > > The most worrisome case will be when we have nested 
> > > > > > > > > > > mappers within each other. In this case, a mapper 
> > > > > > > > > > > function will call another mapper function. We can inline 
> > > > > > > > > > > the inner mapper functions in this scenario, so that 
> > > > > > > > > > > these mapper function can be properly optimized. As a 
> > > > > > > > > > > result, I think the performance should be fine.
> > > > > > > > > > Instead, we can use indirect function calls passed in the 
> > > > > > > > > > array to the runtime. Do you think it is going to be 
> > > > > > > > > > slower? In your current scheme, we generate many runtime 
> > > > > > > > > > calls instead. Could you try to estimate the number of 
> > > > > > > > > > calls in cases if we'll call the mappers through the 
> > > > > > > > > > indirect function calls and in your cuurent scheme, where 
> > > > > > > > > > we need to call the runtime functions many times in each 
> > > > > > > > > > particular mapper?
> > > > > > > > > Hi Alexey,
> > > > > > > > > 
> > > > > > > > > Sorry I don't understand your idea. What indirect function 
> > > > > > > > > calls do you propose to be passed to the runtime? What are 
> > > > > > > > > these functions supposed to do?
> > > > > > > > > 
> > > > > > > > > The number of function calls will be exactly equal to the 
> > > > > > > > > number of components mapped, no matter whether there are 
> > > > > > > > > nested mappers or not. The number of components depend on the 
> > > > > > > > > program. E.g., if we map a large array section, then there 
> > > > > > > > > will be many more function calls.
> > > > > > > > I mean the pointers to the mapper function, generated by the 
> > > > > > > > compiler. In your comment, it is `c.Mapper()`
> > > > > > > If we pass nested mapper functions to the runtime, I think it 
> > > > > > > will slow down execution because of the extra level of indirect 
> > > > > > > function calls. E.g., the runtime will call `omp_mapper1`, which 
> > > > > > > calls the runtime back, which calls `omp_mapper2`,  This can 
> > > > > > > result in a deep call stack.
> > > > > > > 
> > > > > > > I think the current implementation will be more efficient, which 
> > > > > > > doesn't pass nested mappers to the runtime. One call to the outer 
> > > > > > > most mapper function will have all data mapping done. The call 
> > > > > > > stack will be 2 level deep (the first level is the mapper 
> > > > > > > function, and the second level is `__tgt_push_mapper_component`) 
> > > > > > > in this case from the runtime. There are also more 

[clang-tools-extra] r364464 - BitStream reader: propagate errors

2019-06-26 Thread JF Bastien via cfe-commits
Author: jfb
Date: Wed Jun 26 12:50:12 2019
New Revision: 364464

URL: http://llvm.org/viewvc/llvm-project?rev=364464=rev
Log:
BitStream reader: propagate errors

The bitstream reader handles errors poorly. This has two effects:

 * Bugs in file handling (especially modules) manifest as an "unexpected end of
   file" crash
 * Users of clang as a library end up aborting because the code unconditionally
   calls `report_fatal_error`

The bitstream reader should be more resilient and return Expected / Error as
soon as an error is encountered, not way late like it does now. This patch
starts doing so and adopting the error handling where I think it makes sense.
There's plenty more to do: this patch propagates errors to be minimally useful,
and follow-ups will propagate them further and improve diagnostics.

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


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

Modified:
clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp
clang-tools-extra/trunk/clang-doc/BitcodeWriter.cpp
clang-tools-extra/trunk/clang-doc/BitcodeWriter.h
clang-tools-extra/trunk/clangd/ClangdUnit.cpp
clang-tools-extra/trunk/clangd/CodeComplete.cpp
clang-tools-extra/trunk/clangd/index/Background.cpp
clang-tools-extra/trunk/clangd/unittests/HeadersTests.cpp

Modified: clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp?rev=364464=364463=364464=diff
==
--- clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp (original)
+++ clang-tools-extra/trunk/clang-doc/BitcodeReader.cpp Wed Jun 26 12:50:12 2019
@@ -491,24 +491,27 @@ template 
 llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, T I) {
   Record R;
   llvm::StringRef Blob;
-  unsigned RecID = Stream.readRecord(ID, R, );
-  return parseRecord(R, RecID, Blob, I);
+  llvm::Expected MaybeRecID = Stream.readRecord(ID, R, );
+  if (!MaybeRecID)
+return MaybeRecID.takeError();
+  return parseRecord(R, MaybeRecID.get(), Blob, I);
 }
 
 template <>
 llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, Reference *I) {
   Record R;
   llvm::StringRef Blob;
-  unsigned RecID = Stream.readRecord(ID, R, );
-  return parseRecord(R, RecID, Blob, I, CurrentReferenceField);
+  llvm::Expected MaybeRecID = Stream.readRecord(ID, R, );
+  if (!MaybeRecID)
+return MaybeRecID.takeError();
+  return parseRecord(R, MaybeRecID.get(), Blob, I, CurrentReferenceField);
 }
 
 // Read a block of records into a single info.
 template 
 llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T I) {
-  if (Stream.EnterSubBlock(ID))
-return llvm::make_error("Unable to enter subblock.\n",
-   llvm::inconvertibleErrorCode());
+  if (llvm::Error Err = Stream.EnterSubBlock(ID))
+return Err;
 
   while (true) {
 unsigned BlockOrCode = 0;
@@ -521,9 +524,9 @@ llvm::Error ClangDocBitcodeReader::readB
 case Cursor::BlockEnd:
   return llvm::Error::success();
 case Cursor::BlockBegin:
-  if (auto Err = readSubBlock(BlockOrCode, I)) {
-if (!Stream.SkipBlock())
-  continue;
+  if (llvm::Error Err = readSubBlock(BlockOrCode, I)) {
+if (llvm::Error Skipped = Stream.SkipBlock())
+  return joinErrors(std::move(Err), std::move(Skipped));
 return Err;
   }
   continue;
@@ -605,18 +608,34 @@ ClangDocBitcodeReader::skipUntilRecordOr
   BlockOrRecordID = 0;
 
   while (!Stream.AtEndOfStream()) {
-unsigned Code = Stream.ReadCode();
+Expected MaybeCode = Stream.ReadCode();
+if (!MaybeCode) {
+  // FIXME this drops the error on the floor.
+  consumeError(MaybeCode.takeError());
+  return Cursor::BadBlock;
+}
 
-switch ((llvm::bitc::FixedAbbrevIDs)Code) {
+// FIXME check that the enum is in range.
+auto Code = static_cast(MaybeCode.get());
+
+switch (Code) {
 case llvm::bitc::ENTER_SUBBLOCK:
-  BlockOrRecordID = Stream.ReadSubBlockID();
+  if (Expected MaybeID = Stream.ReadSubBlockID())
+BlockOrRecordID = MaybeID.get();
+  else {
+// FIXME this drops the error on the floor.
+consumeError(MaybeID.takeError());
+  }
   return Cursor::BlockBegin;
 case llvm::bitc::END_BLOCK:
   if (Stream.ReadBlockEnd())
 return Cursor::BadBlock;
   return Cursor::BlockEnd;
 case llvm::bitc::DEFINE_ABBREV:
-  Stream.ReadAbbrevRecord();
+  if (llvm::Error Err = Stream.ReadAbbrevRecord()) {
+// FIXME this drops the error on the floor.
+consumeError(std::move(Err));
+  }
   continue;
 case llvm::bitc::UNABBREV_RECORD:
   return Cursor::BadBlock;
@@ -634,17 +653,24 @@ llvm::Error ClangDocBitcodeReader::valid
llvm::inconvertibleErrorCode());
 
   // Sniff for the signature.
-  if 

r364464 - BitStream reader: propagate errors

2019-06-26 Thread JF Bastien via cfe-commits
Author: jfb
Date: Wed Jun 26 12:50:12 2019
New Revision: 364464

URL: http://llvm.org/viewvc/llvm-project?rev=364464=rev
Log:
BitStream reader: propagate errors

The bitstream reader handles errors poorly. This has two effects:

 * Bugs in file handling (especially modules) manifest as an "unexpected end of
   file" crash
 * Users of clang as a library end up aborting because the code unconditionally
   calls `report_fatal_error`

The bitstream reader should be more resilient and return Expected / Error as
soon as an error is encountered, not way late like it does now. This patch
starts doing so and adopting the error handling where I think it makes sense.
There's plenty more to do: this patch propagates errors to be minimally useful,
and follow-ups will propagate them further and improve diagnostics.

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


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

Modified:
cfe/trunk/include/clang/Basic/Diagnostic.h
cfe/trunk/include/clang/Frontend/FrontendAction.h
cfe/trunk/include/clang/Serialization/ASTReader.h
cfe/trunk/include/clang/Serialization/GlobalModuleIndex.h
cfe/trunk/lib/Frontend/ASTUnit.cpp
cfe/trunk/lib/Frontend/CompilerInstance.cpp
cfe/trunk/lib/Frontend/FrontendAction.cpp
cfe/trunk/lib/Frontend/PrecompiledPreamble.cpp
cfe/trunk/lib/Frontend/Rewrite/FrontendActions.cpp
cfe/trunk/lib/Frontend/SerializedDiagnosticReader.cpp
cfe/trunk/lib/Frontend/TestModuleFileExtension.cpp
cfe/trunk/lib/Serialization/ASTReader.cpp
cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
cfe/trunk/lib/Serialization/ASTReaderStmt.cpp
cfe/trunk/lib/Serialization/GlobalModuleIndex.cpp
cfe/trunk/test/Index/pch-from-libclang.c

Modified: cfe/trunk/include/clang/Basic/Diagnostic.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Diagnostic.h?rev=364464=364463=364464=diff
==
--- cfe/trunk/include/clang/Basic/Diagnostic.h (original)
+++ cfe/trunk/include/clang/Basic/Diagnostic.h Wed Jun 26 12:50:12 2019
@@ -25,6 +25,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/Compiler.h"
+#include "llvm/Support/Error.h"
 #include 
 #include 
 #include 
@@ -1303,6 +1304,12 @@ inline DiagnosticBuilder DiagnosticsEngi
   return DiagnosticBuilder(this);
 }
 
+inline const DiagnosticBuilder <<(const DiagnosticBuilder ,
+   llvm::Error &) {
+  DB.AddString(toString(std::move(E)));
+  return DB;
+}
+
 inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
   return Report(SourceLocation(), DiagID);
 }

Modified: cfe/trunk/include/clang/Frontend/FrontendAction.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Frontend/FrontendAction.h?rev=364464=364463=364464=diff
==
--- cfe/trunk/include/clang/Frontend/FrontendAction.h (original)
+++ cfe/trunk/include/clang/Frontend/FrontendAction.h Wed Jun 26 12:50:12 2019
@@ -23,6 +23,7 @@
 #include "clang/Frontend/ASTUnit.h"
 #include "clang/Frontend/FrontendOptions.h"
 #include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Error.h"
 #include 
 #include 
 #include 
@@ -229,7 +230,7 @@ public:
   bool BeginSourceFile(CompilerInstance , const FrontendInputFile );
 
   /// Set the source manager's main input file, and run the action.
-  bool Execute();
+  llvm::Error Execute();
 
   /// Perform any per-file post processing, deallocate per-file
   /// objects, and run statistics and output file cleanup code.

Modified: cfe/trunk/include/clang/Serialization/ASTReader.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Serialization/ASTReader.h?rev=364464=364463=364464=diff
==
--- cfe/trunk/include/clang/Serialization/ASTReader.h (original)
+++ cfe/trunk/include/clang/Serialization/ASTReader.h Wed Jun 26 12:50:12 2019
@@ -1437,6 +1437,7 @@ private:
   void Error(StringRef Msg) const;
   void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
  StringRef Arg2 = StringRef()) const;
+  void Error(llvm::Error &) const;
 
 public:
   /// Load the AST file and validate its contents against the given
@@ -2379,7 +2380,8 @@ public:
 
   /// Reads a record with id AbbrevID from Cursor, resetting the
   /// internal state.
-  unsigned readRecord(llvm::BitstreamCursor , unsigned AbbrevID);
+  Expected readRecord(llvm::BitstreamCursor ,
+unsigned AbbrevID);
 
   /// Is this a module file for a module (rather than a PCH or similar).
   bool isModule() const { return F->isModule(); }
@@ -2679,7 +2681,10 @@ struct SavedStreamPosition {
   : Cursor(Cursor), Offset(Cursor.GetCurrentBitNo()) {}
 
   ~SavedStreamPosition() {
-Cursor.JumpToBit(Offset);
+if (llvm::Error Err = 

[PATCH] D59474: [OpenMP 5.0] Codegen support for user-defined mappers

2019-06-26 Thread Lingda Li via Phabricator via cfe-commits
lildmh marked 2 inline comments as done.
lildmh added inline comments.



Comment at: lib/CodeGen/CGOpenMPRuntime.cpp:8739
+/// // For each component specified by this mapper:
+/// if (currentComponent.hasMapper())
+///   (*currentComponent.Mapper())(rt_mapper_handle, arg_base, arg_begin,

ABataev wrote:
> lildmh wrote:
> > ABataev wrote:
> > > lildmh wrote:
> > > > ABataev wrote:
> > > > > lildmh wrote:
> > > > > > ABataev wrote:
> > > > > > > lildmh wrote:
> > > > > > > > ABataev wrote:
> > > > > > > > > lildmh wrote:
> > > > > > > > > > ABataev wrote:
> > > > > > > > > > > lildmh wrote:
> > > > > > > > > > > > ABataev wrote:
> > > > > > > > > > > > > Currently `currentComponent` is generated by the 
> > > > > > > > > > > > > compiler. But can we instead pass this data as an 
> > > > > > > > > > > > > extra parameter to this `omp_mapper` function.
> > > > > > > > > > > > Emm, I think this scheme will be very difficult and 
> > > > > > > > > > > > inefficient. If we pass components as an argument of 
> > > > > > > > > > > > `omp_mapper` function, it means that the runtime needs 
> > > > > > > > > > > > to generate all components related to a map clause. I 
> > > > > > > > > > > > don't think the runtime is able to do that efficiently. 
> > > > > > > > > > > > On the other hand, in the current scheme, these 
> > > > > > > > > > > > components are naturally generated by the compiler, and 
> > > > > > > > > > > > the runtime only needs to know the base pointer, 
> > > > > > > > > > > > pointer, type, size. etc.
> > > > > > > > > > > With the current scheme, we may end with the code 
> > > > > > > > > > > blowout. We need to generate very similar code for 
> > > > > > > > > > > different types and variables. The worst thing here is 
> > > > > > > > > > > that we will be unable to optimize this huge amount of 
> > > > > > > > > > > code because the codegen relies on the runtime functions 
> > > > > > > > > > > and the code cannot be inlined. That's why I would like 
> > > > > > > > > > > to move as much as possible code to the runtime rather 
> > > > > > > > > > > than to emit it in the compiler. 
> > > > > > > > > > I understand your concerns. I think this is the best we can 
> > > > > > > > > > do right now.
> > > > > > > > > > 
> > > > > > > > > > The most worrisome case will be when we have nested mappers 
> > > > > > > > > > within each other. In this case, a mapper function will 
> > > > > > > > > > call another mapper function. We can inline the inner 
> > > > > > > > > > mapper functions in this scenario, so that these mapper 
> > > > > > > > > > function can be properly optimized. As a result, I think 
> > > > > > > > > > the performance should be fine.
> > > > > > > > > Instead, we can use indirect function calls passed in the 
> > > > > > > > > array to the runtime. Do you think it is going to be slower? 
> > > > > > > > > In your current scheme, we generate many runtime calls 
> > > > > > > > > instead. Could you try to estimate the number of calls in 
> > > > > > > > > cases if we'll call the mappers through the indirect function 
> > > > > > > > > calls and in your cuurent scheme, where we need to call the 
> > > > > > > > > runtime functions many times in each particular mapper?
> > > > > > > > Hi Alexey,
> > > > > > > > 
> > > > > > > > Sorry I don't understand your idea. What indirect function 
> > > > > > > > calls do you propose to be passed to the runtime? What are 
> > > > > > > > these functions supposed to do?
> > > > > > > > 
> > > > > > > > The number of function calls will be exactly equal to the 
> > > > > > > > number of components mapped, no matter whether there are nested 
> > > > > > > > mappers or not. The number of components depend on the program. 
> > > > > > > > E.g., if we map a large array section, then there will be many 
> > > > > > > > more function calls.
> > > > > > > I mean the pointers to the mapper function, generated by the 
> > > > > > > compiler. In your comment, it is `c.Mapper()`
> > > > > > If we pass nested mapper functions to the runtime, I think it will 
> > > > > > slow down execution because of the extra level of indirect function 
> > > > > > calls. E.g., the runtime will call `omp_mapper1`, which calls the 
> > > > > > runtime back, which calls `omp_mapper2`,  This can result in a 
> > > > > > deep call stack.
> > > > > > 
> > > > > > I think the current implementation will be more efficient, which 
> > > > > > doesn't pass nested mappers to the runtime. One call to the outer 
> > > > > > most mapper function will have all data mapping done. The call 
> > > > > > stack will be 2 level deep (the first level is the mapper function, 
> > > > > > and the second level is `__tgt_push_mapper_component`) in this case 
> > > > > > from the runtime. There are also more compiler optimization space 
> > > > > > when we inline all nested mapper functions.
> > > > > Yes, if we leave it as is. But if instead of the 

[PATCH] D63786: Print NULL as "(null)" in diagnostic message

2019-06-26 Thread Xing Xue via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL364462: Print NULL as (null) in diagnostic 
message (authored by xingxue, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D63786?vs=206514=206724#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D63786

Files:
  cfe/trunk/tools/c-index-test/c-index-test.c


Index: cfe/trunk/tools/c-index-test/c-index-test.c
===
--- cfe/trunk/tools/c-index-test/c-index-test.c
+++ cfe/trunk/tools/c-index-test/c-index-test.c
@@ -1053,7 +1053,8 @@
 if (Cursor.kind == CXCursor_InclusionDirective) {
   CXFile File = clang_getIncludedFile(Cursor);
   CXString Included = clang_getFileName(File);
-  printf(" (%s)", clang_getCString(Included));
+  const char *IncludedString = clang_getCString(Included);
+  printf(" (%s)", IncludedString ? IncludedString : "(null)");
   clang_disposeString(Included);
   
   if (clang_isFileMultipleIncludeGuarded(TU, File))
@@ -4644,18 +4645,19 @@
 CXFile File;
 CXString FileName, DiagSpelling, DiagOption, DiagCat;
 unsigned line, column, offset;
-const char *DiagOptionStr = 0, *DiagCatStr = 0;
+const char *FileNameStr = 0, *DiagOptionStr = 0, *DiagCatStr = 0;
 
 D = clang_getDiagnosticInSet(Diags, i);
 DiagLoc = clang_getDiagnosticLocation(D);
 clang_getExpansionLocation(DiagLoc, , , , );
 FileName = clang_getFileName(File);
+FileNameStr = clang_getCString(FileName);
 DiagSpelling = clang_getDiagnosticSpelling(D);
-
+
 printIndent(indent);
 
 fprintf(stderr, "%s:%d:%d: %s: %s",
-clang_getCString(FileName),
+FileNameStr ? FileNameStr : "(null)",
 line,
 column,
 getSeverityString(clang_getDiagnosticSeverity(D)),


Index: cfe/trunk/tools/c-index-test/c-index-test.c
===
--- cfe/trunk/tools/c-index-test/c-index-test.c
+++ cfe/trunk/tools/c-index-test/c-index-test.c
@@ -1053,7 +1053,8 @@
 if (Cursor.kind == CXCursor_InclusionDirective) {
   CXFile File = clang_getIncludedFile(Cursor);
   CXString Included = clang_getFileName(File);
-  printf(" (%s)", clang_getCString(Included));
+  const char *IncludedString = clang_getCString(Included);
+  printf(" (%s)", IncludedString ? IncludedString : "(null)");
   clang_disposeString(Included);
   
   if (clang_isFileMultipleIncludeGuarded(TU, File))
@@ -4644,18 +4645,19 @@
 CXFile File;
 CXString FileName, DiagSpelling, DiagOption, DiagCat;
 unsigned line, column, offset;
-const char *DiagOptionStr = 0, *DiagCatStr = 0;
+const char *FileNameStr = 0, *DiagOptionStr = 0, *DiagCatStr = 0;
 
 D = clang_getDiagnosticInSet(Diags, i);
 DiagLoc = clang_getDiagnosticLocation(D);
 clang_getExpansionLocation(DiagLoc, , , , );
 FileName = clang_getFileName(File);
+FileNameStr = clang_getCString(FileName);
 DiagSpelling = clang_getDiagnosticSpelling(D);
-
+
 printIndent(indent);
 
 fprintf(stderr, "%s:%d:%d: %s: %s",
-clang_getCString(FileName),
+FileNameStr ? FileNameStr : "(null)",
 line,
 column,
 getSeverityString(clang_getDiagnosticSeverity(D)),
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r364462 - Print NULL as "(null)" in diagnostic message

2019-06-26 Thread Xing Xue via cfe-commits
Author: xingxue
Date: Wed Jun 26 12:27:16 2019
New Revision: 364462

URL: http://llvm.org/viewvc/llvm-project?rev=364462=rev
Log:
Print NULL as "(null)" in diagnostic message

Summary:
Passing a null pointer to the printf family for a %s format specifier leads to 
undefined behaviour. The tests currently expect (null). Explicitly test for a 
null pointer and provide the expected string.

Authored By: andusy

Reviewers: hubert.reinterpretcast, xingxue, jasonliu, daltenty, cebowleratibm

Reviewed By: hubert.reinterpretcast

Subscribers: arphaman, jsji, cfe-commits

Tags: #llvm

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

Modified:
cfe/trunk/tools/c-index-test/c-index-test.c

Modified: cfe/trunk/tools/c-index-test/c-index-test.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/c-index-test/c-index-test.c?rev=364462=364461=364462=diff
==
--- cfe/trunk/tools/c-index-test/c-index-test.c (original)
+++ cfe/trunk/tools/c-index-test/c-index-test.c Wed Jun 26 12:27:16 2019
@@ -1053,7 +1053,8 @@ static void PrintCursor(CXCursor Cursor,
 if (Cursor.kind == CXCursor_InclusionDirective) {
   CXFile File = clang_getIncludedFile(Cursor);
   CXString Included = clang_getFileName(File);
-  printf(" (%s)", clang_getCString(Included));
+  const char *IncludedString = clang_getCString(Included);
+  printf(" (%s)", IncludedString ? IncludedString : "(null)");
   clang_disposeString(Included);
   
   if (clang_isFileMultipleIncludeGuarded(TU, File))
@@ -4644,18 +4645,19 @@ static void printDiagnosticSet(CXDiagnos
 CXFile File;
 CXString FileName, DiagSpelling, DiagOption, DiagCat;
 unsigned line, column, offset;
-const char *DiagOptionStr = 0, *DiagCatStr = 0;
+const char *FileNameStr = 0, *DiagOptionStr = 0, *DiagCatStr = 0;
 
 D = clang_getDiagnosticInSet(Diags, i);
 DiagLoc = clang_getDiagnosticLocation(D);
 clang_getExpansionLocation(DiagLoc, , , , );
 FileName = clang_getFileName(File);
+FileNameStr = clang_getCString(FileName);
 DiagSpelling = clang_getDiagnosticSpelling(D);
-
+
 printIndent(indent);
 
 fprintf(stderr, "%s:%d:%d: %s: %s",
-clang_getCString(FileName),
+FileNameStr ? FileNameStr : "(null)",
 line,
 column,
 getSeverityString(clang_getDiagnosticSeverity(D)),


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


[PATCH] D59474: [OpenMP 5.0] Codegen support for user-defined mappers

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



Comment at: lib/CodeGen/CGOpenMPRuntime.cpp:8739
+/// // For each component specified by this mapper:
+/// if (currentComponent.hasMapper())
+///   (*currentComponent.Mapper())(rt_mapper_handle, arg_base, arg_begin,

lildmh wrote:
> ABataev wrote:
> > lildmh wrote:
> > > ABataev wrote:
> > > > lildmh wrote:
> > > > > ABataev wrote:
> > > > > > lildmh wrote:
> > > > > > > ABataev wrote:
> > > > > > > > lildmh wrote:
> > > > > > > > > ABataev wrote:
> > > > > > > > > > lildmh wrote:
> > > > > > > > > > > ABataev wrote:
> > > > > > > > > > > > Currently `currentComponent` is generated by the 
> > > > > > > > > > > > compiler. But can we instead pass this data as an extra 
> > > > > > > > > > > > parameter to this `omp_mapper` function.
> > > > > > > > > > > Emm, I think this scheme will be very difficult and 
> > > > > > > > > > > inefficient. If we pass components as an argument of 
> > > > > > > > > > > `omp_mapper` function, it means that the runtime needs to 
> > > > > > > > > > > generate all components related to a map clause. I don't 
> > > > > > > > > > > think the runtime is able to do that efficiently. On the 
> > > > > > > > > > > other hand, in the current scheme, these components are 
> > > > > > > > > > > naturally generated by the compiler, and the runtime only 
> > > > > > > > > > > needs to know the base pointer, pointer, type, size. etc.
> > > > > > > > > > With the current scheme, we may end with the code blowout. 
> > > > > > > > > > We need to generate very similar code for different types 
> > > > > > > > > > and variables. The worst thing here is that we will be 
> > > > > > > > > > unable to optimize this huge amount of code because the 
> > > > > > > > > > codegen relies on the runtime functions and the code cannot 
> > > > > > > > > > be inlined. That's why I would like to move as much as 
> > > > > > > > > > possible code to the runtime rather than to emit it in the 
> > > > > > > > > > compiler. 
> > > > > > > > > I understand your concerns. I think this is the best we can 
> > > > > > > > > do right now.
> > > > > > > > > 
> > > > > > > > > The most worrisome case will be when we have nested mappers 
> > > > > > > > > within each other. In this case, a mapper function will call 
> > > > > > > > > another mapper function. We can inline the inner mapper 
> > > > > > > > > functions in this scenario, so that these mapper function can 
> > > > > > > > > be properly optimized. As a result, I think the performance 
> > > > > > > > > should be fine.
> > > > > > > > Instead, we can use indirect function calls passed in the array 
> > > > > > > > to the runtime. Do you think it is going to be slower? In your 
> > > > > > > > current scheme, we generate many runtime calls instead. Could 
> > > > > > > > you try to estimate the number of calls in cases if we'll call 
> > > > > > > > the mappers through the indirect function calls and in your 
> > > > > > > > cuurent scheme, where we need to call the runtime functions 
> > > > > > > > many times in each particular mapper?
> > > > > > > Hi Alexey,
> > > > > > > 
> > > > > > > Sorry I don't understand your idea. What indirect function calls 
> > > > > > > do you propose to be passed to the runtime? What are these 
> > > > > > > functions supposed to do?
> > > > > > > 
> > > > > > > The number of function calls will be exactly equal to the number 
> > > > > > > of components mapped, no matter whether there are nested mappers 
> > > > > > > or not. The number of components depend on the program. E.g., if 
> > > > > > > we map a large array section, then there will be many more 
> > > > > > > function calls.
> > > > > > I mean the pointers to the mapper function, generated by the 
> > > > > > compiler. In your comment, it is `c.Mapper()`
> > > > > If we pass nested mapper functions to the runtime, I think it will 
> > > > > slow down execution because of the extra level of indirect function 
> > > > > calls. E.g., the runtime will call `omp_mapper1`, which calls the 
> > > > > runtime back, which calls `omp_mapper2`,  This can result in a 
> > > > > deep call stack.
> > > > > 
> > > > > I think the current implementation will be more efficient, which 
> > > > > doesn't pass nested mappers to the runtime. One call to the outer 
> > > > > most mapper function will have all data mapping done. The call stack 
> > > > > will be 2 level deep (the first level is the mapper function, and the 
> > > > > second level is `__tgt_push_mapper_component`) in this case from the 
> > > > > runtime. There are also more compiler optimization space when we 
> > > > > inline all nested mapper functions.
> > > > Yes, if we leave it as is. But if instead of the bunch unique functions 
> > > > we'll have the common one, that accept list if indirect pointers to 
> > > > functions additionally, and move it to the runtime library, we won't 
> > > > need those 2 functions we have currently. 

[PATCH] D62977: [clang-tidy]: Google: new check 'google-upgrade-googletest-case'

2019-06-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In D62977#1559637 , @astrelni wrote:

> In D62977#1559628 , @lebedev.ri 
> wrote:
>
> > It //sounds// correct, but i don't see accompanying test changes, so i 
> > can't be sure.
>
>
> The tests as they are cover the positive case in that they would not show 
> warning or fixes if we didn't find the replacements.


Yep

In D62977#1559637 , @astrelni wrote:

> The only way to test the negative is to make a second test with a second set 
> of mock googletest headers that declare things in the v1.8 way. Is this what 
> you would prefer?


If that is what it takes to get the test coverage, i suppose so.


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

https://reviews.llvm.org/D62977



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


[PATCH] D62977: [clang-tidy]: Google: new check 'google-upgrade-googletest-case'

2019-06-26 Thread Alex Strelnikov via Phabricator via cfe-commits
astrelni added a comment.

In D62977#1559628 , @lebedev.ri wrote:

> It //sounds// correct, but i don't see accompanying test changes, so i can't 
> be sure.


The tests as they are cover the positive case in that they would not show 
warning or fixes if we didn't find the replacements. The only way to test the 
negative is to make a second test with a second set of mock googletest headers 
that declare things in the v1.8 way. Is this what you would prefer?


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

https://reviews.llvm.org/D62977



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


[PATCH] D63681: [clang-scan-deps] Introduce the DependencyScanning library with the thread worker code and better error handling

2019-06-26 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea added a subscriber: rnk.
aganea added a comment.

A bit more detail on what we're seeing on our end (specs in the post above). 
The 'Count' column represents the number of 1ms samples taken in that function. 
The 'Weight' column is cumulated times for all cores, for a given process, in 
ms.

Image below shows most of the time is spent in `clang-scan-deps.dll` and 
indirectly, in `ntoskrnl.exe`. The graph at the bottom also shows that 
preprocessing the ~600 unity .CPP files in the project issues 16 million IOPS. 
The graphs on the right show no bottlenecks on the disk I/O on the OS I/O-side.

F9417850: clang-scan-deps.jpg 

Top functions in `ntoskrnl.exe`, most callstacks end up in 
`clang-scan-deps.dll`:

F9417863: clang-scan-deps2.jpg 

A good chunk of all this is caused by `llvm::sys::status()`, even though is 
goes through the `FileSystemStatCache`, like I was suggesting previously 
 (ping @rnk)
//(beware, the callstacks are reversed in the image below)//

F9417870: clang-status.JPG 

I can take a look at `llvm::sys::status()` after the vacations (somewhere in 
August)


Repository:
  rC Clang

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

https://reviews.llvm.org/D63681



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


[PATCH] D63623: [clang-tidy] new check: bugprone-posix-return

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



Comment at: clang-tools-extra/clang-tidy/bugprone/PosixReturnCheck.cpp:49
+diag(OperatorLoc, "POSIX functions (except posix_openpt) never return 
negative values")
+<< FixItHint::CreateReplacement(OperatorLoc, Twine(">").str());
+return;

jcai19 wrote:
> gribozavr wrote:
> > Please add tests for fix-its.
> The fix-it is triggered when cases like posix_*(...) < 0 are detected (except 
> posix_openpt) , which are currently covered in the unit test. The test 
> runtime will make sure fix-its are applied.
Could you add CHECK-FIXES lines to validate the fixit directly?



Comment at: clang-tools-extra/test/clang-tidy/bugprone-posix-return.cpp:96
+  if (posix_fadvise(0, 0, 0, 0) < 0) {}
+  if (posix_fadvise(0, 0, 0, 0) >= 0) {} else {}
+  if (posix_fadvise(0, 0, 0, 0) == -1) {}

jcai19 wrote:
> gribozavr wrote:
> > Shouldn't there be a warning in the else branch?
> This check only matches calls to the POSIX functions in the global scope, not 
> member functions or functions defined within namespaces. Although in the 
> global scope,  this particular case will still pass as there won't be a ``<`` 
> binary operator for the else branch so no matching will happen.
Sorry, yes, that's what I meant -- if we warn on `< 0`, then we should warn on 
the else branch of `>=`. I just commented on the wrong test -- sorry about that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63623



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


[PATCH] D63835: [Syntax] Add nodes for most common statements

2019-06-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

This change mostly aims to illustrate that `TreeBuilder` seems to be powerful 
enough to go beyond basic nodes.
But it also introduces enough nodes to make the syntax trees minimally useful 
for traversing statement nodes. Hopefully that could become a good basis to 
define other APIs (mutations, etc).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63835



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


[PATCH] D62977: [clang-tidy]: Google: new check 'google-upgrade-googletest-case'

2019-06-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

It //sounds// correct, but i don't see accompanying test changes, so i can't be 
sure.


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

https://reviews.llvm.org/D62977



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


[PATCH] D62977: [clang-tidy]: Google: new check 'google-upgrade-googletest-case'

2019-06-26 Thread Alex Strelnikov via Phabricator via cfe-commits
astrelni added a comment.

In D62977#1559344 , @lebedev.ri wrote:

> In D62977#1559334 , @astrelni wrote:
>
> > In D62977#1556346 , @lebedev.ri 
> > wrote:
> >
> > > In D62977#1540184 , @lebedev.ri 
> > > wrote:
> > >
> > > > Without seeing the tests - what version checks does this have?
> > > >  It shouldn't fire if the googletest version is the one before that 
> > > > rename.
> > >
> > >
> > > I don't believe this question was answered.
> >
> >
> > Sorry, the original comment got lost between me updating two patches as I 
> > noticed I did it wrong without seeing your comment.
> >
> > Unfortunately there are no versioning macros in googletest, so I'm not sure 
> > how to keep this check from providing warnings if it is run while depending 
> > on a version that is too early. The new names are in master and will be 
> > part of an upcoming version 1.9 release. I have tried to update the 
> > documentation to clarify which version of googletest this intended for. 
> > Please let me know how you think we should proceed.
>
>
> I'm not fully current on what can and can't be done in clang-tidy, but i 
> suppose if the
>  check has matched something, then it must mean that the googletest headers 
> were parsed.
>  Can you perhaps look in the AST that the new names are present?
>  E.g. the new macros, specified in `getNewMacroName()`.


Yes, makes sense. Let me know what you think of the approach I've added in the 
latest diff. I think it is sufficient to check for the existence of one of the 
new macros in the right file and one new method in each matched class.


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

https://reviews.llvm.org/D62977



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


[PATCH] D62977: [clang-tidy]: Google: new check 'google-upgrade-googletest-case'

2019-06-26 Thread Alex Strelnikov via Phabricator via cfe-commits
astrelni updated this revision to Diff 206720.
astrelni marked 4 inline comments as done.

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

https://reviews.llvm.org/D62977

Files:
  clang-tools-extra/clang-tidy/google/CMakeLists.txt
  clang-tools-extra/clang-tidy/google/GoogleTidyModule.cpp
  clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp
  clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/google-upgrade-googletest-case.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/Inputs/gtest/gtest-typed-test.h
  clang-tools-extra/test/clang-tidy/Inputs/gtest/gtest.h
  clang-tools-extra/test/clang-tidy/google-upgrade-googletest-case.cpp
  llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/google/BUILD.gn

Index: llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/google/BUILD.gn
===
--- llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/google/BUILD.gn
+++ llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/google/BUILD.gn
@@ -28,6 +28,7 @@
 "OverloadedUnaryAndCheck.cpp",
 "TodoCommentCheck.cpp",
 "UnnamedNamespaceInHeaderCheck.cpp",
+"UpgradeGoogletestCaseCheck.cpp",
 "UsingNamespaceDirectiveCheck.cpp",
   ]
 }
Index: clang-tools-extra/test/clang-tidy/google-upgrade-googletest-case.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/google-upgrade-googletest-case.cpp
@@ -0,0 +1,991 @@
+// RUN: %check_clang_tidy %s google-upgrade-googletest-case %t -- -- -I%S/Inputs
+
+#include "gtest/gtest.h"
+
+// 
+// Macros
+
+TYPED_TEST_CASE(FooTest, FooTypes);
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning: Google Test APIs named with 'case' are deprecated; use equivalent APIs named with 'suite'
+// CHECK-FIXES: TYPED_TEST_SUITE(FooTest, FooTypes);
+TYPED_TEST_CASE_P(FooTest);
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning: Google Test APIs named with 'case'
+// CHECK-FIXES: TYPED_TEST_SUITE_P(FooTest);
+REGISTER_TYPED_TEST_CASE_P(FooTest, FooTestName);
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning: Google Test APIs named with 'case'
+// CHECK-FIXES: REGISTER_TYPED_TEST_SUITE_P(FooTest, FooTestName);
+INSTANTIATE_TYPED_TEST_CASE_P(FooPrefix, FooTest, FooTypes);
+// CHECK-MESSAGES: [[@LINE-1]]:1: warning: Google Test APIs named with 'case'
+// CHECK-FIXES: INSTANTIATE_TYPED_TEST_SUITE_P(FooPrefix, FooTest, FooTypes);
+
+#ifdef TYPED_TEST_CASE
+// CHECK-MESSAGES: [[@LINE-1]]:2: warning: Google Test APIs named with 'case'
+#undef TYPED_TEST_CASE
+// CHECK-MESSAGES: [[@LINE-1]]:8: warning: Google Test APIs named with 'case'
+#define TYPED_TEST_CASE TYPED_TEST_SUITE
+#endif
+
+#ifdef TYPED_TEST_CASE_P
+// CHECK-MESSAGES: [[@LINE-1]]:2: warning: Google Test APIs named with 'case'
+#undef TYPED_TEST_CASE_P
+// CHECK-MESSAGES: [[@LINE-1]]:8: warning: Google Test APIs named with 'case'
+#define TYPED_TEST_CASE_P TYPED_TEST_SUITE_P
+#endif
+
+#ifdef REGISTER_TYPED_TEST_CASE_P
+// CHECK-MESSAGES: [[@LINE-1]]:2: warning: Google Test APIs named with 'case'
+#undef REGISTER_TYPED_TEST_CASE_P
+// CHECK-MESSAGES: [[@LINE-1]]:8: warning: Google Test APIs named with 'case'
+#define REGISTER_TYPED_TEST_CASE_P REGISTER_TYPED_TEST_SUITE_P
+#endif
+
+#ifdef INSTANTIATE_TYPED_TEST_CASE_P
+// CHECK-MESSAGES: [[@LINE-1]]:2: warning: Google Test APIs named with 'case'
+#undef INSTANTIATE_TYPED_TEST_CASE_P
+// CHECK-MESSAGES: [[@LINE-1]]:8: warning: Google Test APIs named with 'case'
+#define INSTANTIATE_TYPED_TEST_CASE_P INSTANTIATE_TYPED_TEST_SUITE_P
+#endif
+
+TYPED_TEST_CASE(FooTest, FooTypes);
+TYPED_TEST_CASE_P(FooTest);
+REGISTER_TYPED_TEST_CASE_P(FooTest, FooTestName);
+INSTANTIATE_TYPED_TEST_CASE_P(FooPrefix, FooTest, FooTypes);
+
+// 
+// testing::Test
+
+class FooTest : public testing::Test {
+public:
+  static void SetUpTestCase();
+  // CHECK-MESSAGES: [[@LINE-1]]:15: warning: Google Test APIs named with 'case'
+  // CHECK-FIXES: static void SetUpTestSuite();
+  static void TearDownTestCase();
+  // CHECK-MESSAGES: [[@LINE-1]]:15: warning: Google Test APIs named with 'case'
+  // CHECK-FIXES: static void TearDownTestSuite();
+};
+
+void FooTest::SetUpTestCase() {}
+// CHECK-MESSAGES: [[@LINE-1]]:15: warning: Google Test APIs named with 'case'
+// CHECK-FIXES: void FooTest::SetUpTestSuite() {}
+
+void FooTest::TearDownTestCase() {}
+// CHECK-MESSAGES: [[@LINE-1]]:15: warning: Google Test APIs named with 'case'
+// CHECK-FIXES: void FooTest::TearDownTestSuite() {}
+
+template  class FooTypedTest : public testing::Test {
+public:
+  static void SetUpTestCase();
+  // CHECK-MESSAGES: [[@LINE-1]]:15: warning: Google Test APIs named with 'case'
+  // CHECK-FIXES: static 

[PATCH] D63835: [Syntax] Add nodes for most common statements

2019-06-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added a reviewer: sammccall.
Herald added a project: clang.
ilya-biryukov added a parent revision: D61637: [Syntax] Introduce syntax trees.

Most of the statements mirror the ones provided by clang AST.
Major differences are:

- expressions are wrapped into 'ExpressionStatement' instead of being a 
subclass of statement,
- semicolons are always consumed by the leaf expressions (return, expression 
satement, etc),
- some clang statements are not handled yet, we wrap those into an 
UnknownStatement class, which is not present in clang.

We also define an 'Expression' and 'UnknownExpression' classes in order
to produce 'ExpressionStatement' where needed. The actual implementation
of expressions is not yet ready, it will follow later.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D63835

Files:
  clang/include/clang/Tooling/Syntax/Nodes.h
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/lib/Tooling/Syntax/Nodes.cpp
  clang/unittests/Tooling/Syntax/TreeTest.cpp

Index: clang/unittests/Tooling/Syntax/TreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/TreeTest.cpp
+++ clang/unittests/Tooling/Syntax/TreeTest.cpp
@@ -137,7 +137,7 @@
 | |-)
 | `-CompoundStatement
 |   |-1: {
-|   `-2: }
+|   `-3: }
 |-TopLevelDeclaration
 | |-void
 | |-foo
@@ -145,10 +145,317 @@
 | |-)
 | `-CompoundStatement
 |   |-1: {
-|   `-2: }
+|   `-3: }
 `-1: 
 )txt"},
-  };
+  // if.
+  {
+  R"cpp(
+int main() {
+  if (true) {}
+  if (true) {} else if (false) {}
+}
+)cpp",
+  R"txt(
+*: TranslationUnitDeclaration
+|-TopLevelDeclaration
+| |-int
+| |-main
+| |-(
+| |-)
+| `-CompoundStatement
+|   |-1: {
+|   |-2: IfStatement
+|   | |-1: if
+|   | |-(
+|   | |-UnknownExpression
+|   | | `-true
+|   | |-)
+|   | `-2: CompoundStatement
+|   |   |-1: {
+|   |   `-3: }
+|   |-2: IfStatement
+|   | |-1: if
+|   | |-(
+|   | |-UnknownExpression
+|   | | `-true
+|   | |-)
+|   | |-2: CompoundStatement
+|   | | |-1: {
+|   | | `-3: }
+|   | |-3: else
+|   | `-4: IfStatement
+|   |   |-1: if
+|   |   |-(
+|   |   |-UnknownExpression
+|   |   | `-false
+|   |   |-)
+|   |   `-2: CompoundStatement
+|   | |-1: {
+|   | `-3: }
+|   `-3: }
+`-1: 
+)txt"},
+  // for.
+  {R"cpp(
+void test() {
+  for (;;)  {}
+}
+)cpp",
+   R"txt(
+*: TranslationUnitDeclaration
+|-TopLevelDeclaration
+| |-void
+| |-test
+| |-(
+| |-)
+| `-CompoundStatement
+|   |-1: {
+|   |-2: ForStatement
+|   | |-1: for
+|   | |-(
+|   | |-;
+|   | |-;
+|   | |-)
+|   | `-2: CompoundStatement
+|   |   |-1: {
+|   |   `-3: }
+|   `-3: }
+`-1: 
+)txt"},
+  // declaration statement.
+  {"void test() { int a = 10; }",
+   R"txt(
+*: TranslationUnitDeclaration
+|-TopLevelDeclaration
+| |-void
+| |-test
+| |-(
+| |-)
+| `-CompoundStatement
+|   |-1: {
+|   |-2: DeclarationStatement
+|   | |-int
+|   | |-a
+|   | |-=
+|   | |-10
+|   | `-;
+|   `-3: }
+`-1: 
+)txt"},
+  {"void test() { ; }", R"txt(
+*: TranslationUnitDeclaration
+|-TopLevelDeclaration
+| |-void
+| |-test
+| |-(
+| |-)
+| `-CompoundStatement
+|   |-1: {
+|   |-2: EmptyStatement
+|   | `-;
+|   `-3: }
+`-1: 
+)txt"},
+  // switch, case and default.
+  {R"cpp(
+void test() {
+  switch (true) {
+case 0:
+default:;
+  }
+}
+)cpp",
+   R"txt(
+*: TranslationUnitDeclaration
+|-TopLevelDeclaration
+| |-void
+| |-test
+| |-(
+| |-)
+| `-CompoundStatement
+|   |-1: {
+|   |-2: SwitchStatement
+|   | |-1: switch
+|   | |-(
+|   | |-UnknownExpression
+|   | | `-true
+|   | |-)
+|   | `-2: CompoundStatement
+|   |   |-1: {
+|   |   |-2: CaseStatement
+|   |   | |-1: case
+|   |   | |-UnknownExpression
+|   |   | | `-0
+|   |   | |-:
+|   |   | `-2: DefaultStatement
+|   |   |   |-1: default
+|   |   |   |-:
+|   |   |   `-2: EmptyStatement
+|   |   | `-;
+|   |   `-3: }
+|   `-3: }
+`-1: 
+)txt"},
+  // while.
+  {R"cpp(
+void test() {
+  while (true) { continue; break; }
+}
+)cpp",
+   R"txt(
+*: TranslationUnitDeclaration
+|-TopLevelDeclaration
+| |-void
+| |-test
+| |-(
+| |-)
+| `-CompoundStatement
+|   |-1: {
+|   |-2: WhileStatement
+|   | |-1: while
+|   | |-(
+|   | |-UnknownExpression
+|   | | `-true
+|   | |-)
+|   | `-2: CompoundStatement
+|   |   |-1: {
+|   |   |-2: ContinueStatement
+|   |   | |-1: continue
+|   |   | `-;
+|   |   |-2: BreakStatement
+|   |   | |-1: break
+|   |   | `-;
+|   |   `-3: }
+|   `-3: }
+`-1: 
+)txt"},
+  // return.
+  {R"cpp(
+int test() { return 1; }
+  )cpp",
+   R"txt(
+*: TranslationUnitDeclaration
+|-TopLevelDeclaration
+| |-int
+| |-test
+| |-(
+| |-)
+| `-CompoundStatement
+|   |-1: {
+|   |-2: ReturnStatement
+|   | |-1: return
+|   | |-UnknownExpression
+|   | | `-1
+|   | `-;
+|   `-3: }
+`-1: 
+   )txt"},
+  // Range-based for.
+  {R"cpp(
+void test() {
+  int a[3];
+  for (int x : a) ;
+}
+  )cpp",
+  

[PATCH] D63742: [WebAssembly] Implement Address Sanitizer for Emscripten

2019-06-26 Thread Sam Clegg via Phabricator via cfe-commits
sbc100 accepted this revision.
sbc100 added a comment.
This revision is now accepted and ready to land.

Remember to remove "A symbol __global_base is added so that code may know where 
the shadow
memory ends and real memory begins." from the CL description.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63742



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


[PATCH] D53157: Teach the IRBuilder about constrained fadd and friends

2019-06-26 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: include/llvm/IR/IntrinsicInst.h:235
+  ebStrict   ///< This corresponds to "fpexcept.strict".
 };
 

kpn wrote:
> rjmccall wrote:
> > kpn wrote:
> > > rjmccall wrote:
> > > > Is it okay that `ebUnspecified` and `ebInvalid` overlap here?
> > > I can think of a couple of alternatives. If they don't overlap then we 
> > > have to go back and sweep the source to make sure that ebUnspecified is 
> > > always handled in all cases that currently handle ebInvalid. And in the 
> > > future nobody is allowed to check in source that doesn't handle both.
> > > 
> > > Or, we could drop ebUnspecified, but then ebInvalid would have a valid 
> > > meaning to the IRBuilder interface. That looks like a bug even if it 
> > > works properly.
> > > 
> > > Generally, adding eb/rmUnspecified but having them overlap the invalid 
> > > cases seems to me to be the best option.
> > What is the purpose of `ebInvalid`?  Is this a valid argument to the 
> > intrinsic, or is it there so that `getExceptionBehavior()` has something to 
> > return if it doesn't recognize the argument?  For the latter, maybe it 
> > would be better to just assert that the argument was one of the recognized 
> > possibilities; we don't generally expect LLVM to silently propagate 
> > ill-formed IR.  Or if it's valid to not provide exception behavior to the 
> > intrinsic, maybe that's the same as `ebUnspecified`, or maybe the accessor 
> > should return `Optional`.
> The current code is in ConstrainedFPIntrinsic::getExceptionBehavior(), which 
> returns ebInvalid if the metadata is missing or somehow wrong (wrong type, 
> invalid string, etc). This is then used by the IR verifier which fails with 
> an Assert() if it gets ebInvalid. So we aren't propagating ill-formed IR.
> 
> The intrinsic requires the metadata, and it requires the metadata be valid. 
> But I don't want to clutter up IRBuilder's consumer's code. That's why I 
> wanted the API to allow those arguments to not be given.
> 
> One idea of mine is to have ebInvalid be valid when given to the IRBuilder, 
> and the meaning would be "this value is unspecified". But that seems weird.
> 
> Maybe there's another way.
> The current code is in ConstrainedFPIntrinsic::getExceptionBehavior(), which 
> returns ebInvalid if the metadata is missing or somehow wrong (wrong type, 
> invalid string, etc). This is then used by the IR verifier which fails with 
> an Assert() if it gets ebInvalid. So we aren't propagating ill-formed IR.

Okay, in that case, I don't understand why this accessor shouldn't just assume 
that it's working on valid IR and not be able to return `ebInvalid`.

> The intrinsic requires the metadata, and it requires the metadata be valid. 
> But I don't want to clutter up IRBuilder's consumer's code. That's why I 
> wanted the API to allow those arguments to not be given.

If you want the `IRBuilder` factories to be able to not take a value (if 
there's some defaulting scheme that's more complicated than you can express 
with a default argument), you can have it take an `Optional`, and 
then people can just pass in `None`; and then you don't need to muddy up the 
enum with a case that isn't really a valid alternative.


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

https://reviews.llvm.org/D53157



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


[PATCH] D63742: [WebAssembly] Implement Address Sanitizer for Emscripten

2019-06-26 Thread Guanzhong Chen via Phabricator via cfe-commits
quantum updated this revision to Diff 206719.
quantum added a comment.

Split wasm-ld change into D63833 .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63742

Files:
  clang/lib/Driver/ToolChains/WebAssembly.cpp
  clang/test/Driver/wasm-toolchain.c
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp


Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -112,6 +112,7 @@
 static const uint64_t kNetBSDKasan_ShadowOffset64 = 0xdfff9000;
 static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
 static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
+static const uint64_t kEmscriptenShadowOffset = 0;
 
 static const uint64_t kMyriadShadowScale = 5;
 static const uint64_t kMyriadMemoryOffset32 = 0x8000ULL;
@@ -437,6 +438,7 @@
   bool IsWindows = TargetTriple.isOSWindows();
   bool IsFuchsia = TargetTriple.isOSFuchsia();
   bool IsMyriad = TargetTriple.getVendor() == llvm::Triple::Myriad;
+  bool IsEmscripten = TargetTriple.isOSEmscripten();
 
   ShadowMapping Mapping;
 
@@ -459,6 +461,8 @@
   Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
 else if (IsWindows)
   Mapping.Offset = kWindowsShadowOffset32;
+else if (IsEmscripten)
+  Mapping.Offset = kEmscriptenShadowOffset;
 else if (IsMyriad) {
   uint64_t ShadowOffset = (kMyriadMemoryOffset32 + kMyriadMemorySize32 -
(kMyriadMemorySize32 >> Mapping.Scale));
Index: clang/test/Driver/wasm-toolchain.c
===
--- clang/test/Driver/wasm-toolchain.c
+++ clang/test/Driver/wasm-toolchain.c
@@ -49,3 +49,7 @@
 // '-pthread' not allowed with '-mno-atomics'
 // RUN: %clang -### -no-canonical-prefixes -target wasm32-unknown-unknown 
--sysroot=/foo %s -pthread -mno-atomics 2>&1 | FileCheck 
-check-prefix=PTHREAD_NO_ATOMICS %s
 // PTHREAD_NO_ATOMICS: invalid argument '-pthread' not allowed with 
'-mno-atomics'
+
+// RUN: %clang %s -### -fsanitize=address -target wasm32-unknown-emscripten 
2>&1 | FileCheck -check-prefix=CHECK-ASAN-EMSCRIPTEN %s
+// CHECK-ASAN-EMSCRIPTEN: "-fsanitize=address"
+// CHECK-ASAN-EMSCRIPTEN: "-fsanitize-address-globals-dead-stripping"
Index: clang/lib/Driver/ToolChains/WebAssembly.cpp
===
--- clang/lib/Driver/ToolChains/WebAssembly.cpp
+++ clang/lib/Driver/ToolChains/WebAssembly.cpp
@@ -211,7 +211,7 @@
 SanitizerMask WebAssembly::getSupportedSanitizers() const {
   SanitizerMask Res = ToolChain::getSupportedSanitizers();
   if (getTriple().isOSEmscripten()) {
-Res |= SanitizerKind::Vptr | SanitizerKind::Leak;
+Res |= SanitizerKind::Vptr | SanitizerKind::Leak | SanitizerKind::Address;
   }
   return Res;
 }


Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -112,6 +112,7 @@
 static const uint64_t kNetBSDKasan_ShadowOffset64 = 0xdfff9000;
 static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
 static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
+static const uint64_t kEmscriptenShadowOffset = 0;
 
 static const uint64_t kMyriadShadowScale = 5;
 static const uint64_t kMyriadMemoryOffset32 = 0x8000ULL;
@@ -437,6 +438,7 @@
   bool IsWindows = TargetTriple.isOSWindows();
   bool IsFuchsia = TargetTriple.isOSFuchsia();
   bool IsMyriad = TargetTriple.getVendor() == llvm::Triple::Myriad;
+  bool IsEmscripten = TargetTriple.isOSEmscripten();
 
   ShadowMapping Mapping;
 
@@ -459,6 +461,8 @@
   Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
 else if (IsWindows)
   Mapping.Offset = kWindowsShadowOffset32;
+else if (IsEmscripten)
+  Mapping.Offset = kEmscriptenShadowOffset;
 else if (IsMyriad) {
   uint64_t ShadowOffset = (kMyriadMemoryOffset32 + kMyriadMemorySize32 -
(kMyriadMemorySize32 >> Mapping.Scale));
Index: clang/test/Driver/wasm-toolchain.c
===
--- clang/test/Driver/wasm-toolchain.c
+++ clang/test/Driver/wasm-toolchain.c
@@ -49,3 +49,7 @@
 // '-pthread' not allowed with '-mno-atomics'
 // RUN: %clang -### -no-canonical-prefixes -target wasm32-unknown-unknown --sysroot=/foo %s -pthread -mno-atomics 2>&1 | FileCheck -check-prefix=PTHREAD_NO_ATOMICS %s
 // PTHREAD_NO_ATOMICS: invalid argument '-pthread' not allowed with '-mno-atomics'
+
+// RUN: %clang %s -### -fsanitize=address -target wasm32-unknown-emscripten 2>&1 | FileCheck 

[PATCH] D61637: [Syntax] Introduce syntax trees

2019-06-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

This is now in a pretty good shape, I've incorporated changes after our offline 
discussions about child roles.
The builder interface is also much richer now, removing a requirement that the 
tree has to be traversed left-to-right (bottom-up is still required!).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D61637



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


[PATCH] D61637: [Syntax] Introduce syntax trees

2019-06-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 206715.
ilya-biryukov added a comment.

- Remove (outdated) changes to gn files


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D61637

Files:
  clang/include/clang/Tooling/Syntax/BuildTree.h
  clang/include/clang/Tooling/Syntax/Nodes.h
  clang/include/clang/Tooling/Syntax/Tree.h
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/lib/Tooling/Syntax/CMakeLists.txt
  clang/lib/Tooling/Syntax/Nodes.cpp
  clang/lib/Tooling/Syntax/Tree.cpp
  clang/unittests/Tooling/Syntax/CMakeLists.txt
  clang/unittests/Tooling/Syntax/TreeTest.cpp

Index: clang/unittests/Tooling/Syntax/TreeTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/Syntax/TreeTest.cpp
@@ -0,0 +1,160 @@
+//===- TreeTest.cpp ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/Syntax/Tree.h"
+#include "clang/AST/ASTConsumer.h"
+#include "clang/AST/Decl.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Lex/PreprocessorOptions.h"
+#include "clang/Tooling/Syntax/BuildTree.h"
+#include "clang/Tooling/Syntax/Nodes.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringRef.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+using namespace clang;
+
+namespace {
+class SyntaxTreeTest : public ::testing::Test {
+protected:
+  // Build a syntax tree for the code.
+  syntax::TranslationUnitDeclaration *buildTree(llvm::StringRef Code) {
+// FIXME: this code is almost the identical to the one in TokensTest. Share
+//it.
+class BuildSyntaxTree : public ASTConsumer {
+public:
+  BuildSyntaxTree(syntax::TranslationUnitDeclaration *,
+  std::unique_ptr ,
+  std::unique_ptr Tokens)
+  : Root(Root), Arena(Arena), Tokens(std::move(Tokens)) {
+assert(this->Tokens);
+  }
+
+  void HandleTranslationUnit(ASTContext ) override {
+Arena = llvm::make_unique(Ctx.getSourceManager(),
+ Ctx.getLangOpts(),
+ std::move(*Tokens).consume());
+Tokens = nullptr; // make sure we fail if this gets called twice.
+Root = syntax::buildSyntaxTree(*Arena, *Ctx.getTranslationUnitDecl());
+  }
+
+private:
+  syntax::TranslationUnitDeclaration *
+  std::unique_ptr 
+  std::unique_ptr Tokens;
+};
+
+class BuildSyntaxTreeAction : public ASTFrontendAction {
+public:
+  BuildSyntaxTreeAction(syntax::TranslationUnitDeclaration *,
+std::unique_ptr )
+  : Root(Root), Arena(Arena) {}
+
+  std::unique_ptr
+  CreateASTConsumer(CompilerInstance , StringRef InFile) override {
+// We start recording the tokens, ast consumer will take on the result.
+auto Tokens =
+llvm::make_unique(CI.getPreprocessor());
+return llvm::make_unique(Root, Arena,
+  std::move(Tokens));
+  }
+
+private:
+  syntax::TranslationUnitDeclaration *
+  std::unique_ptr 
+};
+
+constexpr const char *FileName = "./input.cpp";
+FS->addFile(FileName, time_t(), llvm::MemoryBuffer::getMemBufferCopy(""));
+// Prepare to run a compiler.
+std::vector Args = {"syntax-test", "-std=c++11",
+  "-fsyntax-only", FileName};
+auto CI = createInvocationFromCommandLine(Args, Diags, FS);
+assert(CI);
+CI->getFrontendOpts().DisableFree = false;
+CI->getPreprocessorOpts().addRemappedFile(
+FileName, llvm::MemoryBuffer::getMemBufferCopy(Code).release());
+CompilerInstance Compiler;
+Compiler.setInvocation(std::move(CI));
+if (!Diags->getClient())
+  Diags->setClient(new IgnoringDiagConsumer);
+Compiler.setDiagnostics(Diags.get());
+Compiler.setFileManager(FileMgr.get());
+Compiler.setSourceManager(SourceMgr.get());
+
+syntax::TranslationUnitDeclaration *Root = nullptr;
+BuildSyntaxTreeAction Recorder(Root, this->Arena);
+if (!Compiler.ExecuteAction(Recorder)) {
+  ADD_FAILURE() << "failed to run the frontend";
+  std::abort();
+}
+return Root;
+  }
+
+  // Adds a file to the test VFS.
+  void addFile(llvm::StringRef Path, llvm::StringRef Contents) {
+if (!FS->addFile(Path, time_t(),
+ llvm::MemoryBuffer::getMemBufferCopy(Contents))) {
+  ADD_FAILURE() << "could not add a file to VFS: " 

[PATCH] D63623: [clang-tidy] new check: bugprone-posix-return

2019-06-26 Thread Jian Cai via Phabricator via cfe-commits
jcai19 marked 2 inline comments as done.
jcai19 added inline comments.



Comment at: clang-tools-extra/clang-tidy/bugprone/PosixReturnCheck.cpp:49
+diag(OperatorLoc, "POSIX functions (except posix_openpt) never return 
negative values")
+<< FixItHint::CreateReplacement(OperatorLoc, Twine(">").str());
+return;

gribozavr wrote:
> Please add tests for fix-its.
The fix-it is triggered when cases like posix_*(...) < 0 are detected (except 
posix_openpt) , which are currently covered in the unit test. The test runtime 
will make sure fix-its are applied.



Comment at: clang-tools-extra/test/clang-tidy/bugprone-posix-return.cpp:96
+  if (posix_fadvise(0, 0, 0, 0) < 0) {}
+  if (posix_fadvise(0, 0, 0, 0) >= 0) {} else {}
+  if (posix_fadvise(0, 0, 0, 0) == -1) {}

gribozavr wrote:
> Shouldn't there be a warning in the else branch?
This check only matches calls to the POSIX functions in the global scope, not 
member functions or functions defined within namespaces. Although in the global 
scope,  this particular case will still pass as there won't be a ``<`` binary 
operator for the else branch so no matching will happen.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63623



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


[PATCH] D53157: Teach the IRBuilder about constrained fadd and friends

2019-06-26 Thread Kevin P. Neal via Phabricator via cfe-commits
kpn added inline comments.



Comment at: include/llvm/IR/IntrinsicInst.h:235
+  ebStrict   ///< This corresponds to "fpexcept.strict".
 };
 

rjmccall wrote:
> kpn wrote:
> > rjmccall wrote:
> > > Is it okay that `ebUnspecified` and `ebInvalid` overlap here?
> > I can think of a couple of alternatives. If they don't overlap then we have 
> > to go back and sweep the source to make sure that ebUnspecified is always 
> > handled in all cases that currently handle ebInvalid. And in the future 
> > nobody is allowed to check in source that doesn't handle both.
> > 
> > Or, we could drop ebUnspecified, but then ebInvalid would have a valid 
> > meaning to the IRBuilder interface. That looks like a bug even if it works 
> > properly.
> > 
> > Generally, adding eb/rmUnspecified but having them overlap the invalid 
> > cases seems to me to be the best option.
> What is the purpose of `ebInvalid`?  Is this a valid argument to the 
> intrinsic, or is it there so that `getExceptionBehavior()` has something to 
> return if it doesn't recognize the argument?  For the latter, maybe it would 
> be better to just assert that the argument was one of the recognized 
> possibilities; we don't generally expect LLVM to silently propagate 
> ill-formed IR.  Or if it's valid to not provide exception behavior to the 
> intrinsic, maybe that's the same as `ebUnspecified`, or maybe the accessor 
> should return `Optional`.
The current code is in ConstrainedFPIntrinsic::getExceptionBehavior(), which 
returns ebInvalid if the metadata is missing or somehow wrong (wrong type, 
invalid string, etc). This is then used by the IR verifier which fails with an 
Assert() if it gets ebInvalid. So we aren't propagating ill-formed IR.

The intrinsic requires the metadata, and it requires the metadata be valid. But 
I don't want to clutter up IRBuilder's consumer's code. That's why I wanted the 
API to allow those arguments to not be given.

One idea of mine is to have ebInvalid be valid when given to the IRBuilder, and 
the meaning would be "this value is unspecified". But that seems weird.

Maybe there's another way.


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

https://reviews.llvm.org/D53157



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


[PATCH] D61637: [Syntax] Introduce syntax trees

2019-06-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 206714.
ilya-biryukov added a comment.

- Introduce roles to allow distinguishing the child nodes.
- Remove recovery node, use an unknown role instead.
- TreeBuidler now can consume children at any point, not just suffix nodes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D61637

Files:
  clang/include/clang/Tooling/Syntax/BuildTree.h
  clang/include/clang/Tooling/Syntax/Nodes.h
  clang/include/clang/Tooling/Syntax/Tree.h
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/lib/Tooling/Syntax/CMakeLists.txt
  clang/lib/Tooling/Syntax/Nodes.cpp
  clang/lib/Tooling/Syntax/Tree.cpp
  clang/unittests/Tooling/Syntax/CMakeLists.txt
  clang/unittests/Tooling/Syntax/TreeTest.cpp
  llvm/utils/gn/secondary/clang/lib/Tooling/Syntax/BUILD.gn

Index: llvm/utils/gn/secondary/clang/lib/Tooling/Syntax/BUILD.gn
===
--- llvm/utils/gn/secondary/clang/lib/Tooling/Syntax/BUILD.gn
+++ llvm/utils/gn/secondary/clang/lib/Tooling/Syntax/BUILD.gn
@@ -8,6 +8,10 @@
 "//llvm/lib/Support",
   ]
   sources = [
+"Arena.cpp",
+"BuildFromAST.cpp",
+"Cascade.cpp",
+"Nodes.cpp",
 "Tokens.cpp",
   ]
 }
Index: clang/unittests/Tooling/Syntax/TreeTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/Syntax/TreeTest.cpp
@@ -0,0 +1,160 @@
+//===- TreeTest.cpp ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/Syntax/Tree.h"
+#include "clang/AST/ASTConsumer.h"
+#include "clang/AST/Decl.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Lex/PreprocessorOptions.h"
+#include "clang/Tooling/Syntax/BuildTree.h"
+#include "clang/Tooling/Syntax/Nodes.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringRef.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+using namespace clang;
+
+namespace {
+class SyntaxTreeTest : public ::testing::Test {
+protected:
+  // Build a syntax tree for the code.
+  syntax::TranslationUnitDeclaration *buildTree(llvm::StringRef Code) {
+// FIXME: this code is almost the identical to the one in TokensTest. Share
+//it.
+class BuildSyntaxTree : public ASTConsumer {
+public:
+  BuildSyntaxTree(syntax::TranslationUnitDeclaration *,
+  std::unique_ptr ,
+  std::unique_ptr Tokens)
+  : Root(Root), Arena(Arena), Tokens(std::move(Tokens)) {
+assert(this->Tokens);
+  }
+
+  void HandleTranslationUnit(ASTContext ) override {
+Arena = llvm::make_unique(Ctx.getSourceManager(),
+ Ctx.getLangOpts(),
+ std::move(*Tokens).consume());
+Tokens = nullptr; // make sure we fail if this gets called twice.
+Root = syntax::buildSyntaxTree(*Arena, *Ctx.getTranslationUnitDecl());
+  }
+
+private:
+  syntax::TranslationUnitDeclaration *
+  std::unique_ptr 
+  std::unique_ptr Tokens;
+};
+
+class BuildSyntaxTreeAction : public ASTFrontendAction {
+public:
+  BuildSyntaxTreeAction(syntax::TranslationUnitDeclaration *,
+std::unique_ptr )
+  : Root(Root), Arena(Arena) {}
+
+  std::unique_ptr
+  CreateASTConsumer(CompilerInstance , StringRef InFile) override {
+// We start recording the tokens, ast consumer will take on the result.
+auto Tokens =
+llvm::make_unique(CI.getPreprocessor());
+return llvm::make_unique(Root, Arena,
+  std::move(Tokens));
+  }
+
+private:
+  syntax::TranslationUnitDeclaration *
+  std::unique_ptr 
+};
+
+constexpr const char *FileName = "./input.cpp";
+FS->addFile(FileName, time_t(), llvm::MemoryBuffer::getMemBufferCopy(""));
+// Prepare to run a compiler.
+std::vector Args = {"syntax-test", "-std=c++11",
+  "-fsyntax-only", FileName};
+auto CI = createInvocationFromCommandLine(Args, Diags, FS);
+assert(CI);
+CI->getFrontendOpts().DisableFree = false;
+CI->getPreprocessorOpts().addRemappedFile(
+FileName, llvm::MemoryBuffer::getMemBufferCopy(Code).release());
+CompilerInstance Compiler;
+Compiler.setInvocation(std::move(CI));
+if (!Diags->getClient())
+  Diags->setClient(new IgnoringDiagConsumer);
+

[PATCH] D63734: Update CODE_OWNERS.txt for clang-doc

2019-06-26 Thread Julie Hockett via Phabricator via cfe-commits
juliehockett added a comment.

ping


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

https://reviews.llvm.org/D63734



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


[PATCH] D59474: [OpenMP 5.0] Codegen support for user-defined mappers

2019-06-26 Thread Lingda Li via Phabricator via cfe-commits
lildmh marked 2 inline comments as done.
lildmh added inline comments.



Comment at: lib/CodeGen/CGOpenMPRuntime.cpp:8739
+/// // For each component specified by this mapper:
+/// if (currentComponent.hasMapper())
+///   (*currentComponent.Mapper())(rt_mapper_handle, arg_base, arg_begin,

ABataev wrote:
> lildmh wrote:
> > ABataev wrote:
> > > lildmh wrote:
> > > > ABataev wrote:
> > > > > lildmh wrote:
> > > > > > ABataev wrote:
> > > > > > > lildmh wrote:
> > > > > > > > ABataev wrote:
> > > > > > > > > lildmh wrote:
> > > > > > > > > > ABataev wrote:
> > > > > > > > > > > Currently `currentComponent` is generated by the 
> > > > > > > > > > > compiler. But can we instead pass this data as an extra 
> > > > > > > > > > > parameter to this `omp_mapper` function.
> > > > > > > > > > Emm, I think this scheme will be very difficult and 
> > > > > > > > > > inefficient. If we pass components as an argument of 
> > > > > > > > > > `omp_mapper` function, it means that the runtime needs to 
> > > > > > > > > > generate all components related to a map clause. I don't 
> > > > > > > > > > think the runtime is able to do that efficiently. On the 
> > > > > > > > > > other hand, in the current scheme, these components are 
> > > > > > > > > > naturally generated by the compiler, and the runtime only 
> > > > > > > > > > needs to know the base pointer, pointer, type, size. etc.
> > > > > > > > > With the current scheme, we may end with the code blowout. We 
> > > > > > > > > need to generate very similar code for different types and 
> > > > > > > > > variables. The worst thing here is that we will be unable to 
> > > > > > > > > optimize this huge amount of code because the codegen relies 
> > > > > > > > > on the runtime functions and the code cannot be inlined. 
> > > > > > > > > That's why I would like to move as much as possible code to 
> > > > > > > > > the runtime rather than to emit it in the compiler. 
> > > > > > > > I understand your concerns. I think this is the best we can do 
> > > > > > > > right now.
> > > > > > > > 
> > > > > > > > The most worrisome case will be when we have nested mappers 
> > > > > > > > within each other. In this case, a mapper function will call 
> > > > > > > > another mapper function. We can inline the inner mapper 
> > > > > > > > functions in this scenario, so that these mapper function can 
> > > > > > > > be properly optimized. As a result, I think the performance 
> > > > > > > > should be fine.
> > > > > > > Instead, we can use indirect function calls passed in the array 
> > > > > > > to the runtime. Do you think it is going to be slower? In your 
> > > > > > > current scheme, we generate many runtime calls instead. Could you 
> > > > > > > try to estimate the number of calls in cases if we'll call the 
> > > > > > > mappers through the indirect function calls and in your cuurent 
> > > > > > > scheme, where we need to call the runtime functions many times in 
> > > > > > > each particular mapper?
> > > > > > Hi Alexey,
> > > > > > 
> > > > > > Sorry I don't understand your idea. What indirect function calls do 
> > > > > > you propose to be passed to the runtime? What are these functions 
> > > > > > supposed to do?
> > > > > > 
> > > > > > The number of function calls will be exactly equal to the number of 
> > > > > > components mapped, no matter whether there are nested mappers or 
> > > > > > not. The number of components depend on the program. E.g., if we 
> > > > > > map a large array section, then there will be many more function 
> > > > > > calls.
> > > > > I mean the pointers to the mapper function, generated by the 
> > > > > compiler. In your comment, it is `c.Mapper()`
> > > > If we pass nested mapper functions to the runtime, I think it will slow 
> > > > down execution because of the extra level of indirect function calls. 
> > > > E.g., the runtime will call `omp_mapper1`, which calls the runtime 
> > > > back, which calls `omp_mapper2`,  This can result in a deep call 
> > > > stack.
> > > > 
> > > > I think the current implementation will be more efficient, which 
> > > > doesn't pass nested mappers to the runtime. One call to the outer most 
> > > > mapper function will have all data mapping done. The call stack will be 
> > > > 2 level deep (the first level is the mapper function, and the second 
> > > > level is `__tgt_push_mapper_component`) in this case from the runtime. 
> > > > There are also more compiler optimization space when we inline all 
> > > > nested mapper functions.
> > > Yes, if we leave it as is. But if instead of the bunch unique functions 
> > > we'll have the common one, that accept list if indirect pointers to 
> > > functions additionally, and move it to the runtime library, we won't need 
> > > those 2 functions we have currently. We'll have full access to the 
> > > mapping data vector in the runtime library and won't need to use those 2 
> > > accessors we have currently. 

r364453 - Make AddLastArg() variadic and use it more. No behavior change.

2019-06-26 Thread Nico Weber via cfe-commits
Author: nico
Date: Wed Jun 26 10:51:47 2019
New Revision: 364453

URL: http://llvm.org/viewvc/llvm-project?rev=364453=rev
Log:
Make AddLastArg() variadic and use it more. No behavior change.

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

Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=364453=364452=364453=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Wed Jun 26 10:51:47 2019
@@ -2914,9 +2914,7 @@ static void RenderCharacterOptions(const
   }
 
   // The default depends on the language standard.
-  if (const Arg *A =
-  Args.getLastArg(options::OPT_fchar8__t, options::OPT_fno_char8__t))
-A->render(Args, CmdArgs);
+  Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
 
   if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
  options::OPT_fno_short_wchar)) {
@@ -4204,11 +4202,9 @@ void Clang::ConstructJob(Compilation ,
 options::OPT_fno_unique_section_names, true))
 CmdArgs.push_back("-fno-unique-section-names");
 
-  if (auto *A = Args.getLastArg(
-  options::OPT_finstrument_functions,
-  options::OPT_finstrument_functions_after_inlining,
-  options::OPT_finstrument_function_entry_bare))
-A->render(Args, CmdArgs);
+  Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
+  options::OPT_finstrument_functions_after_inlining,
+  options::OPT_finstrument_function_entry_bare);
 
   // NVPTX doesn't support PGO or coverage. There's no runtime support for
   // sampling, overhead of call arc collection is way too high and there's no
@@ -4216,8 +4212,7 @@ void Clang::ConstructJob(Compilation ,
   if (!Triple.isNVPTX())
 addPGOAndCoverageFlags(TC, C, D, Output, Args, CmdArgs);
 
-  if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
-ABICompatArg->render(Args, CmdArgs);
+  Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
 
   // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
   if (RawTriple.isPS4CPU() &&
@@ -4856,9 +4851,8 @@ void Clang::ConstructJob(Compilation ,
 
   // -fgnu-keywords default varies depending on language; only pass if
   // specified.
-  if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
-   options::OPT_fno_gnu_keywords))
-A->render(Args, CmdArgs);
+  Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
+  options::OPT_fno_gnu_keywords);
 
   if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
false))
@@ -4867,10 +4861,9 @@ void Clang::ConstructJob(Compilation ,
   if (Args.hasArg(options::OPT_fno_inline))
 CmdArgs.push_back("-fno-inline");
 
-  if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
-   options::OPT_finline_hint_functions,
-   options::OPT_fno_inline_functions))
-InlineArg->render(Args, CmdArgs);
+  Args.AddLastArg(CmdArgs, options::OPT_finline_functions,
+  options::OPT_finline_hint_functions,
+  options::OPT_fno_inline_functions);
 
   // FIXME: Find a better way to determine whether the language has modules
   // support by default, or just assume that all languages do.
@@ -5065,12 +5058,9 @@ void Clang::ConstructJob(Compilation ,
 
   ParseMPreferVectorWidth(D, Args, CmdArgs);
 
-  if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
-A->render(Args, CmdArgs);
-
-  if (Arg *A = Args.getLastArg(
-  options::OPT_fsanitize_undefined_strip_path_components_EQ))
-A->render(Args, CmdArgs);
+  Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
+  Args.AddLastArg(CmdArgs,
+  options::OPT_fsanitize_undefined_strip_path_components_EQ);
 
   // -fdollars-in-identifiers default varies depending on platform and
   // language; only pass if specified.
@@ -5790,8 +5780,7 @@ void Clang::AddClangCLArgs(const ArgList
 CmdArgs.push_back("--dependent-lib=oldnames");
   }
 
-  if (Arg *A = Args.getLastArg(options::OPT_show_includes))
-A->render(Args, CmdArgs);
+  Args.AddLastArg(CmdArgs, options::OPT_show_includes);
 
   // This controls whether or not we emit RTTI data for polymorphic types.
   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
@@ -5920,8 +5909,7 @@ void Clang::AddClangCLArgs(const ArgList
   CmdArgs.push_back(DCCFlag);
   }
 
-  if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
-A->render(Args, CmdArgs);
+  Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
 
   if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
 CmdArgs.push_back("-fdiagnostics-format");



[PATCH] D59474: [OpenMP 5.0] Codegen support for user-defined mappers

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



Comment at: lib/CodeGen/CGOpenMPRuntime.cpp:8739
+/// // For each component specified by this mapper:
+/// if (currentComponent.hasMapper())
+///   (*currentComponent.Mapper())(rt_mapper_handle, arg_base, arg_begin,

lildmh wrote:
> ABataev wrote:
> > lildmh wrote:
> > > ABataev wrote:
> > > > lildmh wrote:
> > > > > ABataev wrote:
> > > > > > lildmh wrote:
> > > > > > > ABataev wrote:
> > > > > > > > lildmh wrote:
> > > > > > > > > ABataev wrote:
> > > > > > > > > > Currently `currentComponent` is generated by the compiler. 
> > > > > > > > > > But can we instead pass this data as an extra parameter to 
> > > > > > > > > > this `omp_mapper` function.
> > > > > > > > > Emm, I think this scheme will be very difficult and 
> > > > > > > > > inefficient. If we pass components as an argument of 
> > > > > > > > > `omp_mapper` function, it means that the runtime needs to 
> > > > > > > > > generate all components related to a map clause. I don't 
> > > > > > > > > think the runtime is able to do that efficiently. On the 
> > > > > > > > > other hand, in the current scheme, these components are 
> > > > > > > > > naturally generated by the compiler, and the runtime only 
> > > > > > > > > needs to know the base pointer, pointer, type, size. etc.
> > > > > > > > With the current scheme, we may end with the code blowout. We 
> > > > > > > > need to generate very similar code for different types and 
> > > > > > > > variables. The worst thing here is that we will be unable to 
> > > > > > > > optimize this huge amount of code because the codegen relies on 
> > > > > > > > the runtime functions and the code cannot be inlined. That's 
> > > > > > > > why I would like to move as much as possible code to the 
> > > > > > > > runtime rather than to emit it in the compiler. 
> > > > > > > I understand your concerns. I think this is the best we can do 
> > > > > > > right now.
> > > > > > > 
> > > > > > > The most worrisome case will be when we have nested mappers 
> > > > > > > within each other. In this case, a mapper function will call 
> > > > > > > another mapper function. We can inline the inner mapper functions 
> > > > > > > in this scenario, so that these mapper function can be properly 
> > > > > > > optimized. As a result, I think the performance should be fine.
> > > > > > Instead, we can use indirect function calls passed in the array to 
> > > > > > the runtime. Do you think it is going to be slower? In your current 
> > > > > > scheme, we generate many runtime calls instead. Could you try to 
> > > > > > estimate the number of calls in cases if we'll call the mappers 
> > > > > > through the indirect function calls and in your cuurent scheme, 
> > > > > > where we need to call the runtime functions many times in each 
> > > > > > particular mapper?
> > > > > Hi Alexey,
> > > > > 
> > > > > Sorry I don't understand your idea. What indirect function calls do 
> > > > > you propose to be passed to the runtime? What are these functions 
> > > > > supposed to do?
> > > > > 
> > > > > The number of function calls will be exactly equal to the number of 
> > > > > components mapped, no matter whether there are nested mappers or not. 
> > > > > The number of components depend on the program. E.g., if we map a 
> > > > > large array section, then there will be many more function calls.
> > > > I mean the pointers to the mapper function, generated by the compiler. 
> > > > In your comment, it is `c.Mapper()`
> > > If we pass nested mapper functions to the runtime, I think it will slow 
> > > down execution because of the extra level of indirect function calls. 
> > > E.g., the runtime will call `omp_mapper1`, which calls the runtime back, 
> > > which calls `omp_mapper2`,  This can result in a deep call stack.
> > > 
> > > I think the current implementation will be more efficient, which doesn't 
> > > pass nested mappers to the runtime. One call to the outer most mapper 
> > > function will have all data mapping done. The call stack will be 2 level 
> > > deep (the first level is the mapper function, and the second level is 
> > > `__tgt_push_mapper_component`) in this case from the runtime. There are 
> > > also more compiler optimization space when we inline all nested mapper 
> > > functions.
> > Yes, if we leave it as is. But if instead of the bunch unique functions 
> > we'll have the common one, that accept list if indirect pointers to 
> > functions additionally, and move it to the runtime library, we won't need 
> > those 2 functions we have currently. We'll have full access to the mapping 
> > data vector in the runtime library and won't need to use those 2 accessors 
> > we have currently. Instead, we'll need just one runtime functions, which 
> > implements the whole mapping logic. We still need to call it recursively, 
> > but I assume the number of calls will remain the same as in the current 
> > scheme. Did you understand 

[PATCH] D63518: BitStream reader: propagate errors

2019-06-26 Thread JF Bastien via Phabricator via cfe-commits
jfb added a comment.

I think this is ready to go! I rebased and ran `check-all` for LLVM / clang / 
clang-tools-extras and everything passes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63518



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


[PATCH] D59474: [OpenMP 5.0] Codegen support for user-defined mappers

2019-06-26 Thread Lingda Li via Phabricator via cfe-commits
lildmh marked an inline comment as done.
lildmh added inline comments.



Comment at: lib/CodeGen/CGOpenMPRuntime.cpp:744
   OMPRTL__tgt_target_data_update_nowait,
+  // Call to int64_t __tgt_mapper_num_components(void *rt_mapper_handle);
+  OMPRTL__tgt_mapper_num_components,

ABataev wrote:
> lildmh wrote:
> > ABataev wrote:
> > > Do we really need to use `int64_t` for number of elements? `size_t` must 
> > > be enough.
> > Because we use the return value to shift the memberof filed of map type, 
> > which is `int64_t`, so I think `int64_t` makes sense here.
> Ok, there is a discrepancy between runtime part and compiler part: 
> `__tgt_push_mapper_component` uses `size_t` for size, while the runtime 
> function uses `int64_t`. It won't work for 32bit platform.
This should work on 32bit machines, since 32bit machines also use `int64_t` for 
the map type?


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

https://reviews.llvm.org/D59474



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


[PATCH] D61989: [clang-tidy] enable modernize-concat-nested-namespaces on header files

2019-06-26 Thread Xiao Shi via Phabricator via cfe-commits
shixiao added a comment.

Ping =) @JonasToth


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D61989



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


[PATCH] D63082: [Diagnostics] Added support for -Wint-in-bool-context

2019-06-26 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added a comment.

ping


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

https://reviews.llvm.org/D63082



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


[PATCH] D59474: [OpenMP 5.0] Codegen support for user-defined mappers

2019-06-26 Thread Lingda Li via Phabricator via cfe-commits
lildmh marked an inline comment as done.
lildmh added inline comments.



Comment at: lib/CodeGen/CGOpenMPRuntime.cpp:8739
+/// // For each component specified by this mapper:
+/// if (currentComponent.hasMapper())
+///   (*currentComponent.Mapper())(rt_mapper_handle, arg_base, arg_begin,

ABataev wrote:
> lildmh wrote:
> > ABataev wrote:
> > > lildmh wrote:
> > > > ABataev wrote:
> > > > > lildmh wrote:
> > > > > > ABataev wrote:
> > > > > > > lildmh wrote:
> > > > > > > > ABataev wrote:
> > > > > > > > > Currently `currentComponent` is generated by the compiler. 
> > > > > > > > > But can we instead pass this data as an extra parameter to 
> > > > > > > > > this `omp_mapper` function.
> > > > > > > > Emm, I think this scheme will be very difficult and 
> > > > > > > > inefficient. If we pass components as an argument of 
> > > > > > > > `omp_mapper` function, it means that the runtime needs to 
> > > > > > > > generate all components related to a map clause. I don't think 
> > > > > > > > the runtime is able to do that efficiently. On the other hand, 
> > > > > > > > in the current scheme, these components are naturally generated 
> > > > > > > > by the compiler, and the runtime only needs to know the base 
> > > > > > > > pointer, pointer, type, size. etc.
> > > > > > > With the current scheme, we may end with the code blowout. We 
> > > > > > > need to generate very similar code for different types and 
> > > > > > > variables. The worst thing here is that we will be unable to 
> > > > > > > optimize this huge amount of code because the codegen relies on 
> > > > > > > the runtime functions and the code cannot be inlined. That's why 
> > > > > > > I would like to move as much as possible code to the runtime 
> > > > > > > rather than to emit it in the compiler. 
> > > > > > I understand your concerns. I think this is the best we can do 
> > > > > > right now.
> > > > > > 
> > > > > > The most worrisome case will be when we have nested mappers within 
> > > > > > each other. In this case, a mapper function will call another 
> > > > > > mapper function. We can inline the inner mapper functions in this 
> > > > > > scenario, so that these mapper function can be properly optimized. 
> > > > > > As a result, I think the performance should be fine.
> > > > > Instead, we can use indirect function calls passed in the array to 
> > > > > the runtime. Do you think it is going to be slower? In your current 
> > > > > scheme, we generate many runtime calls instead. Could you try to 
> > > > > estimate the number of calls in cases if we'll call the mappers 
> > > > > through the indirect function calls and in your cuurent scheme, where 
> > > > > we need to call the runtime functions many times in each particular 
> > > > > mapper?
> > > > Hi Alexey,
> > > > 
> > > > Sorry I don't understand your idea. What indirect function calls do you 
> > > > propose to be passed to the runtime? What are these functions supposed 
> > > > to do?
> > > > 
> > > > The number of function calls will be exactly equal to the number of 
> > > > components mapped, no matter whether there are nested mappers or not. 
> > > > The number of components depend on the program. E.g., if we map a large 
> > > > array section, then there will be many more function calls.
> > > I mean the pointers to the mapper function, generated by the compiler. In 
> > > your comment, it is `c.Mapper()`
> > If we pass nested mapper functions to the runtime, I think it will slow 
> > down execution because of the extra level of indirect function calls. E.g., 
> > the runtime will call `omp_mapper1`, which calls the runtime back, which 
> > calls `omp_mapper2`,  This can result in a deep call stack.
> > 
> > I think the current implementation will be more efficient, which doesn't 
> > pass nested mappers to the runtime. One call to the outer most mapper 
> > function will have all data mapping done. The call stack will be 2 level 
> > deep (the first level is the mapper function, and the second level is 
> > `__tgt_push_mapper_component`) in this case from the runtime. There are 
> > also more compiler optimization space when we inline all nested mapper 
> > functions.
> Yes, if we leave it as is. But if instead of the bunch unique functions we'll 
> have the common one, that accept list if indirect pointers to functions 
> additionally, and move it to the runtime library, we won't need those 2 
> functions we have currently. We'll have full access to the mapping data 
> vector in the runtime library and won't need to use those 2 accessors we have 
> currently. Instead, we'll need just one runtime functions, which implements 
> the whole mapping logic. We still need to call it recursively, but I assume 
> the number of calls will remain the same as in the current scheme. Did you 
> understand the idea? If yes, it would good if you coild try to estimate the 
> number of function calls in current scheme and in this 

[PATCH] D63822: [Driver] Delete --print-supported-cpus in favor of -mcpu=? or -mtune=?

2019-06-26 Thread Ziang Wan via Phabricator via cfe-commits
ziangwan added a comment.

Hey @MaskRay , can you explain why we should remove --print-supported-cpus. 
There already are similar options in clang such as `--print-effective-triple` 
and `--print-libgcc-file-name`. On the other hand, I almost never see an option 
goes like `-xxx=?`.


Repository:
  rC Clang

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

https://reviews.llvm.org/D63822



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


[clang-tools-extra] r364442 - [clang-tidy] Generalize TransformerClangTidyCheck to take a rule generator.

2019-06-26 Thread Yitzhak Mandelbaum via cfe-commits
Author: ymandel
Date: Wed Jun 26 09:04:38 2019
New Revision: 364442

URL: http://llvm.org/viewvc/llvm-project?rev=364442=rev
Log:
[clang-tidy] Generalize TransformerClangTidyCheck to take a rule generator.

Summary: Tidy check behavior often depends on language and/or clang-tidy 
options. This revision allows a user of TranformerClangTidyCheck to pass rule 
_generator_ in place of a rule, where the generator takes both the language and 
clang-tidy options. Additionally, the generator returns an `Optional` to allow 
for the case where the check is deemed irrelevant/disable based on those 
options.

Reviewers: gribozavr

Subscribers: xazax.hun, cfe-commits

Tags: #clang

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

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

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

Modified: clang-tools-extra/trunk/clang-tidy/utils/TransformerClangTidyCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/utils/TransformerClangTidyCheck.cpp?rev=364442=364441=364442=diff
==
--- clang-tools-extra/trunk/clang-tidy/utils/TransformerClangTidyCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/utils/TransformerClangTidyCheck.cpp Wed 
Jun 26 09:04:38 2019
@@ -14,20 +14,40 @@ namespace tidy {
 namespace utils {
 using tooling::RewriteRule;
 
+static bool hasExplanation(const RewriteRule::Case ) {
+  return C.Explanation != nullptr;
+}
+
+// This constructor cannot dispatch to the simpler one (below), because, in
+// order to get meaningful results from `getLangOpts` and `Options`, we need 
the
+// `ClangTidyCheck()` constructor to have been called. If we were to dispatch,
+// we would be accessing `getLangOpts` and `Options` before the underlying
+// `ClangTidyCheck` instance was properly initialized.
+TransformerClangTidyCheck::TransformerClangTidyCheck(
+std::function(const LangOptions &,
+const OptionsView &)>
+MakeRule,
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context), Rule(MakeRule(getLangOpts(), Options)) {
+  if (Rule)
+assert(llvm::all_of(Rule->Cases, hasExplanation) &&
+   "clang-tidy checks must have an explanation by default;"
+   " explicitly provide an empty explanation if none is desired");
+}
+
 TransformerClangTidyCheck::TransformerClangTidyCheck(RewriteRule R,
  StringRef Name,
  ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context), Rule(std::move(R)) {
-  assert(llvm::all_of(Rule.Cases, [](const RewriteRule::Case ) {
-   return C.Explanation != nullptr;
- }) &&
+  assert(llvm::all_of(Rule->Cases, hasExplanation) &&
  "clang-tidy checks must have an explanation by default;"
  " explicitly provide an empty explanation if none is desired");
 }
 
 void TransformerClangTidyCheck::registerMatchers(
 ast_matchers::MatchFinder *Finder) {
-  Finder->addDynamicMatcher(tooling::detail::buildMatcher(Rule), this);
+  if (Rule)
+Finder->addDynamicMatcher(tooling::detail::buildMatcher(*Rule), this);
 }
 
 void TransformerClangTidyCheck::check(
@@ -43,7 +63,8 @@ void TransformerClangTidyCheck::check(
   Root->second.getSourceRange().getBegin());
   assert(RootLoc.isValid() && "Invalid location for Root node of match.");
 
-  RewriteRule::Case Case = tooling::detail::findSelectedCase(Result, Rule);
+  assert(Rule && "check() should not fire if Rule is None");
+  RewriteRule::Case Case = tooling::detail::findSelectedCase(Result, *Rule);
   Expected> Transformations =
   tooling::detail::translateEdits(Result, Case.Edits);
   if (!Transformations) {

Modified: clang-tools-extra/trunk/clang-tidy/utils/TransformerClangTidyCheck.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/utils/TransformerClangTidyCheck.h?rev=364442=364441=364442=diff
==
--- clang-tools-extra/trunk/clang-tidy/utils/TransformerClangTidyCheck.h 
(original)
+++ clang-tools-extra/trunk/clang-tidy/utils/TransformerClangTidyCheck.h Wed 
Jun 26 09:04:38 2019
@@ -31,19 +31,32 @@ namespace utils {
 // };
 class TransformerClangTidyCheck : public ClangTidyCheck {
 public:
-  // All cases in \p R must have a non-null \c Explanation, even though \c
-  // Explanation is optional for RewriteRule in general. Because the primary
-  // purpose of clang-tidy checks is to provide users with diagnostics, we
-  // assume that a missing explanation is a bug.  If no explanation is desired,
-  // indicate that explicitly (for example, by passing `text("no explanation")`
-  //  to 

[clang-tools-extra] r364435 - [clang-tidy] Fix ClangTidyTest to initialize context before checks.

2019-06-26 Thread Yitzhak Mandelbaum via cfe-commits
Author: ymandel
Date: Wed Jun 26 08:04:33 2019
New Revision: 364435

URL: http://llvm.org/viewvc/llvm-project?rev=364435=rev
Log:
[clang-tidy] Fix ClangTidyTest to initialize context before checks.

Summary:
Currently, `clang::tidy::test::runCheckOnCode()` constructs the check
instances *before* initializing the ClangTidyContext. This ordering causes
problems when the check's constructor accesses the context, for example, through
`getLangOpts()`.

This revision moves the construction to after the context initialization, which
follows the pattern used in the clang tidy tool itself.

Reviewers: gribozavr

Subscribers: xazax.hun, cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/unittests/clang-tidy/ClangTidyTest.h

Modified: clang-tools-extra/trunk/unittests/clang-tidy/ClangTidyTest.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clang-tidy/ClangTidyTest.h?rev=364435=364434=364435=diff
==
--- clang-tools-extra/trunk/unittests/clang-tidy/ClangTidyTest.h (original)
+++ clang-tools-extra/trunk/unittests/clang-tidy/ClangTidyTest.h Wed Jun 26 
08:04:33 2019
@@ -27,6 +27,25 @@ namespace clang {
 namespace tidy {
 namespace test {
 
+template  struct CheckFactory {
+  static void
+  createChecks(ClangTidyContext *Context,
+   SmallVectorImpl> ) {
+CheckFactory::createChecks(Context, Result);
+CheckFactory::createChecks(Context, Result);
+  }
+};
+
+template  struct CheckFactory {
+  static void
+  createChecks(ClangTidyContext *Context,
+   SmallVectorImpl> ) {
+Result.emplace_back(llvm::make_unique(
+"test-check-" + std::to_string(Result.size()), Context));
+  }
+};
+
+template 
 class TestClangTidyAction : public ASTFrontendAction {
 public:
   TestClangTidyAction(SmallVectorImpl> ,
@@ -42,6 +61,11 @@ private:
 Context.setASTContext(());
 
 Preprocessor *PP = ();
+
+// Checks must be created here, _after_ `Context` has been initialized, so
+// that check constructors can access the context (for example, through
+// `getLangOpts()`).
+CheckFactory::createChecks(, Checks);
 for (auto  : Checks) {
   Check->registerMatchers();
   Check->registerPPCallbacks(Compiler.getSourceManager(), PP, PP);
@@ -54,25 +78,7 @@ private:
   ClangTidyContext 
 };
 
-template  struct CheckFactory {
-  static void
-  createChecks(ClangTidyContext *Context,
-   SmallVectorImpl> ) {
-CheckFactory::createChecks(Context, Result);
-CheckFactory::createChecks(Context, Result);
-  }
-};
-
-template  struct CheckFactory {
-  static void
-  createChecks(ClangTidyContext *Context,
-   SmallVectorImpl> ) {
-Result.emplace_back(llvm::make_unique(
-"test-check-" + std::to_string(Result.size()), Context));
-  }
-};
-
-template 
+template 
 std::string
 runCheckOnCode(StringRef Code, std::vector *Errors = nullptr,
const Twine  = "input.cc",
@@ -110,9 +116,9 @@ runCheckOnCode(StringRef Code, std::vect
   new FileManager(FileSystemOptions(), InMemoryFileSystem));
 
   SmallVector, 1> Checks;
-  CheckFactory::createChecks(, Checks);
   tooling::ToolInvocation Invocation(
-  Args, new TestClangTidyAction(Checks, Finder, Context), Files.get());
+  Args, new TestClangTidyAction(Checks, Finder, Context),
+  Files.get());
   InMemoryFileSystem->addFile(Filename, 0,
   llvm::MemoryBuffer::getMemBuffer(Code));
   for (const auto  : PathsToContent) {


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


[PATCH] D63817: [clangd] No longer getting template instantiations from header files in Main AST.

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



Comment at: clang-tools-extra/clangd/ClangdUnit.cpp:47
 #include 
+#include 
 

NIT: This include is redundant, maybe remove?
Probably added by accident.



Comment at: clang-tools-extra/clangd/ClangdUnit.cpp:71
 for (Decl *D : DG) {
-  if (D->isFromASTFile())
+  if 
(!D->getASTContext().getSourceManager().isInMainFile(D->getLocation()))
 continue;

Please use `isWrittenInMainFile` instead.
`isInMainFile` takes `#line` markers into account, we don't want that in clangd.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63817



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


[PATCH] D63288: [clang-tidy] Generalize TransformerClangTidyCheck to take a rule generator.

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

resp. to comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63288

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

Index: clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp
@@ -18,16 +18,16 @@
 namespace tidy {
 namespace utils {
 namespace {
+using tooling::change;
 using tooling::RewriteRule;
+using tooling::text;
+using tooling::stencil::cat;
 
 // Invert the code of an if-statement, while maintaining its semantics.
 RewriteRule invertIf() {
   using namespace ::clang::ast_matchers;
-  using tooling::change;
   using tooling::node;
   using tooling::statement;
-  using tooling::text;
-  using tooling::stencil::cat;
 
   StringRef C = "C", T = "T", E = "E";
   RewriteRule Rule = tooling::makeRule(
@@ -65,6 +65,62 @@
   )";
   EXPECT_EQ(Expected, test::runCheckOnCode(Input));
 }
+
+// A trivial rewrite-rule generator that requires Objective-C code.
+Optional needsObjC(const LangOptions ,
+const ClangTidyCheck::OptionsView ) {
+  if (!LangOpts.ObjC)
+return None;
+  return tooling::makeRule(clang::ast_matchers::functionDecl(),
+   change(cat("void changed() {}")), text("no message"));
+}
+
+class NeedsObjCCheck : public TransformerClangTidyCheck {
+public:
+  NeedsObjCCheck(StringRef Name, ClangTidyContext *Context)
+  : TransformerClangTidyCheck(needsObjC, Name, Context) {}
+};
+
+// Verify that the check only rewrites the code when the input is Objective-C.
+TEST(TransformerClangTidyCheckTest, DisableByLang) {
+  const std::string Input = "void log() {}";
+  EXPECT_EQ(Input,
+test::runCheckOnCode(Input, nullptr, "input.cc"));
+
+  EXPECT_EQ("void changed() {}",
+test::runCheckOnCode(Input, nullptr, "input.mm"));
+}
+
+// A trivial rewrite rule generator that checks config options.
+Optional noSkip(const LangOptions ,
+ const ClangTidyCheck::OptionsView ) {
+  if (Options.get("Skip", "false") == "true")
+return None;
+  return tooling::makeRule(clang::ast_matchers::functionDecl(),
+   change(cat("void nothing()")), text("no message"));
+}
+
+class ConfigurableCheck : public TransformerClangTidyCheck {
+public:
+  ConfigurableCheck(StringRef Name, ClangTidyContext *Context)
+  : TransformerClangTidyCheck(noSkip, Name, Context) {}
+};
+
+// Tests operation with config option "Skip" set to true and false.
+TEST(TransformerClangTidyCheckTest, DisableByConfig) {
+  const std::string Input = "void log(int);";
+  const std::string Expected = "void nothing();";
+  ClangTidyOptions Options;
+
+  Options.CheckOptions["test-check-0.Skip"] = "true";
+  EXPECT_EQ(Input, test::runCheckOnCode(
+   Input, nullptr, "input.cc", None, Options));
+
+  Options.CheckOptions["test-check-0.Skip"] = "false";
+  EXPECT_EQ(Expected, test::runCheckOnCode(
+  Input, nullptr, "input.cc", None, Options));
+}
+
 } // namespace
 } // namespace utils
 } // namespace tidy
Index: clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
===
--- clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
+++ clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h
@@ -31,19 +31,32 @@
 // };
 class TransformerClangTidyCheck : public ClangTidyCheck {
 public:
-  // All cases in \p R must have a non-null \c Explanation, even though \c
-  // Explanation is optional for RewriteRule in general. Because the primary
-  // purpose of clang-tidy checks is to provide users with diagnostics, we
-  // assume that a missing explanation is a bug.  If no explanation is desired,
-  // indicate that explicitly (for example, by passing `text("no explanation")`
-  //  to `makeRule` as the `Explanation` argument).
+  // \p MakeRule generates the rewrite rule to be used by the check, based on
+  // the given language and clang-tidy options. It can return \c None to handle
+  // cases where the options disable the check.
+  //
+  // All cases in the rule generated by \p MakeRule must have a non-null \c
+  // Explanation, even though \c Explanation is optional for RewriteRule in
+  // general. Because the primary purpose of clang-tidy checks is to provide
+  // users with diagnostics, we assume that a missing explanation is a bug.  If
+  // no explanation is desired, indicate that explicitly (for example, by
+  // passing `text("no 

[PATCH] D63784: [clang-tidy] Fix ClangTidyTest to initialize context before checks.

2019-06-26 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added inline comments.



Comment at: clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h:48
+
+template 
 class TestClangTidyAction : public ASTFrontendAction {

gribozavr wrote:
> "CheckTypes"?  'cause "Checks" below is also technically a "check list".
Agreed. I was just blindly following what was already there. Changed here and 
below.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63784



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


[PATCH] D63784: [clang-tidy] Fix ClangTidyTest to initialize context before checks.

2019-06-26 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 206667.
ymandel marked 3 inline comments as done.
ymandel added a comment.

responded to comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63784

Files:
  clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h


Index: clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h
===
--- clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h
+++ clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h
@@ -27,6 +27,25 @@
 namespace tidy {
 namespace test {
 
+template  struct CheckFactory {
+  static void
+  createChecks(ClangTidyContext *Context,
+   SmallVectorImpl> ) {
+CheckFactory::createChecks(Context, Result);
+CheckFactory::createChecks(Context, Result);
+  }
+};
+
+template  struct CheckFactory {
+  static void
+  createChecks(ClangTidyContext *Context,
+   SmallVectorImpl> ) {
+Result.emplace_back(llvm::make_unique(
+"test-check-" + std::to_string(Result.size()), Context));
+  }
+};
+
+template 
 class TestClangTidyAction : public ASTFrontendAction {
 public:
   TestClangTidyAction(SmallVectorImpl> ,
@@ -42,6 +61,11 @@
 Context.setASTContext(());
 
 Preprocessor *PP = ();
+
+// Checks must be created here, _after_ `Context` has been initialized, so
+// that check constructors can access the context (for example, through
+// `getLangOpts()`).
+CheckFactory::createChecks(, Checks);
 for (auto  : Checks) {
   Check->registerMatchers();
   Check->registerPPCallbacks(Compiler.getSourceManager(), PP, PP);
@@ -54,25 +78,7 @@
   ClangTidyContext 
 };
 
-template  struct CheckFactory {
-  static void
-  createChecks(ClangTidyContext *Context,
-   SmallVectorImpl> ) {
-CheckFactory::createChecks(Context, Result);
-CheckFactory::createChecks(Context, Result);
-  }
-};
-
-template  struct CheckFactory {
-  static void
-  createChecks(ClangTidyContext *Context,
-   SmallVectorImpl> ) {
-Result.emplace_back(llvm::make_unique(
-"test-check-" + std::to_string(Result.size()), Context));
-  }
-};
-
-template 
+template 
 std::string
 runCheckOnCode(StringRef Code, std::vector *Errors = nullptr,
const Twine  = "input.cc",
@@ -110,9 +116,9 @@
   new FileManager(FileSystemOptions(), InMemoryFileSystem));
 
   SmallVector, 1> Checks;
-  CheckFactory::createChecks(, Checks);
   tooling::ToolInvocation Invocation(
-  Args, new TestClangTidyAction(Checks, Finder, Context), Files.get());
+  Args, new TestClangTidyAction(Checks, Finder, Context),
+  Files.get());
   InMemoryFileSystem->addFile(Filename, 0,
   llvm::MemoryBuffer::getMemBuffer(Code));
   for (const auto  : PathsToContent) {


Index: clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h
===
--- clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h
+++ clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h
@@ -27,6 +27,25 @@
 namespace tidy {
 namespace test {
 
+template  struct CheckFactory {
+  static void
+  createChecks(ClangTidyContext *Context,
+   SmallVectorImpl> ) {
+CheckFactory::createChecks(Context, Result);
+CheckFactory::createChecks(Context, Result);
+  }
+};
+
+template  struct CheckFactory {
+  static void
+  createChecks(ClangTidyContext *Context,
+   SmallVectorImpl> ) {
+Result.emplace_back(llvm::make_unique(
+"test-check-" + std::to_string(Result.size()), Context));
+  }
+};
+
+template 
 class TestClangTidyAction : public ASTFrontendAction {
 public:
   TestClangTidyAction(SmallVectorImpl> ,
@@ -42,6 +61,11 @@
 Context.setASTContext(());
 
 Preprocessor *PP = ();
+
+// Checks must be created here, _after_ `Context` has been initialized, so
+// that check constructors can access the context (for example, through
+// `getLangOpts()`).
+CheckFactory::createChecks(, Checks);
 for (auto  : Checks) {
   Check->registerMatchers();
   Check->registerPPCallbacks(Compiler.getSourceManager(), PP, PP);
@@ -54,25 +78,7 @@
   ClangTidyContext 
 };
 
-template  struct CheckFactory {
-  static void
-  createChecks(ClangTidyContext *Context,
-   SmallVectorImpl> ) {
-CheckFactory::createChecks(Context, Result);
-CheckFactory::createChecks(Context, Result);
-  }
-};
-
-template  struct CheckFactory {
-  static void
-  createChecks(ClangTidyContext *Context,
-   SmallVectorImpl> ) {
-Result.emplace_back(llvm::make_unique(
-"test-check-" + std::to_string(Result.size()), Context));
-  }
-};
-
-template 
+template 
 std::string
 runCheckOnCode(StringRef Code, std::vector *Errors = nullptr,
const Twine  = "input.cc",
@@ -110,9 +116,9 @@
   new FileManager(FileSystemOptions(), 

[PATCH] D63817: [clangd] No longer getting template instantiations from header files in Main AST.

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



Comment at: clang-tools-extra/clangd/ClangdUnit.cpp:75
+  if (!SM->isInMainFile(D->getLocation()))
+// This decl comes from another file and should not be included in the
+// top level decls.

hokein wrote:
> nit: This comment just repeats the code, I think the comment describe why we 
> need to do this check (because of the template instantiation?)  
Removed the D->isFromASTFile because this if actually covers that as well. 
Don't know what to do about comments though as it is not only specific to that 
case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63817



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


[PATCH] D63817: [clangd] No longer getting template instantiations from header files in Main AST.

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

Removed comment, getting SM from Decl and removed old check for checking the 
file.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63817

Files:
  clang-tools-extra/clangd/ClangdUnit.cpp
  clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp


Index: clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
===
--- clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
+++ clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
@@ -83,6 +83,23 @@
   EXPECT_THAT(AST.getLocalTopLevelDecls(), ElementsAre(DeclNamed("main")));
 }
 
+TEST(ClangdUnitTest, DoesNotGetIncludedTopDecls) {
+  TestTU TU;
+  TU.HeaderCode = R"cpp(
+template
+struct H {
+  H() {}
+};
+  )cpp";
+  TU.Code = R"cpp(
+int main() {
+  H h;
+}
+  )cpp";
+  auto AST = TU.build();
+  EXPECT_THAT(AST.getLocalTopLevelDecls(), ElementsAre(DeclNamed("main")));
+}
+
 TEST(ClangdUnitTest, TokensAfterPreamble) {
   TestTU TU;
   TU.AdditionalFiles["foo.h"] = R"(
Index: clang-tools-extra/clangd/ClangdUnit.cpp
===
--- clang-tools-extra/clangd/ClangdUnit.cpp
+++ clang-tools-extra/clangd/ClangdUnit.cpp
@@ -44,6 +44,7 @@
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -67,7 +68,7 @@
 
   bool HandleTopLevelDecl(DeclGroupRef DG) override {
 for (Decl *D : DG) {
-  if (D->isFromASTFile())
+  if 
(!D->getASTContext().getSourceManager().isInMainFile(D->getLocation()))
 continue;
 
   // ObjCMethodDecl are not actually top-level decls.


Index: clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
===
--- clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
+++ clang-tools-extra/clangd/unittests/ClangdUnitTests.cpp
@@ -83,6 +83,23 @@
   EXPECT_THAT(AST.getLocalTopLevelDecls(), ElementsAre(DeclNamed("main")));
 }
 
+TEST(ClangdUnitTest, DoesNotGetIncludedTopDecls) {
+  TestTU TU;
+  TU.HeaderCode = R"cpp(
+template
+struct H {
+  H() {}
+};
+  )cpp";
+  TU.Code = R"cpp(
+int main() {
+  H h;
+}
+  )cpp";
+  auto AST = TU.build();
+  EXPECT_THAT(AST.getLocalTopLevelDecls(), ElementsAre(DeclNamed("main")));
+}
+
 TEST(ClangdUnitTest, TokensAfterPreamble) {
   TestTU TU;
   TU.AdditionalFiles["foo.h"] = R"(
Index: clang-tools-extra/clangd/ClangdUnit.cpp
===
--- clang-tools-extra/clangd/ClangdUnit.cpp
+++ clang-tools-extra/clangd/ClangdUnit.cpp
@@ -44,6 +44,7 @@
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -67,7 +68,7 @@
 
   bool HandleTopLevelDecl(DeclGroupRef DG) override {
 for (Decl *D : DG) {
-  if (D->isFromASTFile())
+  if (!D->getASTContext().getSourceManager().isInMainFile(D->getLocation()))
 continue;
 
   // ObjCMethodDecl are not actually top-level decls.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D63773: [clangd] dummy variable extraction on a function scope

2019-06-26 Thread Shaurya Gupta via Phabricator via cfe-commits
SureYeaah updated this revision to Diff 206663.
SureYeaah marked 4 inline comments as done.
SureYeaah added a comment.

Refactored code

- Refactored code as pointed by kadircet
- Fixed crash for if statements without an else clause


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63773

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

Index: clang-tools-extra/clangd/unittests/TweakTests.cpp
===
--- clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -216,6 +216,208 @@
   checkTransform(ID, Input, Output);
 }
 
+TEST(TweakTest, ExtractVariable) {
+  llvm::StringLiteral ID = "ExtractVariable";
+  checkAvailable(ID, R"cpp(
+int xyz() {
+  return 1;
+}
+void f() {
+  int a = 5 + [[4 * [[^xyz();
+  // FIXME: add test case for multiple variable initialization once
+  // SelectionTree commonAncestor bug is fixed
+  switch(a) {
+case 1: {
+  a = ^1;
+  break;
+}
+default: {
+  a = ^3; 
+}
+  }
+  if(^1) {}
+  if(a < ^3)
+if(a == 4)
+  a = 5;
+else
+  a = 6;
+  else if (a < 4) {
+a = ^4;
+  }
+  else {
+a = ^5;
+  }
+  // for loop testing
+  for(a = ^1; a > ^3+^4; a++) 
+a = 2;
+  // while testing
+  while(a < ^1) {
+^a++;
+  }
+  // do while testing
+  do
+a = 1;
+  while(a < ^3);
+}
+  )cpp");
+  checkNotAvailable(ID, R"cpp(
+void f(int b = ^1) {
+  int a = 5 + 4 * 3;
+  // switch testing
+  switch(a) {
+case 1: 
+  a = ^1;
+  break;
+default:
+  a = ^3; 
+  }
+  // if testing
+  if(a < 3)
+if(a == ^4)
+  a = ^5;
+else
+  a = ^6;
+  else if (a < ^4) {
+a = 4;
+  }
+  else {
+a = 5;
+  }
+  // for loop testing
+  for(int a = 1, b = 2, c = 3; ^a > ^b ^+ ^c; ^a++) 
+a = ^2;
+  // while testing
+  while(a < 1) {
+a++;
+  }
+  // do while testing
+  do
+a = ^1;
+  while(a < 3);
+  // testing in cases where braces are required
+  if (true)
+do
+  a = 1;
+while(a < ^1);
+}
+  )cpp");
+  // vector of pairs of input and output strings
+  const std::vector>
+  InputOutputs = {
+  // extraction from variable declaration/assignment
+  {R"cpp(void varDecl() {
+   int a = 5 * (4 + (3 [[- 1)]]);
+ })cpp",
+   R"cpp(void varDecl() {
+   auto dummy = (3 - 1); int a = 5 * (4 + dummy);
+ })cpp"},
+  // extraction from for loop init/cond/incr
+  {R"cpp(void forLoop() {
+   for(int a = 1; a < ^3; a++) {
+ a = 5 + 4 * 3;
+   }
+ })cpp",
+   R"cpp(void forLoop() {
+   auto dummy = 3; for(int a = 1; a < dummy; a++) {
+ a = 5 + 4 * 3;
+   }
+ })cpp"},
+  // extraction inside for loop body
+  {R"cpp(void forBody() {
+   for(int a = 1; a < 3; a++) {
+ a = 5 + [[4 * 3]];
+   }
+ })cpp",
+   R"cpp(void forBody() {
+   for(int a = 1; a < 3; a++) {
+ auto dummy = 4 * 3; a = 5 + dummy;
+   }
+ })cpp"},
+  // extraction inside while loop condition
+  {R"cpp(void whileLoop(int a) {
+   while(a < 5 + [[4 * 3]]) 
+ a += 1;
+ })cpp",
+   R"cpp(void whileLoop(int a) {
+   auto dummy = 4 * 3; while(a < 5 + dummy) 
+ a += 1;
+ })cpp"},
+  // extraction inside while body condition
+  {R"cpp(void whileBody(int a) {
+   while(a < 1) {
+ a += ^7 * 3;
+   }
+ })cpp",
+   R"cpp(void whileBody(int a) {
+   while(a < 1) {
+ auto dummy = 7; a += dummy * 3;
+   }
+ })cpp"},
+  // extraction inside do-while loop condition
+  {R"cpp(void doWhileLoop(int a) {
+   do
+ a += 3;
+   while(a < ^1);
+ })cpp",
+   R"cpp(void doWhileLoop(int a) {
+   auto dummy = 1; do
+ a += 3;
+   while(a < dummy);
+ })cpp"},
+  // extraction inside do-while 

[PATCH] D63822: [Driver] Delete --print-supported-cpus in favor of -mcpu=? or -mtune=?

2019-06-26 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay created this revision.
MaskRay added reviewers: kongyi, ziangwan.
Herald added subscribers: cfe-commits, srhines.
Herald added a project: clang.

Also fix some style issues after D63105 .


Repository:
  rC Clang

https://reviews.llvm.org/D63822

Files:
  docs/CommandGuide/clang.rst
  include/clang/Driver/Options.td
  lib/Driver/Driver.cpp
  lib/Frontend/CompilerInvocation.cpp
  test/Driver/print-supported-cpus.c
  tools/driver/cc1_main.cpp

Index: tools/driver/cc1_main.cpp
===
--- tools/driver/cc1_main.cpp
+++ tools/driver/cc1_main.cpp
@@ -169,8 +169,8 @@
 static void ensureSufficientStack() {}
 #endif
 
-/// print supported cpus of the given target
-int PrintSupportedCPUs(std::string TargetStr) {
+/// Print supported cpus of the given target.
+static int PrintSupportedCPUs(std::string TargetStr) {
   std::string Error;
   const llvm::Target *TheTarget =
   llvm::TargetRegistry::lookupTarget(TargetStr, Error);
@@ -219,10 +219,9 @@
   if (Clang->getFrontendOpts().TimeTrace)
 llvm::timeTraceProfilerInitialize();
 
-  // --print-supported-cpus takes priority over the actual compilation
-  if (Clang->getFrontendOpts().PrintSupportedCPUs) {
+  // -mcpu=? takes priority over the actual compilation.
+  if (Clang->getFrontendOpts().PrintSupportedCPUs)
 return PrintSupportedCPUs(Clang->getTargetOpts().Triple);
-  }
 
   // Infer the builtin include path if unspecified.
   if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
Index: test/Driver/print-supported-cpus.c
===
--- test/Driver/print-supported-cpus.c
+++ test/Driver/print-supported-cpus.c
@@ -1,35 +1,23 @@
-// Test that the --print-supported-cpus flag works
-// Also test its aliases: -mcpu=? and -mtune=?
+// Test that -mcpu=? or -mtune=? lists supported CPU models.
 
 // REQUIRES: x86-registered-target
 // REQUIRES: arm-registered-target
 
-// RUN: %clang --target=x86_64-unknown-linux-gnu \
-// RUN:   --print-supported-cpus 2>&1 \
-// RUN:   | FileCheck %s --check-prefix=CHECK-X86
+// RUN: %clang --target=x86_64-unknown-linux-gnu -mcpu=? 2>&1 | \
+// RUN:   FileCheck %s --check-prefix=CHECK-X86
+
+// RUN: %clang --target=x86_64-unknown-linux-gnu -mtune=? -fuse-ld=dummy 2>&1 | \
+// RUN:   FileCheck %s --check-prefix=CHECK-X86
+
+// CHECK-NOT: warning: argument unused during compilation
 // CHECK-X86: Target: x86_64-unknown-linux-gnu
 // CHECK-X86: corei7
 // CHECK-X86: Use -mcpu or -mtune to specify the target's processor.
 
-// RUN: %clang --target=x86_64-unknown-linux-gnu \
-// RUN:   -mcpu=? 2>&1 \
-// RUN:   | FileCheck %s --check-prefix=CHECK-X86-MCPU
-// CHECK-X86-MCPU: Target: x86_64-unknown-linux-gnu
-// CHECK-X86-MCPU: corei7
-// CHECK-X86-MCPU: Use -mcpu or -mtune to specify the target's processor.
+// RUN: %clang --target=arm-unknown-linux-android -mcpu=? 2>&1 | \
+// RUN:   FileCheck %s --check-prefix=CHECK-ARM
 
-// RUN: %clang --target=arm-unknown-linux-android \
-// RUN:   --print-supported-cpus 2>&1 \
-// RUN:   | FileCheck %s --check-prefix=CHECK-ARM
 // CHECK-ARM: Target: arm-unknown-linux-android
 // CHECK-ARM: cortex-a73
 // CHECK-ARM: cortex-a75
 // CHECK-ARM: Use -mcpu or -mtune to specify the target's processor.
-
-// RUN: %clang --target=arm-unknown-linux-android \
-// RUN:   -mtune=? 2>&1 \
-// RUN:   | FileCheck %s --check-prefix=CHECK-ARM-MTUNE
-// CHECK-ARM-MTUNE: Target: arm-unknown-linux-android
-// CHECK-ARM-MTUNE: cortex-a73
-// CHECK-ARM-MTUNE: cortex-a75
-// CHECK-ARM-MTUNE: Use -mcpu or -mtune to specify the target's processor.
Index: lib/Frontend/CompilerInvocation.cpp
===
--- lib/Frontend/CompilerInvocation.cpp
+++ lib/Frontend/CompilerInvocation.cpp
@@ -1784,7 +1784,7 @@
   Opts.ShowHelp = Args.hasArg(OPT_help);
   Opts.ShowStats = Args.hasArg(OPT_print_stats);
   Opts.ShowTimers = Args.hasArg(OPT_ftime_report);
-  Opts.PrintSupportedCPUs = Args.hasArg(OPT__print_supported_cpus);
+  Opts.PrintSupportedCPUs = Args.hasArg(OPT_mcpu_EQ_QUESTION);
   Opts.TimeTrace = Args.hasArg(OPT_ftime_trace);
   Opts.ShowVersion = Args.hasArg(OPT_version);
   Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
Index: lib/Driver/Driver.cpp
===
--- lib/Driver/Driver.cpp
+++ lib/Driver/Driver.cpp
@@ -280,6 +280,7 @@
 
 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
+ (PhaseArg = DAL.getLastArg(options::OPT_mcpu_EQ_QUESTION)) ||
  (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
  (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
  (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
@@ -1673,7 +1674,7 @@
 
   if (C.getArgs().hasArg(options::OPT_v) ||
   

[PATCH] D62574: Initial draft of target-configurable address spaces.

2019-06-26 Thread Bevin Hansson via Phabricator via cfe-commits
ebevhan marked 3 inline comments as done.
ebevhan added a comment.

In D62574#1552220 , @Anastasia wrote:

> Ok, I think at some point you might want to test extra functionality that 
> doesn't fit into OpenCL model, for example explicit conversion over 
> non-overlapping address spaces? I think for this you might find useful to add 
> the extra flag that switches on extra testing with "fake" setup of address 
> spaces.


That functionality is actually enabled by default to allow for Clang's current 
semantics. Embedded-C allows all explicit conversions by default, and OpenCL in 
Clang allows all explicit conversion to and from target spaces as an extension.

It's rather up to each target to *disable* the default explicit conversion 
behavior if they don't want it.




Comment at: include/clang/AST/ASTContext.h:2598
+  /// Returns true if address space A overlaps with B.
+  bool isAddressSpaceOverlapping(LangAS A, LangAS B) const {
+// A overlaps with B if either is a superset of the other.

Anastasia wrote:
> Is there any advantage of keeping superset concept? Amd if yes, how do 
> we position the new functionality with explicit cast?
> 
> I think I am missing a bit conceptual view... because I think we originally 
> discussed to switch to implicit/explicit conversion model. Perhaps there is 
> no reason to do it but I would just like to understand why? 
Yes, I know the original discussion was regarding the implicit/explicit model, 
but I came to realize during the implementation that all that was needed to get 
the superspace model to work generically with the current behavior was an 
override on the explicit conversion.

The implicit/explicit model also has the drawback that it's a bit too 
expressive. You can express semantics that just don't really make sense, like 
permitting implicit conversion but not explicit conversion. The superspace 
model doesn't let you do that, and the additions I've made here still don't: If 
implicit conversion is allowed, explicit conversion must also be allowed. It 
just becomes possible to allow explicit conversion for ASes that don't overlap.

Since the superspace model is what OpenCL and Embedded-C use in their 
specification, it's probably better to use that anyway.



Comment at: lib/Sema/SemaCast.cpp:2224
+// the cast is explicitly legal as well.
+if (CStyle ? !Self.Context.isExplicitAddrSpaceConversionLegal(SrcQ, DestQ)
+   : !Self.Context.isAddressSpaceSupersetOf(DestQ, SrcQ)) {

Anastasia wrote:
> It seems like you are changing the functionality here. Don't we need any test 
> for this?
I don't think it's necessarily changing. If we are doing a reinterpret_cast 
that stems from a c-style cast, we want to check that explicit conversion is 
allowed. This happens both if either AS overlaps, or if the target permits it. 
If it's not a C-style cast, then we need to check for subspace correctness 
instead, as reinterpret_cast can only do 'safe' casts.

The original code here allows all explicit C-style casts regardless of AS, but 
now we have to ask the target first.



Comment at: lib/Sema/SemaCast.cpp:2319
+
+  Kind = CK_AddressSpaceConversion;
+  return TC_Success;

Anastasia wrote:
> Btw I think this is set in:
> https://reviews.llvm.org/D62299
> 
> Although I don't have any objections to changing to this.
Oh, indeed.


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

https://reviews.llvm.org/D62574



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


r364428 - Make CodeGen depend on ASTMatchers

2019-06-26 Thread Michael Liao via cfe-commits
Author: hliao
Date: Wed Jun 26 07:13:43 2019
New Revision: 364428

URL: http://llvm.org/viewvc/llvm-project?rev=364428=rev
Log:
Make CodeGen depend on ASTMatchers

- Shared library builds are broken due to the missing dependency.

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

Modified: cfe/trunk/lib/CodeGen/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CMakeLists.txt?rev=364428=364427=364428=diff
==
--- cfe/trunk/lib/CodeGen/CMakeLists.txt (original)
+++ cfe/trunk/lib/CodeGen/CMakeLists.txt Wed Jun 26 07:13:43 2019
@@ -101,6 +101,7 @@ add_clang_library(clangCodeGen
   LINK_LIBS
   clangAnalysis
   clangAST
+  clangASTMatchers
   clangBasic
   clangFrontend
   clangLex


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


[PATCH] D63821: [clangd] Added C++ API code for semantic highlighting

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

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D63821

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/ClangdLSPServer.h
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/SemanticHighlighting.h
  clang-tools-extra/clangd/TUScheduler.cpp
  clang-tools-extra/clangd/TUScheduler.h
  clang-tools-extra/clangd/unittests/ClangdTests.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
  clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -10,6 +10,7 @@
 #include "Compiler.h"
 #include "Matchers.h"
 #include "Protocol.h"
+#include "SemanticHighlighting.h"
 #include "SyncAPI.h"
 #include "TestFS.h"
 #include "TestTU.h"
@@ -33,9 +34,13 @@
 using ::testing::Matcher;
 using ::testing::UnorderedElementsAreArray;
 
-class IgnoreDiagnostics : public DiagnosticsConsumer {
+class IgnoreDiagnostics : public DiagnosticsConsumer, public HighlightingsConsumer {
   void onDiagnosticsReady(PathRef File,
   std::vector Diagnostics) override {}
+
+  virtual void
+  onHighlightingsReady(PathRef File,
+std::vector Highlightings) override {}
 };
 
 MATCHER_P2(FileRange, File, Range, "") {
@@ -539,7 +544,7 @@
 
   IgnoreDiagnostics DiagConsumer;
   MockFSProvider FS;
-  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
+  ClangdServer Server(CDB, FS, DiagConsumer, DiagConsumer, ClangdServer::optsForTest());
 
   // Fill the filesystem.
   auto FooCpp = testPath("src/foo.cpp");
@@ -1791,7 +1796,7 @@
   MockFSProvider FS;
   IgnoreDiagnostics DiagConsumer;
   MockCompilationDatabase CDB;
-  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
+  ClangdServer Server(CDB, FS, DiagConsumer, DiagConsumer, ClangdServer::optsForTest());
 
   auto FooCpp = testPath("foo.cpp");
   const char *SourceContents = R"cpp(
@@ -1866,7 +1871,7 @@
   MockFSProvider FS;
   IgnoreDiagnostics DiagConsumer;
   MockCompilationDatabase CDB;
-  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
+  ClangdServer Server(CDB, FS, DiagConsumer, DiagConsumer, ClangdServer::optsForTest());
 
   auto FooCpp = testPath("foo.cpp");
   // The trigger locations must be the same.
Index: clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
===
--- clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
+++ clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "Annotations.h"
+#include "ClangdServer.h"
 #include "Context.h"
 #include "Matchers.h"
 #include "TUScheduler.h"
@@ -44,9 +45,10 @@
 
   void updateWithCallback(TUScheduler , PathRef File,
   llvm::StringRef Contents, WantDiagnostics WD,
+  bool WantHighlight,
   llvm::unique_function CB) {
 WithContextValue Ctx(llvm::make_scope_exit(std::move(CB)));
-S.update(File, getInputs(File, Contents), WD);
+S.update(File, getInputs(File, Contents), WD, WantHighlight);
   }
 
   static Key)>>
@@ -71,7 +73,7 @@
   /// any. The TUScheduler should be created with captureDiags as a
   /// DiagsCallback for this to work.
   void updateWithDiags(TUScheduler , PathRef File, ParseInputs Inputs,
-   WantDiagnostics WD,
+   WantDiagnostics WD, bool WantHighlight,
llvm::unique_function)> CB) {
 Path OrigFile = File.str();
 WithContextValue Ctx(
@@ -82,13 +84,13 @@
   CB(std::move(Diags));
 },
 std::move(CB)));
-S.update(File, std::move(Inputs), WD);
+S.update(File, std::move(Inputs), WD, WantHighlight);
   }
 
   void updateWithDiags(TUScheduler , PathRef File, llvm::StringRef Contents,
-   WantDiagnostics WD,
+   WantDiagnostics WD, bool WantHighlight,
llvm::unique_function)> CB) {
-return updateWithDiags(S, File, getInputs(File, Contents), WD,
+return updateWithDiags(S, File, getInputs(File, Contents), WD, WantHighlight,
std::move(CB));
   }
 
@@ -113,7 +115,7 @@
   Files[Missing] = "";
 
   EXPECT_EQ(S.getContents(Added), "");
-  

[PATCH] D61446: Generalize the pass registration mechanism used by Polly to any third-party tool

2019-06-26 Thread serge via Phabricator via cfe-commits
serge-sans-paille marked 10 inline comments as done.
serge-sans-paille added inline comments.



Comment at: llvm/cmake/modules/AddLLVM.cmake:808
 
+if(NOT llvm-pass-plugins)
+# Target used to hold global properties referencable from 
generator-expression

Meinersbur wrote:
> [serious] I get the following error:
> ```
> CMake Error at cmake/modules/AddLLVM.cmake:813 (add_custom_target):
>   add_custom_target cannot create target "llvm-pass-plugins" because another
>   target with the same name already exists.  The existing target is a custom
>   target created in source directory "/home/meinersbur/src/llvm".  See
>   documentation for policy CMP0002 for more details.
> Call Stack (most recent call first):
>   projects/compiler-rt/test/CMakeLists.txt:2 (include)
> ```
> 
> What you meant to use is
> ```
> if (NOT TARGET llvm-pass-plugins)
> ```
> See https://cmake.org/cmake/help/latest/command/if.html
I'm no longer using that mechanism, it was showing some limits wrt. cmake 
generator-expression and export set. 



Comment at: llvm/cmake/modules/AddLLVM.cmake:851
+"extern \"C\" ::llvm::PassPluginLibraryInfo 
LLVM_ATTRIBUTE_WEAK llvmGetPassPluginInfo() { return ${entry_point}(); }")
+  target_sources(${register_llvm_pass_plugin_EXTRA_LOADABLE} PRIVATE 
${CMAKE_CURRENT_BINARY_DIR}/${register_llvm_pass_plugin_EXTRA_LOADABLE}_plugin_entry_point.cpp)
+endif()

Meinersbur wrote:
> [serious] Under Windows, I get the following error:
> ```
> CMake Error at cmake/modules/AddLLVM.cmake:853 (target_sources):
>   target_sources called with non-compilable target type
> Call Stack (most recent call first):
>   tools/polly/lib/CMakeLists.txt:164 (register_llvm_pass_plugin)
> ```
> 
> This is because "LLVMPolly" is not a library, but a dummy "add_custom_target" 
> since loadable modules are not supported under Windows.
I'm no longer using `target_sources`, it should be fine now.



Comment at: llvm/docs/WritingAnLLVMPass.rst:1222
 
+Building out-of-tree passes
+===

Meinersbur wrote:
> "out-of-tree" is the wrong term. This registration only works if the plugin 
> if configured in the same cmake-run. "out-of-tree" would describe a processes 
> with a separate cmake source- and build-tree using `LLVM_MAIN_SRC_DIR` or 
> https://llvm.org/docs/CMake.html#embedding-llvm-in-your-project
I'm not super happy with the new title, but I gave it a try.



Comment at: llvm/tools/CMakeLists.txt:45
 
+add_llvm_external_project(polly)
+

Meinersbur wrote:
> What is the reason to have this after `add_llvm_implicit_projects` in 
> contrast to the other LLVM subprojects?
polly used to be included before the other external projects, so that clang/opt 
could depend on it. We are now injecting dependencies a posteriori, so  polly 
needs to be included after opt/clang/bugpoint. I've put it right before the 
loop on `add_llvm_external_project` because they share the same function call 
name.



Comment at: polly/lib/Support/RegisterPasses.cpp:727
+extern "C" ::llvm::PassPluginLibraryInfo LLVM_ATTRIBUTE_WEAK
+llvmGetPassPluginInfo() {
+  return getPassPluginInfo();

Meinersbur wrote:
> serge-sans-paille wrote:
> > Meinersbur wrote:
> > > [serious] Unfortunately, the new pass manager's plugin system relies on 
> > > the function name to be `llvmGetPassPluginInfo` in each plugin. This 
> > > works with multiple dynamic libraries all declaring the same name using 
> > > the `PassPlugin::Load` mechanism, but linking them all statically will 
> > > violate the one-definition-rule.
> > > 
> > > IMHO, Polly.cpp would have been a better place for this function.
> > > but linking them all statically will violate the one-definition-rule.
> > 
> > They are unused when liked statically, and flagged as weak to avoid 
> > link-time conflict.
> > 
> > > IMHO, Polly.cpp would have been a better place for this function.
> > I still agree it's more explicit if linked conditionaly.
> You seem to have removed the weak attribute. Did you mean to put it into the 
> `polly` namespace to avoid name clashing with other plugins?
There are two entry points: `llvmGetPassPluginInfo`  for new PM (marked as 
weak) and `get##name##PluginInfo` for legacy PM (name is supposed to be unique, 
no need for weak linkage)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D61446



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


[PATCH] D58035: [clang/DIVar] Emit flag for params that have unchanged values

2019-06-26 Thread Djordje Todorovic via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL364424: [clang/DIVar] Emit the flag for params that have 
unmodified value (authored by djtodoro, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D58035?vs=201505=206651#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D58035

Files:
  cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
  cfe/trunk/lib/CodeGen/CGDebugInfo.h
  cfe/trunk/test/CodeGen/debug-info-param-modification.c

Index: cfe/trunk/test/CodeGen/debug-info-param-modification.c
===
--- cfe/trunk/test/CodeGen/debug-info-param-modification.c
+++ cfe/trunk/test/CodeGen/debug-info-param-modification.c
@@ -0,0 +1,12 @@
+// RUN: %clang -Xclang -femit-debug-entry-values -g -O2 -S -target x86_64-none-linux-gnu -emit-llvm %s -o - | FileCheck %s -check-prefix=CHECK-ENTRY-VAL-OPT
+// CHECK-ENTRY-VAL-OPT: !DILocalVariable(name: "a", arg: 1, scope: {{.*}}, file: {{.*}}, line: {{.*}}, type: {{.*}})
+// CHECK-ENTRY-VAL-OPT: !DILocalVariable(name: "b", arg: 2, scope: {{.*}}, file: {{.*}}, line: {{.*}}, type: {{.*}}, flags: DIFlagArgumentNotModified)
+//
+// RUN: %clang -g -O2 -target x86_64-none-linux-gnu -S -emit-llvm %s -o - | FileCheck %s
+// CHECK-NOT: !DILocalVariable(name: "b", arg: 2, scope: {{.*}}, file: {{.*}}, line: {{.*}}, type: {{.*}}, flags: DIFlagArgumentNotModified)
+//
+
+int fn2 (int a, int b) {
+  ++a;
+  return b;
+}
Index: cfe/trunk/lib/CodeGen/CGDebugInfo.h
===
--- cfe/trunk/lib/CodeGen/CGDebugInfo.h
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.h
@@ -134,6 +134,10 @@
 
   llvm::DenseMap DIFileCache;
   llvm::DenseMap SPCache;
+  /// Cache function definitions relevant to use for parameters mutation
+  /// analysis.
+  llvm::DenseMap SPDefCache;
+  llvm::DenseMap ParamCache;
   /// Cache declarations relevant to DW_TAG_imported_declarations (C++
   /// using declarations) that aren't covered by other more specific caches.
   llvm::DenseMap DeclCache;
Index: cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
===
--- cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
@@ -18,6 +18,7 @@
 #include "CodeGenFunction.h"
 #include "CodeGenModule.h"
 #include "ConstantEmitter.h"
+#include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclFriend.h"
 #include "clang/AST/DeclObjC.h"
@@ -3588,6 +3589,12 @@
   if (HasDecl && isa(D))
 DeclCache[D->getCanonicalDecl()].reset(SP);
 
+  // We use the SPDefCache only in the case when the debug entry values option
+  // is set, in order to speed up parameters modification analysis.
+  if (CGM.getCodeGenOpts().EnableDebugEntryValues && HasDecl &&
+  isa(D))
+SPDefCache[cast(D)].reset(SP);
+
   if (CGM.getCodeGenOpts().DwarfVersion >= 5) {
 // Starting with DWARF V5 method declarations are emitted as children of
 // the interface type.
@@ -3964,6 +3971,11 @@
  llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
  Builder.GetInsertBlock());
 
+  if (CGM.getCodeGenOpts().EnableDebugEntryValues && ArgNo) {
+if (auto *PD = dyn_cast(VD))
+  ParamCache[PD].reset(D);
+  }
+
   return D;
 }
 
@@ -4555,6 +4567,29 @@
   TheCU->setDWOId(Signature);
 }
 
+/// Analyzes each function parameter to determine whether it is constant
+/// throughout the function body.
+static void analyzeParametersModification(
+ASTContext ,
+llvm::DenseMap ,
+llvm::DenseMap ) {
+  for (auto  : SPDefCache) {
+auto *FD = SP.first;
+assert(FD->hasBody() && "Functions must have body here");
+const Stmt *FuncBody = (*FD).getBody();
+for (auto Parm : FD->parameters()) {
+  ExprMutationAnalyzer FuncAnalyzer(*FuncBody, Ctx);
+  if (FuncAnalyzer.isMutated(Parm))
+continue;
+
+  auto I = ParamCache.find(Parm);
+  assert(I != ParamCache.end() && "Parameters should be already cached");
+  auto *DIParm = cast(I->second);
+  DIParm->setIsNotModified();
+}
+  }
+}
+
 void CGDebugInfo::finalize() {
   // Creating types might create further types - invalidating the current
   // element and the size(), so don't cache/reference them.
@@ -4627,6 +4662,10 @@
 if (auto MD = TypeCache[RT])
   DBuilder.retainType(cast(MD));
 
+  if (CGM.getCodeGenOpts().EnableDebugEntryValues)
+// This will be used to emit debug entry values.
+analyzeParametersModification(CGM.getContext(), SPDefCache, ParamCache);
+
   DBuilder.finalize();
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D63561: [OpenCL] Improve diagnostic for placement new

2019-06-26 Thread Sven van Haastregt via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL364423: [OpenCL] Improve diagnostic for placement new 
(authored by svenvh, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D63561?vs=205611=206650#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D63561

Files:
  cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
  cfe/trunk/lib/Sema/SemaExprCXX.cpp
  cfe/trunk/test/SemaOpenCLCXX/newdelete.cl


Index: cfe/trunk/lib/Sema/SemaExprCXX.cpp
===
--- cfe/trunk/lib/Sema/SemaExprCXX.cpp
+++ cfe/trunk/lib/Sema/SemaExprCXX.cpp
@@ -2413,7 +2413,11 @@
 }
 
 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
-  Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
+  if (PlaceArgs.empty()) {
+Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
+  } else {
+Diag(StartLoc, diag::err_openclcxx_placement_new);
+  }
   return true;
 }
 
Index: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
===
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
@@ -8809,6 +8809,9 @@
   "vector component name '%0' is an OpenCL version 2.2 feature">,
   InGroup;
 
+def err_openclcxx_placement_new : Error<
+  "use of placement new requires explicit declaration">;
+
 // MIG routine annotations.
 def warn_mig_server_routine_does_not_return_kern_return_t : Warning<
   "'mig_server_routine' attribute only applies to routines that return a 
kern_return_t">,
Index: cfe/trunk/test/SemaOpenCLCXX/newdelete.cl
===
--- cfe/trunk/test/SemaOpenCLCXX/newdelete.cl
+++ cfe/trunk/test/SemaOpenCLCXX/newdelete.cl
@@ -21,7 +21,7 @@
 void test_default_new_delete(void *buffer, A **pa) {
   A *a = new A; // expected-error {{'default new' is not supported in 
OpenCL C++}}
   delete a; // expected-error {{'default delete' is not supported 
in OpenCL C++}}
-  *pa = new (buffer) A; // expected-error {{'default new' is not supported in 
OpenCL C++}}
+  *pa = new (buffer) A; // expected-error {{use of placement new requires 
explicit declaration}}
 }
 
 // expected-note@+1 {{candidate function not viable: requires 2 arguments, but 
1 was provided}}


Index: cfe/trunk/lib/Sema/SemaExprCXX.cpp
===
--- cfe/trunk/lib/Sema/SemaExprCXX.cpp
+++ cfe/trunk/lib/Sema/SemaExprCXX.cpp
@@ -2413,7 +2413,11 @@
 }
 
 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
-  Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
+  if (PlaceArgs.empty()) {
+Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
+  } else {
+Diag(StartLoc, diag::err_openclcxx_placement_new);
+  }
   return true;
 }
 
Index: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
===
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
@@ -8809,6 +8809,9 @@
   "vector component name '%0' is an OpenCL version 2.2 feature">,
   InGroup;
 
+def err_openclcxx_placement_new : Error<
+  "use of placement new requires explicit declaration">;
+
 // MIG routine annotations.
 def warn_mig_server_routine_does_not_return_kern_return_t : Warning<
   "'mig_server_routine' attribute only applies to routines that return a kern_return_t">,
Index: cfe/trunk/test/SemaOpenCLCXX/newdelete.cl
===
--- cfe/trunk/test/SemaOpenCLCXX/newdelete.cl
+++ cfe/trunk/test/SemaOpenCLCXX/newdelete.cl
@@ -21,7 +21,7 @@
 void test_default_new_delete(void *buffer, A **pa) {
   A *a = new A; // expected-error {{'default new' is not supported in OpenCL C++}}
   delete a; // expected-error {{'default delete' is not supported in OpenCL C++}}
-  *pa = new (buffer) A; // expected-error {{'default new' is not supported in OpenCL C++}}
+  *pa = new (buffer) A; // expected-error {{use of placement new requires explicit declaration}}
 }
 
 // expected-note@+1 {{candidate function not viable: requires 2 arguments, but 1 was provided}}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D63773: [clangd] dummy variable extraction on a function scope

2019-06-26 Thread Shaurya Gupta via Phabricator via cfe-commits
SureYeaah marked 12 inline comments as done.
SureYeaah added inline comments.



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp:54
+
+// RAV subclass to find all DeclRefs in a given Stmt
+class FindDeclRefsVisitor

kadircet wrote:
> I believe this class is rather used to check if any decl referenced in an 
> expression was declared in a statement, rather then finding those declrefs.
> 
> So what about turning it inside out :D ? Something like:
> 
> ```
> bool isDeclaredIn(const DeclStmt *DS, const Expr *E, SourceManager ) {
>   // Collects all DelcRefs in an AST node.
>   class FindDeclRefsVisitor  {
>   public: 
> bool VisitDeclRefExpr(... *DRE) { DeclRefs.push_back(DRE); return true; }
> std::vector DeclRefs;
>   };
>   FindDeclRefsVisitor X;
>   X.TraverseStmt ...
>   for(auto *DRE : X.DeclRefs) {
>  ...
>}
>return ...;
> }
> ```
Aah, I didn't know you could declare a class inside a function. Nice.



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp:95
+// Returns true if we will need braces after extraction
+static bool needBraces(const SelectionTree::Node *N, const Stmt *Stm,
+   const SourceManager ) {

kadircet wrote:
> I suppose currently this check is not doing what it claims to do(not checking 
> for whether it is the only statement and/or if there are enclosing braces).
> 
> Maybe leave it out of this patch completely?
Right now, we check whether we will need braces and if so, we don't provide an 
extraction option. Although we don't insert the braces, we still need to check 
if the extraction would require braces.

The "body" of an if, for, while etc. will either be a CompoundStmt in which 
case there are already braces or not in which case there are no braces. So if 
while going up the AST parents, we encounter a CompoundStmt, we stop there. 
Otherwise, if we encounter an if/for/while etc. Stmt, we we have 2 cases - 
Either we are in the body (e.g. do  while(...); ) or the condition part 
(e.g. if(...) or for(...)). So we check which of these two cases it is and 
accordingly decide if we need braces i.e. the body case.

So we don't need to check whether it's the only statement. Does that make sense?



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp:108
+// check whether to allow extraction from for(...)
+static bool checkFor(const ForStmt *F, const Expr *Exp,
+ const SourceManager ) {

kadircet wrote:
> I believe it would be better to have a more generic check that will ensure 
> all of the delcs referenced in `Exp` are still visible in the context which 
> we'll insert the new statement. WDYT?
> 
> Were there any reasons to make it specific for `ForStmt` ?
The reason why it's specific for ForStmt (at least for now) is because only in 
ForStmt we can have declarations as well as other expressions in the for(...) 
part. For all other cases, we don't have such a scenario. WDYT?



Comment at: clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp:137
+  N->ASTNode.get(), M)) {
+  // Check whether the expression references any variable in the for
+  // initializer and if so, we can't extract

kadircet wrote:
> what about a case like:
> ```
> for(int i=0;;) {
>   int z = [[f(i)*10]] + 5;
> }
> ```
> I believe it should be OK to extract in this case right ?
This check is only for extraction from the for(; ; ) and not 
the body of the for. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63773



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


r364424 - [clang/DIVar] Emit the flag for params that have unmodified value

2019-06-26 Thread Djordje Todorovic via cfe-commits
Author: djtodoro
Date: Wed Jun 26 06:32:02 2019
New Revision: 364424

URL: http://llvm.org/viewvc/llvm-project?rev=364424=rev
Log:
[clang/DIVar] Emit the flag for params that have unmodified value

Emit the debug info flag that indicates that a parameter has unchanged
value throughout a function.

([5/13] Introduce the debug entry values.)

Co-authored-by: Ananth Sowda 
Co-authored-by: Nikola Prica 
Co-authored-by: Ivan Baev 

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

Added:
cfe/trunk/test/CodeGen/debug-info-param-modification.c
Modified:
cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
cfe/trunk/lib/CodeGen/CGDebugInfo.h

Modified: cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDebugInfo.cpp?rev=364424=364423=364424=diff
==
--- cfe/trunk/lib/CodeGen/CGDebugInfo.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.cpp Wed Jun 26 06:32:02 2019
@@ -18,6 +18,7 @@
 #include "CodeGenFunction.h"
 #include "CodeGenModule.h"
 #include "ConstantEmitter.h"
+#include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclFriend.h"
 #include "clang/AST/DeclObjC.h"
@@ -3588,6 +3589,12 @@ void CGDebugInfo::EmitFunctionStart(Glob
   if (HasDecl && isa(D))
 DeclCache[D->getCanonicalDecl()].reset(SP);
 
+  // We use the SPDefCache only in the case when the debug entry values option
+  // is set, in order to speed up parameters modification analysis.
+  if (CGM.getCodeGenOpts().EnableDebugEntryValues && HasDecl &&
+  isa(D))
+SPDefCache[cast(D)].reset(SP);
+
   if (CGM.getCodeGenOpts().DwarfVersion >= 5) {
 // Starting with DWARF V5 method declarations are emitted as children of
 // the interface type.
@@ -3964,6 +3971,11 @@ llvm::DILocalVariable *CGDebugInfo::Emit
  llvm::DebugLoc::get(Line, Column, Scope, 
CurInlinedAt),
  Builder.GetInsertBlock());
 
+  if (CGM.getCodeGenOpts().EnableDebugEntryValues && ArgNo) {
+if (auto *PD = dyn_cast(VD))
+  ParamCache[PD].reset(D);
+  }
+
   return D;
 }
 
@@ -4555,6 +4567,29 @@ void CGDebugInfo::setDwoId(uint64_t Sign
   TheCU->setDWOId(Signature);
 }
 
+/// Analyzes each function parameter to determine whether it is constant
+/// throughout the function body.
+static void analyzeParametersModification(
+ASTContext ,
+llvm::DenseMap ,
+llvm::DenseMap ) {
+  for (auto  : SPDefCache) {
+auto *FD = SP.first;
+assert(FD->hasBody() && "Functions must have body here");
+const Stmt *FuncBody = (*FD).getBody();
+for (auto Parm : FD->parameters()) {
+  ExprMutationAnalyzer FuncAnalyzer(*FuncBody, Ctx);
+  if (FuncAnalyzer.isMutated(Parm))
+continue;
+
+  auto I = ParamCache.find(Parm);
+  assert(I != ParamCache.end() && "Parameters should be already cached");
+  auto *DIParm = cast(I->second);
+  DIParm->setIsNotModified();
+}
+  }
+}
+
 void CGDebugInfo::finalize() {
   // Creating types might create further types - invalidating the current
   // element and the size(), so don't cache/reference them.
@@ -4627,6 +4662,10 @@ void CGDebugInfo::finalize() {
 if (auto MD = TypeCache[RT])
   DBuilder.retainType(cast(MD));
 
+  if (CGM.getCodeGenOpts().EnableDebugEntryValues)
+// This will be used to emit debug entry values.
+analyzeParametersModification(CGM.getContext(), SPDefCache, ParamCache);
+
   DBuilder.finalize();
 }
 

Modified: cfe/trunk/lib/CodeGen/CGDebugInfo.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDebugInfo.h?rev=364424=364423=364424=diff
==
--- cfe/trunk/lib/CodeGen/CGDebugInfo.h (original)
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.h Wed Jun 26 06:32:02 2019
@@ -134,6 +134,10 @@ class CGDebugInfo {
 
   llvm::DenseMap DIFileCache;
   llvm::DenseMap SPCache;
+  /// Cache function definitions relevant to use for parameters mutation
+  /// analysis.
+  llvm::DenseMap SPDefCache;
+  llvm::DenseMap ParamCache;
   /// Cache declarations relevant to DW_TAG_imported_declarations (C++
   /// using declarations) that aren't covered by other more specific caches.
   llvm::DenseMap DeclCache;

Added: cfe/trunk/test/CodeGen/debug-info-param-modification.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/debug-info-param-modification.c?rev=364424=auto
==
--- cfe/trunk/test/CodeGen/debug-info-param-modification.c (added)
+++ cfe/trunk/test/CodeGen/debug-info-param-modification.c Wed Jun 26 06:32:02 
2019
@@ -0,0 +1,12 @@
+// RUN: %clang -Xclang -femit-debug-entry-values -g -O2 -S -target 
x86_64-none-linux-gnu -emit-llvm %s -o - | FileCheck %s 
-check-prefix=CHECK-ENTRY-VAL-OPT
+// CHECK-ENTRY-VAL-OPT: !DILocalVariable(name: "a", arg: 1, scope: {{.*}}, 

r364423 - [OpenCL] Improve diagnostic for placement new

2019-06-26 Thread Sven van Haastregt via cfe-commits
Author: svenvh
Date: Wed Jun 26 06:31:24 2019
New Revision: 364423

URL: http://llvm.org/viewvc/llvm-project?rev=364423=rev
Log:
[OpenCL] Improve diagnostic for placement new

Without an explicit declaration for placement new, clang would reject
uses of placement new with "'default new' is not supported in OpenCL
C++".  This may mislead users into thinking that placement new is not
supported, see e.g. PR42060.

Clarify that placement new requires an explicit declaration.

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

Modified:
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/lib/Sema/SemaExprCXX.cpp
cfe/trunk/test/SemaOpenCLCXX/newdelete.cl

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=364423=364422=364423=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Wed Jun 26 06:31:24 
2019
@@ -8809,6 +8809,9 @@ def ext_opencl_ext_vector_type_rgba_sele
   "vector component name '%0' is an OpenCL version 2.2 feature">,
   InGroup;
 
+def err_openclcxx_placement_new : Error<
+  "use of placement new requires explicit declaration">;
+
 // MIG routine annotations.
 def warn_mig_server_routine_does_not_return_kern_return_t : Warning<
   "'mig_server_routine' attribute only applies to routines that return a 
kern_return_t">,

Modified: cfe/trunk/lib/Sema/SemaExprCXX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExprCXX.cpp?rev=364423=364422=364423=diff
==
--- cfe/trunk/lib/Sema/SemaExprCXX.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExprCXX.cpp Wed Jun 26 06:31:24 2019
@@ -2413,7 +2413,11 @@ bool Sema::FindAllocationFunctions(Sourc
 }
 
 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
-  Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
+  if (PlaceArgs.empty()) {
+Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
+  } else {
+Diag(StartLoc, diag::err_openclcxx_placement_new);
+  }
   return true;
 }
 

Modified: cfe/trunk/test/SemaOpenCLCXX/newdelete.cl
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaOpenCLCXX/newdelete.cl?rev=364423=364422=364423=diff
==
--- cfe/trunk/test/SemaOpenCLCXX/newdelete.cl (original)
+++ cfe/trunk/test/SemaOpenCLCXX/newdelete.cl Wed Jun 26 06:31:24 2019
@@ -21,7 +21,7 @@ class B {
 void test_default_new_delete(void *buffer, A **pa) {
   A *a = new A; // expected-error {{'default new' is not supported in 
OpenCL C++}}
   delete a; // expected-error {{'default delete' is not supported 
in OpenCL C++}}
-  *pa = new (buffer) A; // expected-error {{'default new' is not supported in 
OpenCL C++}}
+  *pa = new (buffer) A; // expected-error {{use of placement new requires 
explicit declaration}}
 }
 
 // expected-note@+1 {{candidate function not viable: requires 2 arguments, but 
1 was provided}}


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


[PATCH] D61446: Generalize the pass registration mechanism used by Polly to any third-party tool

2019-06-26 Thread serge via Phabricator via cfe-commits
serge-sans-paille updated this revision to Diff 206648.
serge-sans-paille marked an inline comment as done.
serge-sans-paille added a comment.

@Meinersbur your comment and my devs crossed, but this should be fine. This 
update enables new PM static plugin support for clang, something that was 
lacking to polly previously. I've tested it a bit and it builds fine with 
static setup, still need to test it with more config.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D61446

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/CodeGen/CMakeLists.txt
  clang/tools/driver/CMakeLists.txt
  clang/tools/driver/cc1_main.cpp
  llvm/CMakeLists.txt
  llvm/cmake/modules/AddLLVM.cmake
  llvm/cmake/modules/LLVMProcessSources.cmake
  llvm/docs/WritingAnLLVMPass.rst
  llvm/include/llvm/Config/llvm-config.h.cmake
  llvm/tools/CMakeLists.txt
  llvm/tools/bugpoint/CMakeLists.txt
  llvm/tools/bugpoint/bugpoint.cpp
  llvm/tools/opt/CMakeLists.txt
  llvm/tools/opt/NewPMDriver.cpp
  llvm/tools/opt/opt.cpp
  llvm/utils/gn/secondary/llvm/include/llvm/Config/BUILD.gn
  polly/include/polly/RegisterPasses.h
  polly/lib/CMakeLists.txt
  polly/lib/Polly.cpp
  polly/lib/Support/RegisterPasses.cpp
  polly/test/Unit/lit.site.cfg.in
  polly/test/lit.site.cfg.in
  polly/test/update_check.py

Index: polly/test/update_check.py
===
--- polly/test/update_check.py
+++ polly/test/update_check.py
@@ -15,7 +15,7 @@
 polly_lib_dir = '''@POLLY_LIB_DIR@'''
 shlibext = '''@LLVM_SHLIBEXT@'''
 llvm_tools_dir = '''@LLVM_TOOLS_DIR@'''
-link_polly_into_tools = not '''@LINK_POLLY_INTO_TOOLS@'''.lower() in {'','0','n','no','off','false','notfound','link_polly_into_tools-notfound'}
+llvm_polly_link_into_tools = not '''@LLVM_POLLY_LINK_INTO_TOOLS@'''.lower() in {'','0','n','no','off','false','notfound','llvm_polly_link_into_tools-notfound'}
 
 runre = re.compile(r'\s*\;\s*RUN\s*\:(?P.*)')
 filecheckre = re.compile(r'\s*(?P.*)\|\s*(?PFileCheck\s[^|]*)')
@@ -298,7 +298,7 @@
 toolarg = toolarg.replace('%s', filename)
 toolarg = toolarg.replace('%S', os.path.dirname(filename))
 if toolarg == '%loadPolly':
-if not link_polly_into_tools:
+if not llvm_polly_link_into_tools:
 newtool += ['-load',os.path.join(polly_lib_dir,'LLVMPolly' + shlibext)]
 newtool.append('-polly-process-unprofitable')
 newtool.append('-polly-remarks-minimal')
Index: polly/test/lit.site.cfg.in
===
--- polly/test/lit.site.cfg.in
+++ polly/test/lit.site.cfg.in
@@ -8,7 +8,7 @@
 config.polly_lib_dir = "@POLLY_LIB_DIR@"
 config.target_triple = "@TARGET_TRIPLE@"
 config.enable_gpgpu_codegen = "@GPU_CODEGEN@"
-config.link_polly_into_tools = "@LINK_POLLY_INTO_TOOLS@"
+config.llvm_polly_link_into_tools = "@LLVM_POLLY_LINK_INTO_TOOLS@"
 config.targets_to_build = "@TARGETS_TO_BUILD@"
 config.extra_paths = "@POLLY_TEST_EXTRA_PATHS@".split(";")
 
@@ -36,14 +36,14 @@
 # directories.
 config.excludes = ['Inputs']
 
-if config.link_polly_into_tools == '' or \
-   config.link_polly_into_tools.lower() == '0' or \
-   config.link_polly_into_tools.lower() == 'n' or \
-   config.link_polly_into_tools.lower() == 'no' or \
-   config.link_polly_into_tools.lower() == 'off' or \
-   config.link_polly_into_tools.lower() == 'false' or \
-   config.link_polly_into_tools.lower() == 'notfound' or \
-   config.link_polly_into_tools.lower() == 'link_polly_into_tools-notfound':
+if config.llvm_polly_link_into_tools == '' or \
+   config.llvm_polly_link_into_tools.lower() == '0' or \
+   config.llvm_polly_link_into_tools.lower() == 'n' or \
+   config.llvm_polly_link_into_tools.lower() == 'no' or \
+   config.llvm_polly_link_into_tools.lower() == 'off' or \
+   config.llvm_polly_link_into_tools.lower() == 'false' or \
+   config.llvm_polly_link_into_tools.lower() == 'notfound' or \
+   config.llvm_polly_link_into_tools.lower() == 'llvm_polly_link_into_tools-notfound':
 config.substitutions.append(('%loadPolly', '-load '
  + config.polly_lib_dir + '/LLVMPolly@LLVM_SHLIBEXT@'
  + ' -load-pass-plugin '
Index: polly/test/Unit/lit.site.cfg.in
===
--- polly/test/Unit/lit.site.cfg.in
+++ polly/test/Unit/lit.site.cfg.in
@@ -13,7 +13,7 @@
 config.shlibdir = "@SHLIBDIR@"
 config.target_triple = "@TARGET_TRIPLE@"
 config.enable_gpgpu_codegen = "@GPU_CODEGEN@"
-config.link_polly_into_tools = "@LINK_POLLY_INTO_TOOLS@"
+config.llvm_polly_link_into_tools = "@LLVM_POLLY_LINK_INTO_TOOLS@"
 config.has_unittests = @POLLY_GTEST_AVAIL@
 
 # Support substitution of the tools_dir, libs_dirs, and build_mode with user
Index: polly/lib/Support/RegisterPasses.cpp

[PATCH] D63817: [clangd] No longer getting template instantiations from header files in Main AST.

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



Comment at: clang-tools-extra/clangd/ClangdUnit.cpp:74
 
+  if (!SM->isInMainFile(D->getLocation()))
+// This decl comes from another file and should not be included in the

you could get SourceManager from `D->getASTContext().getSourceManager()`.



Comment at: clang-tools-extra/clangd/ClangdUnit.cpp:75
+  if (!SM->isInMainFile(D->getLocation()))
+// This decl comes from another file and should not be included in the
+// top level decls.

nit: This comment just repeats the code, I think the comment describe why we 
need to do this check (because of the template instantiation?)  


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D63817



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


[clang-tools-extra] r364421 - [clangd] Added functionality for getting semantic highlights for variable and function declarations

2019-06-26 Thread Johan Vikstrom via cfe-commits
Author: jvikstrom
Date: Wed Jun 26 06:08:36 2019
New Revision: 364421

URL: http://llvm.org/viewvc/llvm-project?rev=364421=rev
Log:
[clangd] Added functionality for getting semantic highlights for variable and 
function declarations

Added:
clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp
clang-tools-extra/trunk/clangd/SemanticHighlighting.h
clang-tools-extra/trunk/clangd/unittests/SemanticHighlightingTests.cpp
Modified:
clang-tools-extra/trunk/clangd/CMakeLists.txt
clang-tools-extra/trunk/clangd/unittests/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=364421=364420=364421=diff
==
--- clang-tools-extra/trunk/clangd/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clangd/CMakeLists.txt Wed Jun 26 06:08:36 2019
@@ -63,6 +63,7 @@ add_clang_library(clangDaemon
   Quality.cpp
   RIFF.cpp
   Selection.cpp
+  SemanticHighlighting.cpp
   SourceCode.cpp
   QueryDriverDatabase.cpp
   Threading.cpp

Added: clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp?rev=364421=auto
==
--- clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp (added)
+++ clang-tools-extra/trunk/clangd/SemanticHighlighting.cpp Wed Jun 26 06:08:36 
2019
@@ -0,0 +1,78 @@
+//===--- SemanticHighlighting.cpp - -- ---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "SemanticHighlighting.h"
+#include "Logger.h"
+#include "SourceCode.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+// Collects all semantic tokens in an ASTContext.
+class HighlightingTokenCollector
+: public RecursiveASTVisitor {
+  std::vector Tokens;
+  ASTContext 
+  const SourceManager 
+
+public:
+  HighlightingTokenCollector(ParsedAST )
+  : Ctx(AST.getASTContext()), SM(AST.getSourceManager()) {}
+
+  std::vector collectTokens() {
+Tokens.clear();
+TraverseAST(Ctx);
+return Tokens;
+  }
+
+  bool VisitVarDecl(VarDecl *Var) {
+addToken(Var, HighlightingKind::Variable);
+return true;
+  }
+  bool VisitFunctionDecl(FunctionDecl *Func) {
+addToken(Func, HighlightingKind::Function);
+return true;
+  }
+
+private:
+  void addToken(const NamedDecl *D, HighlightingKind Kind) {
+if (D->getLocation().isMacroID())
+  // FIXME: skip tokens inside macros for now.
+  return;
+
+if (D->getDeclName().isEmpty())
+  // Don't add symbols that don't have any length.
+  return;
+
+auto R = getTokenRange(SM, Ctx.getLangOpts(), D->getLocation());
+if (!R) {
+  // R should always have a value, if it doesn't something is very wrong.
+  elog("Tried to add semantic token with an invalid range");
+  return;
+}
+
+Tokens.push_back({Kind, R.getValue()});
+  }
+};
+
+} // namespace
+
+bool operator==(const HighlightingToken , const HighlightingToken ) {
+  return Lhs.Kind == Rhs.Kind && Lhs.R == Rhs.R;
+}
+
+std::vector getSemanticHighlightings(ParsedAST ) {
+  AST.getASTContext().setTraversalScope(AST.getLocalTopLevelDecls());
+  return HighlightingTokenCollector(AST).collectTokens();
+}
+
+} // namespace clangd
+} // namespace clang

Added: clang-tools-extra/trunk/clangd/SemanticHighlighting.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/SemanticHighlighting.h?rev=364421=auto
==
--- clang-tools-extra/trunk/clangd/SemanticHighlighting.h (added)
+++ clang-tools-extra/trunk/clangd/SemanticHighlighting.h Wed Jun 26 06:08:36 
2019
@@ -0,0 +1,37 @@
+//==-- SemanticHighlighting.h - Generating highlights from the AST-- C++ 
-*-==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_SEMANTICHIGHLIGHT_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_SEMANTICHIGHLIGHT_H
+
+#include "ClangdUnit.h"
+
+namespace clang {
+namespace clangd {
+
+enum class HighlightingKind {
+  Variable,
+  Function,
+};
+
+// Contains all information needed for the highlighting a token.
+struct HighlightingToken {
+  HighlightingKind Kind;
+  Range R;
+};
+
+bool operator==(const HighlightingToken , 

[PATCH] D63760: [clangd] Address limitations in SelectionTree:

2019-06-26 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

LGTM, thanks!




Comment at: clangd/Selection.cpp:45
+  if (R.first > Begin)
+return false; // [R.First, Begin) is not covered.
+  if (Begin < R.second)

I suppose comment should be `[Begin, R.first)`. Could you also change the order 
within condition?



Comment at: clangd/Selection.cpp:48
+Begin = R.second; // Prefix is covered, truncate the range.
+  if (Begin >= End)
+return true;

nit: maybe move this check into previous condition? i.e:
```
if (Begin < R.second) {
  Begin = R.second; // Prefix is covered, truncate the range.
  if (Begin >= End)
return true;
}



Comment at: clangd/Selection.cpp:236
   // This runs for every node in the AST, and must be fast in common cases.
   // This is called from pop(), so we can take children into account.
+  SelectionTree::Selection claimRange(SourceRange S) {

also called from push() now



Comment at: clangd/unittests/SelectionTests.cpp:170
+struct S { S(const char*); };
+S [[s ^= "foo"]];
+  )cpp",

could you also add a test case with cursor on identifier(i.e, `s`)


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D63760



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


[PATCH] D63818: [clangd] Collect the refs when the main file is header.

2019-06-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: ilya-biryukov.
Herald added subscribers: cfe-commits, kadircet, arphaman, jkorous, MaskRay.
Herald added a project: clang.

Previously, we only collect refs of the symbols which are declared in
the preamble and referenced in the main file, it works well when the
main file is .cpp file.

However, when the main file is .h file (when opening a .h file in the
editor), we don't collect refs of the symbol declared in this file, so we miss
these refs in our dynamic index.

A typical scenario:

1. Open Foo.h (which contains class Foo)
2. Open Foo.cpp, call find references for Foo

And we only get refs from Foo.cpp.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D63818

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


Index: clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
===
--- clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
+++ clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
@@ -626,6 +626,33 @@
   EXPECT_THAT(Refs, Not(Contains(Pair(findSymbol(MainSymbols, "c").ID, _;
 }
 
+
+TEST_F(SymbolCollectorTest, HeaderAsMainFile) {
+  CollectorOpts.RefFilter = RefKind::All;
+  Annotations Header(R"(
+  class $Foo[[Foo]] {};
+
+  void $Func[[Func]]() {
+$Foo[[Foo]] fo;
+  }
+  )");
+  // The main file is normal .cpp file, we shouldn't collect any refs of 
symbols
+  // which are not declared in the preamble.
+  TestFileName = testPath("foo.cpp");
+  runSymbolCollector("", Header.code());
+  EXPECT_THAT(Refs, UnorderedElementsAre());
+
+  // Run the .h file as main file, we should collect the refs.
+  TestFileName = testPath("foo.h");
+  runSymbolCollector("", Header.code(),
+ /*ExtraArgs=*/{"-xobjective-c++-header"});
+  EXPECT_THAT(Symbols, UnorderedElementsAre(QName("Foo"), QName("Func")));
+  EXPECT_THAT(Refs, UnorderedElementsAre(Pair(findSymbol(Symbols, "Foo").ID,
+  HaveRanges(Header.ranges("Foo"))),
+ Pair(findSymbol(Symbols, "Func").ID,
+  HaveRanges(Header.ranges("Func");
+}
+
 TEST_F(SymbolCollectorTest, RefsInHeaders) {
   CollectorOpts.RefFilter = RefKind::All;
   CollectorOpts.RefsInHeaders = true;
Index: clang-tools-extra/clangd/index/SymbolCollector.h
===
--- clang-tools-extra/clangd/index/SymbolCollector.h
+++ clang-tools-extra/clangd/index/SymbolCollector.h
@@ -134,9 +134,10 @@
   void setIncludeLocation(const Symbol , SourceLocation);
   // Indexed macros, to be erased if they turned out to be include guards.
   llvm::DenseSet IndexedMacros;
-  // All refs collected from the AST.
-  // Only symbols declared in preamble (from #include) and referenced from the
-  // main file will be included.
+  // All refs collected from the AST. It includes:
+  //   1) symbols declared in the preamble and referenced from the main file (
+  // which is not a header), or
+  //   2) symbols declared and referenced from the main file (which is a 
header)
   RefSlab::Builder Refs;
   // All relations collected from the AST.
   RelationSlab::Builder Relations;
Index: clang-tools-extra/clangd/index/SymbolCollector.cpp
===
--- clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -314,10 +314,12 @@
   if (IsOnlyRef && !CollectRef)
 return true;
 
-  // ND is the canonical (i.e. first) declaration. If it's in the main file,
-  // then no public declaration was visible, so assume it's main-file only.
+  // ND is the canonical (i.e. first) declaration. If it's in the main file
+  // (which is not a header), then no public declaration was visible, so assume
+  // it's main-file only.
   bool IsMainFileOnly =
-  SM.isWrittenInMainFile(SM.getExpansionLoc(ND->getBeginLoc()));
+  SM.isWrittenInMainFile(SM.getExpansionLoc(ND->getBeginLoc())) &&
+  !ASTCtx->getLangOpts().IsHeaderFile;
   // In C, printf is a redecl of an implicit builtin! So check OrigD instead.
   if (ASTNode.OrigD->isImplicit() ||
   !shouldCollectSymbol(*ND, *ASTCtx, Opts, IsMainFileOnly))


Index: clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
===
--- clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
+++ clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
@@ -626,6 +626,33 @@
   EXPECT_THAT(Refs, Not(Contains(Pair(findSymbol(MainSymbols, "c").ID, _;
 }
 
+
+TEST_F(SymbolCollectorTest, HeaderAsMainFile) {
+  CollectorOpts.RefFilter = RefKind::All;
+  Annotations Header(R"(
+  class $Foo[[Foo]] {};
+
+  void $Func[[Func]]() {
+$Foo[[Foo]] fo;
+  }

  1   2   >