[PATCH] D95244: [clang][AST] Handle overload callee type in CallExpr::getCallReturnType.

2021-02-03 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95244

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


[PATCH] D95871: [clang] Store the location for invalid type of a declarator.

2021-02-03 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

It would be nice to have a testcase with a nontrivial range so we can see the 
choice of location...




Comment at: clang/lib/Sema/SemaType.cpp:5659
   if (D.isInvalidType())
-return Context.getTrivialTypeSourceInfo(T);
-
+return Context.getTrivialTypeSourceInfo(T, D.getEndLoc());
   return GetTypeSourceInfoForDeclarator(state, T, TInfo);

why endloc rather than start or something else?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95871

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


[PATCH] D95915: [clang][driver] Only warn once about invalid -stdlib value

2021-02-03 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 321022.
tbaeder added a comment.

Noticed similar/worse behavior for -rtlib. Expanded the patch to that and 
-unwindlib as well.


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

https://reviews.llvm.org/D95915

Files:
  clang/lib/Driver/ToolChain.cpp


Index: clang/lib/Driver/ToolChain.cpp
===
--- clang/lib/Driver/ToolChain.cpp
+++ clang/lib/Driver/ToolChain.cpp
@@ -884,8 +884,14 @@
   else if (LibName == "platform")
 return GetDefaultRuntimeLibType();
 
-  if (A)
-getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
+  if (A) {
+static bool Warned = false;
+if (!Warned) {
+  getDriver().Diag(diag::err_drv_invalid_rtlib_name)
+  << A->getAsString(Args);
+  Warned = true;
+}
+  }
 
   return GetDefaultRuntimeLibType();
 }
@@ -910,9 +916,14 @@
   } else if (LibName == "libgcc")
 return ToolChain::UNW_Libgcc;
 
-  if (A)
-getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
-<< A->getAsString(Args);
+  if (A) {
+static bool Warned = false;
+if (!Warned) {
+  getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
+  << A->getAsString(Args);
+  Warned = true;
+}
+  }
 
   return GetDefaultUnwindLibType();
 }
@@ -929,8 +940,14 @@
   else if (LibName == "platform")
 return GetDefaultCXXStdlibType();
 
-  if (A)
-getDriver().Diag(diag::err_drv_invalid_stdlib_name) << 
A->getAsString(Args);
+  if (A) {
+static bool Warned = false;
+if (!Warned) {
+  getDriver().Diag(diag::err_drv_invalid_stdlib_name)
+  << A->getAsString(Args);
+  Warned = true;
+}
+  }
 
   return GetDefaultCXXStdlibType();
 }


Index: clang/lib/Driver/ToolChain.cpp
===
--- clang/lib/Driver/ToolChain.cpp
+++ clang/lib/Driver/ToolChain.cpp
@@ -884,8 +884,14 @@
   else if (LibName == "platform")
 return GetDefaultRuntimeLibType();
 
-  if (A)
-getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
+  if (A) {
+static bool Warned = false;
+if (!Warned) {
+  getDriver().Diag(diag::err_drv_invalid_rtlib_name)
+  << A->getAsString(Args);
+  Warned = true;
+}
+  }
 
   return GetDefaultRuntimeLibType();
 }
@@ -910,9 +916,14 @@
   } else if (LibName == "libgcc")
 return ToolChain::UNW_Libgcc;
 
-  if (A)
-getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
-<< A->getAsString(Args);
+  if (A) {
+static bool Warned = false;
+if (!Warned) {
+  getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
+  << A->getAsString(Args);
+  Warned = true;
+}
+  }
 
   return GetDefaultUnwindLibType();
 }
@@ -929,8 +940,14 @@
   else if (LibName == "platform")
 return GetDefaultCXXStdlibType();
 
-  if (A)
-getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
+  if (A) {
+static bool Warned = false;
+if (!Warned) {
+  getDriver().Diag(diag::err_drv_invalid_stdlib_name)
+  << A->getAsString(Args);
+  Warned = true;
+}
+  }
 
   return GetDefaultCXXStdlibType();
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95925: [clangd] Detect rename conflicits within enclosing scope

2021-02-03 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

Thanks, this looks right to me.




Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:338
+  const CompoundStmt *EnclosingScope = ParentNode->get();
+  if (const auto *If = ParentNode->get())
+if (const auto *Then = dyn_cast(If->getThen()))

I found that the current structure (we have two places of this `If` cases, and 
they are separated) is a bit hard to follow, I'd suggest union them, just like 
the code below, it seems straight-forward to me, and easy to extend. 


```
if (const auto* CompoundStmtEnclosing = Parents.begin()->get()) {
   CheckCompoundStmt(CompoundStmtEnclosing);
   // below we detect conflicts in conditions or others (if the CompoundStmt is 
a function body, we could detect the parameter decls as well)
   getParents(CompoundStmtEnclosing);
   if ( ...()) {
  CheckConditionVariable();
   } else if (...) {
   }
} else if (const auto* IfEnclosing = ... ()) {
   CheckCompoundStmt(If->getThen());
  // possibly CheckCompoundStmt(If->getElse)
} else {
  ...
}
```



Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:339
+  if (const auto *If = ParentNode->get())
+if (const auto *Then = dyn_cast(If->getThen()))
+  EnclosingScope = Then;

thinking more about the `if` case, I think else should be included as well? no 
need to address in this patch.

like

```
if (int a = 0) {
} else {
  int s; // rename s=>a will cause a compiling error.
}
```



Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:352
+for (const auto &Child : DS->getDeclGroup())
+  if (const auto *VD = dyn_cast(Child))
+if (VD != &RenamedDecl && VD->getName() == NewName)

nit: VarDecl => NamedDecl


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95925

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


[PATCH] D90851: [clang-tidy] Extending bugprone-signal-handler with POSIX functions.

2021-02-03 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added inline comments.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/bugprone-signal-handler.rst:29-30
+  
`_
+  for more information). This is not an extension of the minimal set 
(``quick_exit``
+  is not included). Default is ``POSIX``.

aaron.ballman wrote:
> aaron.ballman wrote:
> > Huh, that's really strange that POSIX leaves `quick_exit` off the list. I'm 
> > going to reach out to someone from the Austin Group to see if that's 
> > intentional or not.
> I didn't need to reach out to them because I realized the latest POSIX spec 
> is still based on C99 and they've not released the updated POSIX spec yet.
> 
> I think the POSIX functions should be a superset of the C functions.
Do you mean that we should add `quick_exit` to the POSIX set? And have a 
requirement that minimal set is subset of the POSIX set (if the lists are 
modified in the future)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D90851

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


[PATCH] D95860: [clang][Frontend] Fix a crash in DiagnosticRenderer.

2021-02-03 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D95860#2536721 , @balazske wrote:

> In D95860#2536609 , @steakhal wrote:
>
>> Please, also add a regression test for Haoxin Tu's reproducer.
>>
>>   // RUN: %clang %s
>>   
>>   // expected warning
>>   volatile long a ( a .~b
>
> What about the already added test?

Oh sorry, I was tricked by that the analyzer is enabled.

We would crash even without the analyzer, so pushing this test under the 
Analysis seems unnecessary to me.
BTW, the analysis expects a compiler-error-free program. This shouldn't 
compile. This is not related to analysis in any way.

The alpha.clone.CloneChecker reproducer however, crashes at the end of the 
analysis when it tries to emit the diagnostics. IMO that should be in the 
`Analysis`, the current one should be where frontend tests are.
IMO we should have tests for both of these.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95860

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


[PATCH] D92270: [ConstantFold] Fold more operations to poison

2021-02-03 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added a comment.

https://bugs.llvm.org/show_bug.cgi?id=49005 seems to be due to this (either 
directly or it has unearthed an existing problem)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92270

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


[PATCH] D62574: Add support for target-configurable address spaces.

2021-02-03 Thread Danila Malyutin via Phabricator via cfe-commits
danilaml added a comment.

So is missing an in-tree user (like AMDGPU) the only thing that prevents from 
merging this?


Repository:
  rG LLVM Github Monorepo

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


[PATCH] D95460: [flang][driver] Add forced form flags and -ffixed-line-length

2021-02-03 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski accepted this revision.
awarzynski added a comment.
This revision is now accepted and ready to land.

Thank you for working on this @FarisRehman !


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95460

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


[clang] d38973a - [clang][AVR] Improve avr-ld command line options

2021-02-03 Thread Ben Shi via cfe-commits

Author: Ben Shi
Date: 2021-02-03T18:23:01+08:00
New Revision: d38973aa4d6a2c8be97b9781ca7325ca3eb0c40d

URL: 
https://github.com/llvm/llvm-project/commit/d38973aa4d6a2c8be97b9781ca7325ca3eb0c40d
DIFF: 
https://github.com/llvm/llvm-project/commit/d38973aa4d6a2c8be97b9781ca7325ca3eb0c40d.diff

LOG: [clang][AVR] Improve avr-ld command line options

Reviewed By: dylanmckay, MaskRay

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/AVR.cpp
clang/test/Driver/avr-ld.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/AVR.cpp 
b/clang/lib/Driver/ToolChains/AVR.cpp
index ebbc6f2d5c79..697623cbee3e 100644
--- a/clang/lib/Driver/ToolChains/AVR.cpp
+++ b/clang/lib/Driver/ToolChains/AVR.cpp
@@ -32,247 +32,248 @@ const struct {
   StringRef Name;
   std::string SubPath;
   StringRef Family;
+  unsigned DataAddr;
 } MCUInfo[] = {
-{"at90s1200", "", "avr1"},
-{"attiny11", "", "avr1"},
-{"attiny12", "", "avr1"},
-{"attiny15", "", "avr1"},
-{"attiny28", "", "avr1"},
-{"at90s2313", "tiny-stack", "avr2"},
-{"at90s2323", "tiny-stack", "avr2"},
-{"at90s2333", "tiny-stack", "avr2"},
-{"at90s2343", "tiny-stack", "avr2"},
-{"at90s4433", "tiny-stack", "avr2"},
-{"attiny22", "tiny-stack", "avr2"},
-{"attiny26", "tiny-stack", "avr2"},
-{"at90s4414", "", "avr2"},
-{"at90s4434", "", "avr2"},
-{"at90s8515", "", "avr2"},
-{"at90c8534", "", "avr2"},
-{"at90s8535", "", "avr2"},
-{"attiny13", "avr25/tiny-stack", "avr25"},
-{"attiny13a", "avr25/tiny-stack", "avr25"},
-{"attiny2313", "avr25/tiny-stack", "avr25"},
-{"attiny2313a", "avr25/tiny-stack", "avr25"},
-{"attiny24", "avr25/tiny-stack", "avr25"},
-{"attiny24a", "avr25/tiny-stack", "avr25"},
-{"attiny25", "avr25/tiny-stack", "avr25"},
-{"attiny261", "avr25/tiny-stack", "avr25"},
-{"attiny261a", "avr25/tiny-stack", "avr25"},
-{"at86rf401", "avr25", "avr25"},
-{"ata5272", "avr25", "avr25"},
-{"attiny4313", "avr25", "avr25"},
-{"attiny44", "avr25", "avr25"},
-{"attiny44a", "avr25", "avr25"},
-{"attiny84", "avr25", "avr25"},
-{"attiny84a", "avr25", "avr25"},
-{"attiny45", "avr25", "avr25"},
-{"attiny85", "avr25", "avr25"},
-{"attiny441", "avr25", "avr25"},
-{"attiny461", "avr25", "avr25"},
-{"attiny461a", "avr25", "avr25"},
-{"attiny841", "avr25", "avr25"},
-{"attiny861", "avr25", "avr25"},
-{"attiny861a", "avr25", "avr25"},
-{"attiny87", "avr25", "avr25"},
-{"attiny43u", "avr25", "avr25"},
-{"attiny48", "avr25", "avr25"},
-{"attiny88", "avr25", "avr25"},
-{"attiny828", "avr25", "avr25"},
-{"at43usb355", "avr3", "avr3"},
-{"at76c711", "avr3", "avr3"},
-{"atmega103", "avr31", "avr31"},
-{"at43usb320", "avr31", "avr31"},
-{"attiny167", "avr35", "avr35"},
-{"at90usb82", "avr35", "avr35"},
-{"at90usb162", "avr35", "avr35"},
-{"ata5505", "avr35", "avr35"},
-{"atmega8u2", "avr35", "avr35"},
-{"atmega16u2", "avr35", "avr35"},
-{"atmega32u2", "avr35", "avr35"},
-{"attiny1634", "avr35", "avr35"},
-{"atmega8", "avr4", "avr4"},
-{"ata6289", "avr4", "avr4"},
-{"atmega8a", "avr4", "avr4"},
-{"ata6285", "avr4", "avr4"},
-{"ata6286", "avr4", "avr4"},
-{"atmega48", "avr4", "avr4"},
-{"atmega48a", "avr4", "avr4"},
-{"atmega48pa", "avr4", "avr4"},
-{"atmega48pb", "avr4", "avr4"},
-{"atmega48p", "avr4", "avr4"},
-{"atmega88", "avr4", "avr4"},
-{"atmega88a", "avr4", "avr4"},
-{"atmega88p", "avr4", "avr4"},
-{"atmega88pa", "avr4", "avr4"},
-{"atmega88pb", "avr4", "avr4"},
-{"atmega8515", "avr4", "avr4"},
-{"atmega8535", "avr4", "avr4"},
-{"atmega8hva", "avr4", "avr4"},
-{"at90pwm1", "avr4", "avr4"},
-{"at90pwm2", "avr4", "avr4"},
-{"at90pwm2b", "avr4", "avr4"},
-{"at90pwm3", "avr4", "avr4"},
-{"at90pwm3b", "avr4", "avr4"},
-{"at90pwm81", "avr4", "avr4"},
-{"ata5790", "avr5", "avr5"},
-{"ata5795", "avr5", "avr5"},
-{"atmega16", "avr5", "avr5"},
-{"atmega16a", "avr5", "avr5"},
-{"atmega161", "avr5", "avr5"},
-{"atmega162", "avr5", "avr5"},
-{"atmega163", "avr5", "avr5"},
-{"atmega164a", "avr5", "avr5"},
-{"atmega164p", "avr5", "avr5"},
-{"atmega164pa", "avr5", "avr5"},
-{"atmega165", "avr5", "avr5"},
-{"atmega165a", "avr5", "avr5"},
-{"atmega165p", "avr5", "avr5"},
-{"atmega165pa", "avr5", "avr5"},
-{"atmega168", "avr5", "avr5"},
-{"atmega168a", "avr5", "avr5"},
-{"atmega168p", "avr5", "avr5"},
-{"atmega168pa", "avr5", "avr5"},
-{"atmega168pb", "avr5", "avr5"},
-{"atmega169", "avr5", "avr5"},
-{"atmega169a", "avr5", "avr5"},
-{"atmega169p", "avr5", "avr5"},
-{"atmega169pa", "avr5", "avr5"},
-{"atmega32", "avr5", "avr5"},
-{"atmega32a", "

[PATCH] D93579: [clang][AVR] Improve avr-ld command line options

2021-02-03 Thread Ben Shi via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd38973aa4d6a: [clang][AVR] Improve avr-ld command line 
options (authored by benshi001).

Changed prior to commit:
  https://reviews.llvm.org/D93579?vs=318881&id=321035#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93579

Files:
  clang/lib/Driver/ToolChains/AVR.cpp
  clang/test/Driver/avr-ld.c

Index: clang/test/Driver/avr-ld.c
===
--- clang/test/Driver/avr-ld.c
+++ clang/test/Driver/avr-ld.c
@@ -1,2 +1,44 @@
-// RUN: %clang -### --target=avr -mmcu=atmega328 --sysroot %S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINK %s
-// LINK: {{".*ld.*"}} {{.*}} {{"-L.*avr5"}} {{.*}} "-Tdata=0x800100" {{.*}} "-latmega328" "-mavr5"
+// RUN: %clang -### --target=avr -mmcu=at90s2313 --sysroot %S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKA %s
+// LINKA: {{".*ld.*"}} {{.*}} {{"-L.*tiny-stack"}} {{.*}} "-Tdata=0x800060" {{.*}} "-lat90s2313" "-mavr2"
+
+// RUN: %clang -### --target=avr -mmcu=at90s8515 --sysroot %S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKB %s
+// LINKB: {{".*ld.*"}} {{.*}} "-Tdata=0x800060" {{.*}} "-lat90s8515" "-mavr2"
+
+// RUN: %clang -### --target=avr -mmcu=attiny13 --sysroot %S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKC %s
+// LINKC: {{".*ld.*"}} {{.*}} {{"-L.*avr25/tiny-stack"}} {{.*}} "-Tdata=0x800060" {{.*}} "-lattiny13" "-mavr25"
+
+// RUN: %clang -### --target=avr -mmcu=attiny44 --sysroot %S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKD %s
+// LINKD: {{".*ld.*"}} {{.*}} {{"-L.*avr25"}} {{.*}} "-Tdata=0x800060" {{.*}} "-lattiny44" "-mavr25"
+
+// RUN: %clang -### --target=avr -mmcu=atmega103 --sysroot %S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKE %s
+// LINKE: {{".*ld.*"}} {{.*}} {{"-L.*avr31"}} {{.*}} "-Tdata=0x800060" {{.*}} "-latmega103" "-mavr31"
+
+// RUN: %clang -### --target=avr -mmcu=atmega8u2 --sysroot %S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKF %s
+// LINKF: {{".*ld.*"}} {{.*}} {{"-L.*avr35"}} {{.*}} "-Tdata=0x800100" {{.*}} "-latmega8u2" "-mavr35"
+
+// RUN: %clang -### --target=avr -mmcu=atmega48pa --sysroot %S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKG %s
+// LINKG: {{".*ld.*"}} {{.*}} {{"-L.*avr4"}} {{.*}} "-Tdata=0x800100" {{.*}} "-latmega48pa" "-mavr4"
+
+// RUN: %clang -### --target=avr -mmcu=atmega328 --sysroot %S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKH %s
+// LINKH: {{".*ld.*"}} {{.*}} {{"-L.*avr5"}} {{.*}} "-Tdata=0x800100" {{.*}} "-latmega328" "-mavr5"
+
+// RUN: %clang -### --target=avr -mmcu=atmega1281 --sysroot %S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKI %s
+// LINKI: {{".*ld.*"}} {{.*}} {{"-L.*avr51"}} {{.*}} "-Tdata=0x800200" {{.*}} "-latmega1281" "-mavr51"
+
+// RUN: %clang -### --target=avr -mmcu=atmega2560 --sysroot %S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKJ %s
+// LINKJ: {{".*ld.*"}} {{.*}} {{"-L.*avr6"}} {{.*}} "-Tdata=0x800200" {{.*}} "-latmega2560" "-mavr6"
+
+// RUN: %clang -### --target=avr -mmcu=attiny10 --sysroot %S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKK %s
+// LINKK: {{".*ld.*"}} {{.*}} {{"-L.*avrtiny"}} {{.*}} "-Tdata=0x800040" {{.*}} "-lattiny10" "-mavrtiny"
+
+// RUN: %clang -### --target=avr -mmcu=atxmega16a4 --sysroot %S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKL %s
+// LINKL: {{".*ld.*"}} {{.*}} {{"-L.*avrxmega2"}} {{.*}} "-Tdata=0x802000" {{.*}} "-latxmega16a4" "-mavrxmega2"
+
+// RUN: %clang -### --target=avr -mmcu=atxmega64b3 --sysroot %S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKM %s
+// LINKM: {{".*ld.*"}} {{.*}} {{"-L.*avrxmega4"}} {{.*}} "-Tdata=0x802000" {{.*}} "-latxmega64b3" "-mavrxmega4"
+
+// RUN: %clang -### --target=avr -mmcu=atxmega128a3u --sysroot %S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKN %s
+// LINKN: {{".*ld.*"}} {{.*}} {{"-L.*avrxmega6"}} {{.*}} "-Tdata=0x802000" {{.*}} "-latxmega128a3u" "-mavrxmega6"
+
+// RUN: %clang -### --target=avr -mmcu=atxmega128a1 --sysroot %S/Inputs/basic_avr_tree %s 2>&1 | FileCheck -check-prefix LINKO %s
+// LINKO: {{".*ld.*"}} {{.*}} {{"-L.*avrxmega7"}} {{.*}} "-Tdata=0x802000" {{.*}} "-latxmega128a1" "-mavrxmega7"
Index: clang/lib/Driver/ToolChains/AVR.cpp
===
--- clang/lib/Driver/ToolChains/AVR.cpp
+++ clang/lib/Driver/ToolChains/AVR.cpp
@@ -32,247 +32,248 @@
   StringRef Name;
   std::string SubPath;
   StringRef Family;
+  unsigned DataAddr;
 } MCUInfo[] = {
-{"at90s1200", "", "avr1"},
-{"attiny11", "", "avr1"},
-{"attiny12", "", "avr1"},
-{"attiny15", "", "avr1"},
-{"attiny28", "", "avr1"},
-{"at90s2313", "tiny-stack", "avr2"},
-{"at90s2323", "tiny-stack", "avr2"},
-{"at90s2333", 

[PATCH] D95523: [OpenCL] Add cl_khr_subgroup_ballot to TableGen BIFs

2021-02-03 Thread Sven van Haastregt via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9caf364d69db: [OpenCL] Add cl_khr_subgroup_ballot to 
TableGen BIFs (authored by svenvh).

Changed prior to commit:
  https://reviews.llvm.org/D95523?vs=319860&id=321036#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95523

Files:
  clang/lib/Sema/OpenCLBuiltins.td
  clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl

Index: clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
===
--- clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -7,7 +7,10 @@
 // RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror -fsyntax-only -cl-std=CLC++ -fdeclare-opencl-builtins -DNO_HEADER
 // RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror -fsyntax-only -cl-std=CLC++ -fdeclare-opencl-builtins -finclude-default-header
 
-// Test the -fdeclare-opencl-builtins option.
+// Test the -fdeclare-opencl-builtins option.  This is not a completeness
+// test, so it should not test for all builtins defined by OpenCL.  Instead
+// this test should cover different functional aspects of the TableGen builtin
+// function machinery.
 
 #pragma OPENCL EXTENSION cl_khr_fp16 : enable
 #if __OPENCL_C_VERSION__ < CL_VERSION_1_2
@@ -30,6 +33,11 @@
 typedef int int4 __attribute__((ext_vector_type(4)));
 typedef uint uint4 __attribute__((ext_vector_type(4)));
 typedef long long2 __attribute__((ext_vector_type(2)));
+
+// Enable extensions that are enabled in opencl-c-base.h.
+#if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 200)
+#define cl_khr_subgroup_ballot 1
+#endif
 #endif
 
 kernel void test_pointers(volatile global void *global_p, global const int4 *a) {
@@ -132,6 +140,14 @@
 #endif
 }
 
+kernel void extended_subgroup(global uint4 *out) {
+  out[0] = get_sub_group_eq_mask();
+#if __OPENCL_C_VERSION__ < CL_VERSION_2_0 && !defined(__OPENCL_CPP_VERSION__)
+  // expected-error@-2{{implicit declaration of function 'get_sub_group_eq_mask' is invalid in OpenCL}}
+  // expected-error@-3{{implicit conversion changes signedness}}
+#endif
+}
+
 kernel void basic_vector_data() {
 #if __OPENCL_C_VERSION__ >= CL_VERSION_2_0
   generic void *generic_p;
Index: clang/lib/Sema/OpenCLBuiltins.td
===
--- clang/lib/Sema/OpenCLBuiltins.td
+++ clang/lib/Sema/OpenCLBuiltins.td
@@ -53,6 +53,7 @@
 // FunctionExtension definitions.
 def FuncExtNone  : FunctionExtension<"">;
 def FuncExtKhrSubgroups  : FunctionExtension<"cl_khr_subgroups">;
+def FuncExtKhrSubgroupBallot : FunctionExtension<"cl_khr_subgroup_ballot">;
 def FuncExtKhrGlobalInt32BaseAtomics : FunctionExtension<"cl_khr_global_int32_base_atomics">;
 def FuncExtKhrGlobalInt32ExtendedAtomics : FunctionExtension<"cl_khr_global_int32_extended_atomics">;
 def FuncExtKhrLocalInt32BaseAtomics  : FunctionExtension<"cl_khr_local_int32_base_atomics">;
@@ -344,6 +345,7 @@
 // GenType definitions for multiple base types (e.g. all floating point types,
 // or all integer types).
 // All types
+def AGenType1  : GenericType<"AGenType1", TLAll, Vec1>;
 def AGenTypeN  : GenericType<"AGenTypeN", TLAll, VecAndScalar>;
 def AGenTypeNNoScalar  : GenericType<"AGenTypeNNoScalar", TLAll, VecNoScalar>;
 // All integer
@@ -1486,6 +1488,44 @@
   }
 }
 
+// OpenCL Extension v3.0 s38 - Extended Subgroup Functions
+
+// Section 38.4.1 - cl_khr_subgroup_extended_types
+// TODO
+
+// Section 38.5.1 - cl_khr_subgroup_non_uniform_vote
+// TODO
+
+// Section 38.6.1 - cl_khr_subgroup_ballot
+let Extension = FuncExtKhrSubgroupBallot in {
+  def : Builtin<"sub_group_non_uniform_broadcast", [AGenTypeN, AGenTypeN, UInt]>;
+  def : Builtin<"sub_group_broadcast_first", [AGenType1, AGenType1]>;
+  def : Builtin<"sub_group_ballot", [VectorType, Int]>;
+  def : Builtin<"sub_group_inverse_ballot", [Int, VectorType], Attr.Const>;
+  def : Builtin<"sub_group_ballot_bit_extract", [Int, VectorType, UInt], Attr.Const>;
+  def : Builtin<"sub_group_ballot_bit_count", [UInt, VectorType], Attr.Const>;
+  def : Builtin<"sub_group_ballot_inclusive_scan", [UInt, VectorType]>;
+  def : Builtin<"sub_group_ballot_exclusive_scan", [UInt, VectorType]>;
+  def : Builtin<"sub_group_ballot_find_lsb", [UInt, VectorType]>;
+  def : Builtin<"sub_group_ballot_find_msb", [UInt, VectorType]>;
+
+  foreach op = ["eq", "ge", "gt", "le", "lt"] in {
+def : Builtin<"get_sub_group_" # op # "_mask", [VectorType], Attr.Const>;
+  }
+}
+
+// Section 38.7.1 - cl_khr_subgroup_non_uniform_arithmetic
+// TODO
+
+// Section 38.8.1 - cl_khr_subgroup_shuffle
+// TODO
+
+// Section 38.9.1 - cl_khr_subgroup_shuffle_relative
+// TODO
+
+// Sect

[clang] 9caf364 - [OpenCL] Add cl_khr_subgroup_ballot to TableGen BIFs

2021-02-03 Thread Sven van Haastregt via cfe-commits

Author: Sven van Haastregt
Date: 2021-02-03T10:23:49Z
New Revision: 9caf364d69db3cd0ce0fba99dba95dbc2b646fbc

URL: 
https://github.com/llvm/llvm-project/commit/9caf364d69db3cd0ce0fba99dba95dbc2b646fbc
DIFF: 
https://github.com/llvm/llvm-project/commit/9caf364d69db3cd0ce0fba99dba95dbc2b646fbc.diff

LOG: [OpenCL] Add cl_khr_subgroup_ballot to TableGen BIFs

Add the builtin functions brought by the cl_khr_subgroup_ballot
extension to `-fdeclare-opencl-builtins`.

Also add placeholder comments for the other Extended Subgroup
Functions from the OpenCL Extension Specification.

Add a comment clarifying the scope of the test.

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

Added: 


Modified: 
clang/lib/Sema/OpenCLBuiltins.td
clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl

Removed: 




diff  --git a/clang/lib/Sema/OpenCLBuiltins.td 
b/clang/lib/Sema/OpenCLBuiltins.td
index fd9e24cfc31e..858939b566a3 100644
--- a/clang/lib/Sema/OpenCLBuiltins.td
+++ b/clang/lib/Sema/OpenCLBuiltins.td
@@ -53,6 +53,7 @@ class FunctionExtension : 
AbstractExtension<_Ext>;
 // FunctionExtension definitions.
 def FuncExtNone  : FunctionExtension<"">;
 def FuncExtKhrSubgroups  : 
FunctionExtension<"cl_khr_subgroups">;
+def FuncExtKhrSubgroupBallot : 
FunctionExtension<"cl_khr_subgroup_ballot">;
 def FuncExtKhrGlobalInt32BaseAtomics : 
FunctionExtension<"cl_khr_global_int32_base_atomics">;
 def FuncExtKhrGlobalInt32ExtendedAtomics : 
FunctionExtension<"cl_khr_global_int32_extended_atomics">;
 def FuncExtKhrLocalInt32BaseAtomics  : 
FunctionExtension<"cl_khr_local_int32_base_atomics">;
@@ -344,6 +345,7 @@ def TLAllInts   : TypeList<[Char, UChar, Short, UShort, 
Int, UInt, Long, ULo
 // GenType definitions for multiple base types (e.g. all floating point types,
 // or all integer types).
 // All types
+def AGenType1  : GenericType<"AGenType1", TLAll, Vec1>;
 def AGenTypeN  : GenericType<"AGenTypeN", TLAll, VecAndScalar>;
 def AGenTypeNNoScalar  : GenericType<"AGenTypeNNoScalar", TLAll, 
VecNoScalar>;
 // All integer
@@ -1486,6 +1488,44 @@ let Extension = FuncExtKhrSubgroups in {
   }
 }
 
+// OpenCL Extension v3.0 s38 - Extended Subgroup Functions
+
+// Section 38.4.1 - cl_khr_subgroup_extended_types
+// TODO
+
+// Section 38.5.1 - cl_khr_subgroup_non_uniform_vote
+// TODO
+
+// Section 38.6.1 - cl_khr_subgroup_ballot
+let Extension = FuncExtKhrSubgroupBallot in {
+  def : Builtin<"sub_group_non_uniform_broadcast", [AGenTypeN, AGenTypeN, 
UInt]>;
+  def : Builtin<"sub_group_broadcast_first", [AGenType1, AGenType1]>;
+  def : Builtin<"sub_group_ballot", [VectorType, Int]>;
+  def : Builtin<"sub_group_inverse_ballot", [Int, VectorType], 
Attr.Const>;
+  def : Builtin<"sub_group_ballot_bit_extract", [Int, VectorType, 
UInt], Attr.Const>;
+  def : Builtin<"sub_group_ballot_bit_count", [UInt, VectorType], 
Attr.Const>;
+  def : Builtin<"sub_group_ballot_inclusive_scan", [UInt, VectorType]>;
+  def : Builtin<"sub_group_ballot_exclusive_scan", [UInt, VectorType]>;
+  def : Builtin<"sub_group_ballot_find_lsb", [UInt, VectorType]>;
+  def : Builtin<"sub_group_ballot_find_msb", [UInt, VectorType]>;
+
+  foreach op = ["eq", "ge", "gt", "le", "lt"] in {
+def : Builtin<"get_sub_group_" # op # "_mask", [VectorType], 
Attr.Const>;
+  }
+}
+
+// Section 38.7.1 - cl_khr_subgroup_non_uniform_arithmetic
+// TODO
+
+// Section 38.8.1 - cl_khr_subgroup_shuffle
+// TODO
+
+// Section 38.9.1 - cl_khr_subgroup_shuffle_relative
+// TODO
+
+// Section 38.10.1 - cl_khr_subgroup_clustered_reduce
+// TODO
+
 //
 // Arm extensions.
 let Extension = ArmIntegerDotProductInt8 in {

diff  --git a/clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl 
b/clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
index 773998a60941..7f9f0cb19f91 100644
--- a/clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ b/clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -7,7 +7,10 @@
 // RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CLC++ -fdeclare-opencl-builtins -DNO_HEADER
 // RUN: %clang_cc1 %s -triple spir -verify -pedantic -Wconversion -Werror 
-fsyntax-only -cl-std=CLC++ -fdeclare-opencl-builtins -finclude-default-header
 
-// Test the -fdeclare-opencl-builtins option.
+// Test the -fdeclare-opencl-builtins option.  This is not a completeness
+// test, so it should not test for all builtins defined by OpenCL.  Instead
+// this test should cover 
diff erent functional aspects of the TableGen builtin
+// function machinery.
 
 #pragma OPENCL EXTENSION cl_khr_fp16 : enable
 #if __OPENCL_C_VERSION__ < CL_VERSION_1_2
@@ -30,6 +33,11 @@ typedef int int2 __attribute__((ext_vector_type(2)));
 typedef int int4 __attribute__((ext_vector_type(4)));
 typedef uint uint4 __attribute__

[clang] e6a62ac - [OpenCL] Add cl_khr_subgroup_non_uniform_vote to TableGen BIFs

2021-02-03 Thread Sven van Haastregt via cfe-commits

Author: Sven van Haastregt
Date: 2021-02-03T10:23:52Z
New Revision: e6a62ac62571229d941dfe81affabdbc47e478eb

URL: 
https://github.com/llvm/llvm-project/commit/e6a62ac62571229d941dfe81affabdbc47e478eb
DIFF: 
https://github.com/llvm/llvm-project/commit/e6a62ac62571229d941dfe81affabdbc47e478eb.diff

LOG: [OpenCL] Add cl_khr_subgroup_non_uniform_vote to TableGen BIFs

Add the builtin functions brought by the
cl_khr_subgroup_non_uniform_vote extension to
`-fdeclare-opencl-builtins`.

Added: 


Modified: 
clang/lib/Sema/OpenCLBuiltins.td

Removed: 




diff  --git a/clang/lib/Sema/OpenCLBuiltins.td 
b/clang/lib/Sema/OpenCLBuiltins.td
index 858939b566a3..cad0f57e8051 100644
--- a/clang/lib/Sema/OpenCLBuiltins.td
+++ b/clang/lib/Sema/OpenCLBuiltins.td
@@ -53,6 +53,7 @@ class FunctionExtension : 
AbstractExtension<_Ext>;
 // FunctionExtension definitions.
 def FuncExtNone  : FunctionExtension<"">;
 def FuncExtKhrSubgroups  : 
FunctionExtension<"cl_khr_subgroups">;
+def FuncExtKhrSubgroupNonUniformVote : 
FunctionExtension<"cl_khr_subgroup_non_uniform_vote">;
 def FuncExtKhrSubgroupBallot : 
FunctionExtension<"cl_khr_subgroup_ballot">;
 def FuncExtKhrGlobalInt32BaseAtomics : 
FunctionExtension<"cl_khr_global_int32_base_atomics">;
 def FuncExtKhrGlobalInt32ExtendedAtomics : 
FunctionExtension<"cl_khr_global_int32_extended_atomics">;
@@ -1494,7 +1495,12 @@ let Extension = FuncExtKhrSubgroups in {
 // TODO
 
 // Section 38.5.1 - cl_khr_subgroup_non_uniform_vote
-// TODO
+let Extension = FuncExtKhrSubgroupNonUniformVote in {
+  def : Builtin<"sub_group_elect", [Int]>;
+  def : Builtin<"sub_group_non_uniform_all", [Int, Int]>;
+  def : Builtin<"sub_group_non_uniform_any", [Int, Int]>;
+  def : Builtin<"sub_group_non_uniform_all_equal", [Int, AGenType1]>;
+}
 
 // Section 38.6.1 - cl_khr_subgroup_ballot
 let Extension = FuncExtKhrSubgroupBallot in {



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


[PATCH] D95872: [clang][Arm] Fix handling of -Wa,-march=

2021-02-03 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett updated this revision to Diff 321037.
DavidSpickett added a comment.

- Added split -Wa test for -mthumb
- Use `--check-prefix`/`--check-prefixes`
- Comment at top of march/mcpu file to explain choice of test CPUs


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95872

Files:
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Arch/ARM.cpp
  clang/test/Driver/arm-target-as-march-mcpu.s
  clang/test/Driver/arm-target-as-mthumb.s

Index: clang/test/Driver/arm-target-as-mthumb.s
===
--- clang/test/Driver/arm-target-as-mthumb.s
+++ clang/test/Driver/arm-target-as-mthumb.s
@@ -5,12 +5,18 @@
 // RUN: %clang -target armv7a-linux-gnueabi -### -c -mthumb %s 2>&1 | \
 // RUN: FileCheck -check-prefix=TRIPLE-ARM %s
 // RUN: %clang -target armv7a-linux-gnueabi -### -c -Wa,-mthumb \
-// RUN: %S/Inputs/wildcard1.c  2>&1 | FileCheck -check-prefix=TRIPLE-ARM %s
+// RUN: %S/Inputs/wildcard1.c 2>&1 | FileCheck -check-prefix=TRIPLE-ARM %s
+// RUN: %clang -target armv7a-linux-gnueabi -### -c -Wa,-mcpu=cortex-a8,-mthumb \
+// RUN: %S/Inputs/wildcard1.c 2>&1 | FileCheck -check-prefix=TRIPLE-ARM %s
 
 // TRIPLE-ARM: "-triple" "armv7-unknown-linux-gnueabi"
 
 // RUN: %clang -target armv7a-linux-gnueabi -### -c -Wa,-mthumb %s 2>&1 | \
 // RUN: FileCheck -check-prefix=TRIPLE-THUMB %s
+// RUN: %clang -target armv7a-linux-gnueabi -### -c -Wa,-mcpu=cortex-a8,-mthumb %s 2>&1 | \
+// RUN: FileCheck -check-prefix=TRIPLE-THUMB %s
+// RUN: %clang -target armv7a-linux-gnueabi -### -c -Wa,-mcpu=cortex-a8 -Wa,-mthumb %s 2>&1 | \
+// RUN: FileCheck -check-prefix=TRIPLE-THUMB %s
 // RUN: %clang -target armv7a-linux-gnueabi -### -c -Xassembler -mthumb %s \
 // RUN: 2>&1 | FileCheck -check-prefix=TRIPLE-THUMB %s
 
Index: clang/test/Driver/arm-target-as-march-mcpu.s
===
--- /dev/null
+++ clang/test/Driver/arm-target-as-march-mcpu.s
@@ -0,0 +1,104 @@
+/// These tests make sure that options passed to the assembler
+/// via -Wa or -Xassembler are applied correctly to assembler inputs.
+/// Also we check that the same priority rules apply to compiler and
+/// assembler options.
+///
+/// Note that the cortex-a8 is armv7-a, the cortex-a32 is armv8-a
+/// and clang's default Arm architecture is armv4t.
+
+/// Sanity check how the options behave when passed to the compiler
+// RUN: %clang -target arm-linux-gnueabi -### -c -march=armv7-a %s 2>&1 | \
+// RUN: FileCheck --check-prefix=TRIPLE-ARMV7 %s
+// RUN: %clang -target arm-linux-gnueabi -### -c -march=armv7-a+crc %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=TRIPLE-ARMV7,EXT-CRC %s
+
+/// -Wa/-Xassembler doesn't apply to non assembly files
+// RUN: %clang -target arm-linux-gnueabi -### -c -Wa,-march=armv7-a \
+// RUN: %S/Inputs/wildcard1.c 2>&1 | FileCheck --check-prefix=TRIPLE-ARMV4 %s
+// RUN: %clang -target arm-linux-gnueabi -### -c -Xassembler -march=armv7-a \
+// RUN: %S/Inputs/wildcard1.c 2>&1 | FileCheck --check-prefix=TRIPLE-ARMV4 %s
+
+/// -Wa/-Xassembler does apply to assembler input
+// RUN: %clang -target arm-linux-gnueabi -### -c -Wa,-march=armv7-a %s 2>&1 | \
+// RUN: FileCheck --check-prefix=TRIPLE-ARMV7 %s
+// RUN: %clang -target arm-linux-gnueabi -### -c -Wa,-march=armv7-a+crc %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=TRIPLE-ARMV7,EXT-CRC %s
+// RUN: %clang -target arm-linux-gnueabi -### -c -Xassembler -march=armv7-a %s 2>&1 | \
+// RUN: FileCheck --check-prefix=TRIPLE-ARMV7 %s
+// RUN: %clang -target arm-linux-gnueabi -### -c -Xassembler -march=armv7-a+crc %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=TRIPLE-ARMV7,EXT-CRC %s
+
+/// Check that arch name is still canonicalised
+// RUN: %clang -target arm-linux-gnueabi -### -c -Wa,-march=armv7a %s 2>&1 | \
+// RUN: FileCheck --check-prefix=TRIPLE-ARMV7 %s
+// RUN: %clang -target arm-linux-gnueabi -### -c -Xassembler -march=armv7 %s 2>&1 | \
+// RUN: FileCheck --check-prefix=TRIPLE-ARMV7 %s
+
+/// march to compiler and assembler, we choose the one suited to the input file type
+// RUN: %clang -target arm-linux-gnueabi -### -c -march=armv8-a -Wa,-march=armv7a %s 2>&1 | \
+// RUN: FileCheck --check-prefix=TRIPLE-ARMV7 %s
+// RUN: %clang -target arm-linux-gnueabi -### -c -march=armv7-a -Wa,-march=armv8-a \
+// RUN: %S/Inputs/wildcard1.c 2>&1 | FileCheck --check-prefix=TRIPLE-ARMV7 %s
+
+/// mcpu to compiler and march to assembler, we use the assembler's architecture for assembly files.
+/// We use the target CPU for both.
+// RUN: %clang -target arm-linux-gnueabi -### -c -mcpu=cortex-a8 -Wa,-march=armv8a %s 2>&1 | \
+// RUN: FileCheck --check-prefixes=TRIPLE-ARMV8,CPU-A8 %s
+// RUN: %clang -target arm-linux-gnueabi -### -c -mcpu=cortex-a8 -Wa,-march=armv8-a \
+// RUN: %S/Inputs/wildcard1.c 2>&1 | FileCheck --check-prefixes=TRIPLE-ARMV7,CPU-A8 %s
+
+/// march to compiler and mcpu to assembler, we use 

[PATCH] D95852: [clangd] Report xref for base methods.

2021-02-03 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 updated this revision to Diff 321038.
usaxena95 added a comment.

Addressed comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95852

Files:
  clang-tools-extra/clangd/XRefs.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
@@ -1889,6 +1889,30 @@
   checkFindRefs(Test, /*UseIndex=*/true);
 }
 
+TEST(FindReferences, RefsToBaseMethod) {
+  llvm::StringRef Test =
+  R"cpp(
+class BaseBase {
+public:
+  virtual void [[func]]();
+};
+class Base : public BaseBase {
+public:
+  void [[func]]() override;
+};
+class Derived : public Base {
+public:
+  void $decl[[fu^nc]]() override;
+};
+void test(BaseBase* BB, Base* B, Derived* D) {
+  // refs to overridden methods in complete type hierarchy are reported.
+  BB->[[func]]();
+  B->[[func]]();
+  D->[[func]]();
+})cpp";
+  checkFindRefs(Test, /*UseIndex=*/true);
+}
+
 TEST(FindReferences, MainFileReferencesOnly) {
   llvm::StringRef Test =
   R"cpp(
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -1281,6 +1281,21 @@
   return findImplementors(std::move(IDs), QueryKind, Index, *MainFilePath);
 }
 
+namespace {
+// Recursively finds all the overridden methods of `CMD` in complete type
+// hierarchy.
+void getOverriddenMethods(const CXXMethodDecl *CMD,
+  llvm::DenseSet &OverriddenMethods) {
+  if (!CMD)
+return;
+  for (const CXXMethodDecl *Base : CMD->overridden_methods()) {
+if (auto ID = getSymbolID(Base))
+  OverriddenMethods.insert(ID);
+getOverriddenMethods(Base, OverriddenMethods);
+  }
+}
+} // namespace
+
 ReferencesResult findReferences(ParsedAST &AST, Position Pos, uint32_t Limit,
 const SymbolIndex *Index) {
   if (!Limit)
@@ -1300,7 +1315,7 @@
 return {};
   }
 
-  llvm::DenseSet IDs;
+  llvm::DenseSet IDs, OverriddenMethods;
 
   const auto *IdentifierAtCursor =
   syntax::spelledIdentifierTouching(*CurLoc, AST.getTokens());
@@ -1343,13 +1358,16 @@
 if (Index) {
   OverriddenBy.Predicate = RelationKind::OverriddenBy;
   for (const NamedDecl *ND : Decls) {
-// Special case: Inlcude declaration of overridding methods.
+// Special case: For virtual methods, report decl/def of overrides and
+// references to all overridden methods in complete type hierarchy.
 if (const auto *CMD = llvm::dyn_cast(ND)) {
   if (CMD->isVirtual())
 if (IdentifierAtCursor && SM.getSpellingLoc(CMD->getLocation()) ==
-  IdentifierAtCursor->location())
+  IdentifierAtCursor->location()) {
   if (auto ID = getSymbolID(CMD))
 OverriddenBy.Subjects.insert(ID);
+  getOverriddenMethods(CMD, OverriddenMethods);
+}
 }
   }
 }
@@ -1415,7 +1433,8 @@
 }
   }
   // Now query the index for references from other files.
-  auto QueryIndex = [&](llvm::DenseSet IDs, bool AllowAttributes) {
+  auto QueryIndex = [&](llvm::DenseSet IDs, bool AllowAttributes,
+bool AllowMainFileSymbols) {
 RefsRequest Req;
 Req.IDs = std::move(IDs);
 Req.Limit = Limit;
@@ -1427,7 +1446,8 @@
 return;
   auto LSPLoc = toLSPLocation(R.Location, *MainFilePath);
   // Avoid indexed results for the main file - the AST is authoritative.
-  if (!LSPLoc || LSPLoc->uri.file() == *MainFilePath)
+  if (!LSPLoc ||
+  (!AllowMainFileSymbols && LSPLoc->uri.file() == *MainFilePath))
 return;
   ReferencesResult::Reference Result;
   Result.Loc = std::move(*LSPLoc);
@@ -1442,12 +1462,17 @@
   Results.References.push_back(std::move(Result));
 });
   };
-  QueryIndex(std::move(IDs), /*AllowAttributes=*/true);
+  QueryIndex(std::move(IDs), /*AllowAttributes=*/true,
+ /*AllowMainFileSymbols=*/false);
+  // For a virtual method: Occurrences of BaseMethod should be treated as refs
+  // and not as decl/def. Allow symbols from main file since AST does not report
+  // these.
+  QueryIndex(std::move(OverriddenMethods), /*AllowAttributes=*/false,
+ /*AllowMainFileSymbols=*/true);
   if (Results.References.size() > Limit) {
 Results.HasMore = true;
 Results.References.resize(Limit);
   }
-  // FIXME: Report refs of base methods.
   return Results;
 }
 
___
cfe-commi

[PATCH] D95872: [clang][Arm] Fix handling of -Wa,-march=

2021-02-03 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett marked 6 inline comments as done.
DavidSpickett added inline comments.



Comment at: clang/test/Driver/arm-target-as-march-mcpu.s:42
+/// We use the target CPU for both.
+// RUN: %clang -target arm-linux-gnueabi -### -c -mcpu=cortex-a8 
-Wa,-march=armv8a %s 2>&1 | \
+// RUN: FileCheck -check-prefix=TRIPLE-ARMV8 --check-prefix=CPU-A8 %s

nickdesaulniers wrote:
> nickdesaulniers wrote:
> > Below you have a comment `(cortex-a32 is armv8a)`.  That is very helpful 
> > for me.  I assume `cortex-a8` is armv7a?
> And if so, would you mind adding a similar comment here?
Exactly, I've added a comment up top to explain the logic in one place.



Comment at: clang/test/Driver/arm-target-as-march-mcpu.s:82
+/// Last mcpu to compiler wins
+// RUN: %clang -target arm-linux-gnueabi -### -c -mcpu=cortex-a32 
-mcpu=cortex-a8 %s 2>&1 | \
+// RUN: FileCheck -check-prefix=TRIPLE-ARMV7 -check-prefix=CPU-A8 %s

nickdesaulniers wrote:
> add a `-mcpu=foo,bar` test for `-mcpu`? (Comma separated)
mcpu and march don't let you use multiple values:
```
error: the clang compiler does not support '-march=armv8-a,armv7-a'
error: unsupported argument 'armv7-a' to option 'Wa,
```
(the latter it thinks that its another arg like `-Wa,armv7-a`)

Pretty sure that's tested elsewhere or if it isn't, this isn't the place for it 
at least.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95872

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


[PATCH] D95860: [clang][Frontend] Fix a crash in DiagnosticRenderer.

2021-02-03 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 321039.
balazske added a comment.

Existing test moved to Frontend, added new test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95860

Files:
  clang/lib/Frontend/DiagnosticRenderer.cpp
  clang/test/Analysis/copypaste/Inputs/clone-end-in-other-file.inc
  clang/test/Analysis/copypaste/clone-end-in-other-file.cpp
  clang/test/Frontend/crash-diagnostic-renderer.cpp


Index: clang/test/Frontend/crash-diagnostic-renderer.cpp
===
--- /dev/null
+++ clang/test/Frontend/crash-diagnostic-renderer.cpp
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -verify %s
+
+// This case reproduces a problem that is shown here:
+// https://bugs.llvm.org/show_bug.cgi?id=46540
+// No assertion should happen during printing of diagnostic messages.
+
+// expected-error@13{{'b' does not refer to a type name in pseudo-destructor 
expression; expected the name of type 'volatile long'}}
+// expected-error@13{{expected ')'}}
+// expected-note@13{{to match this '('}}
+// expected-error@13{{reference to pseudo-destructor must be called; did you 
mean to call it with no arguments?}}
+// expected-error@13{{cannot initialize a variable of type 'volatile long' 
with an rvalue of type 'void'}}
+// expected-error@13{{expected ';' after top level declarator}}
+volatile long a ( a .~b
Index: clang/test/Analysis/copypaste/clone-end-in-other-file.cpp
===
--- /dev/null
+++ clang/test/Analysis/copypaste/clone-end-in-other-file.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.clone.CloneChecker 
-analyzer-config alpha.clone.CloneChecker:MinimumCloneComplexity=0 -verify %s
+
+// This test should verify that there is no crash if the detected clone range
+// starts in a file and ends in a different file.
+
+void f1(int i) {
+#define X\
+  while (true) { \
+  }
+  if (i == 10) // expected-warning{{Duplicate code detected}}
+#include "Inputs/clone-end-in-other-file.inc"
+if (i == 10) // expected-note{{Similar code here}}
+#include "Inputs/clone-end-in-other-file.inc"
+}
Index: clang/test/Analysis/copypaste/Inputs/clone-end-in-other-file.inc
===
--- /dev/null
+++ clang/test/Analysis/copypaste/Inputs/clone-end-in-other-file.inc
@@ -0,0 +1 @@
+X
Index: clang/lib/Frontend/DiagnosticRenderer.cpp
===
--- clang/lib/Frontend/DiagnosticRenderer.cpp
+++ clang/lib/Frontend/DiagnosticRenderer.cpp
@@ -394,6 +394,9 @@
   }
 }
 
+if (Begin.isInvalid() || End.isInvalid() || BeginFileID != EndFileID)
+  continue;
+
 // Do the backtracking.
 SmallVector CommonArgExpansions;
 computeCommonMacroArgExpansionFileIDs(Begin, End, SM, CommonArgExpansions);


Index: clang/test/Frontend/crash-diagnostic-renderer.cpp
===
--- /dev/null
+++ clang/test/Frontend/crash-diagnostic-renderer.cpp
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -verify %s
+
+// This case reproduces a problem that is shown here:
+// https://bugs.llvm.org/show_bug.cgi?id=46540
+// No assertion should happen during printing of diagnostic messages.
+
+// expected-error@13{{'b' does not refer to a type name in pseudo-destructor expression; expected the name of type 'volatile long'}}
+// expected-error@13{{expected ')'}}
+// expected-note@13{{to match this '('}}
+// expected-error@13{{reference to pseudo-destructor must be called; did you mean to call it with no arguments?}}
+// expected-error@13{{cannot initialize a variable of type 'volatile long' with an rvalue of type 'void'}}
+// expected-error@13{{expected ';' after top level declarator}}
+volatile long a ( a .~b
Index: clang/test/Analysis/copypaste/clone-end-in-other-file.cpp
===
--- /dev/null
+++ clang/test/Analysis/copypaste/clone-end-in-other-file.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.clone.CloneChecker -analyzer-config alpha.clone.CloneChecker:MinimumCloneComplexity=0 -verify %s
+
+// This test should verify that there is no crash if the detected clone range
+// starts in a file and ends in a different file.
+
+void f1(int i) {
+#define X\
+  while (true) { \
+  }
+  if (i == 10) // expected-warning{{Duplicate code detected}}
+#include "Inputs/clone-end-in-other-file.inc"
+if (i == 10) // expected-note{{Similar code here}}
+#include "Inputs/clone-end-in-other-file.inc"
+}
Index: clang/test/Analysis/copypaste/Inputs/clone-end-in-other-file.inc
===
--- /dev/null
+++ clang/test/Analysis/copypaste/Inputs/clone-end-in-other-file.inc
@@ -0,0 +1 @@
+X
Index: clang/lib/Frontend/DiagnosticRenderer.cpp

[PATCH] D95852: [clangd] Report xref for base methods.

2021-02-03 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

Thanks!




Comment at: clang-tools-extra/clangd/XRefs.cpp:1294
+  OverriddenMethods.insert(ID);
+getOverriddenMethods(Base, OverriddenMethods);
+  }

The recursive will be infinite if we have a cycle, but I guess clang will never 
generate a broken AST like that. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95852

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


[PATCH] D95860: [clang][Frontend] Fix a crash in DiagnosticRenderer.

2021-02-03 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 321041.
balazske added a comment.

Reformatting test file.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95860

Files:
  clang/lib/Frontend/DiagnosticRenderer.cpp
  clang/test/Analysis/copypaste/Inputs/clone-end-in-other-file.inc
  clang/test/Analysis/copypaste/clone-end-in-other-file.cpp
  clang/test/Frontend/crash-diagnostic-renderer.cpp


Index: clang/test/Frontend/crash-diagnostic-renderer.cpp
===
--- /dev/null
+++ clang/test/Frontend/crash-diagnostic-renderer.cpp
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -verify %s
+
+// This case reproduces a problem that is shown here:
+// https://bugs.llvm.org/show_bug.cgi?id=46540
+// No assertion should happen during printing of diagnostic messages.
+
+// expected-error@13{{'b' does not refer to a type name in pseudo-destructor 
expression; expected the name of type 'volatile long'}}
+// expected-error@13{{expected ')'}}
+// expected-note@13{{to match this '('}}
+// expected-error@13{{reference to pseudo-destructor must be called; did you 
mean to call it with no arguments?}}
+// expected-error@13{{cannot initialize a variable of type 'volatile long' 
with an rvalue of type 'void'}}
+// expected-error@13{{expected ';' after top level declarator}}
+volatile long a ( a .~b
Index: clang/test/Analysis/copypaste/clone-end-in-other-file.cpp
===
--- /dev/null
+++ clang/test/Analysis/copypaste/clone-end-in-other-file.cpp
@@ -0,0 +1,13 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.clone.CloneChecker 
-analyzer-config alpha.clone.CloneChecker:MinimumCloneComplexity=0 -verify %s
+
+// This test should verify that there is no crash if the detected clone range
+// starts in a file and ends in a different file.
+
+#define X while (true) {}
+
+void f1(int i) {
+  if (i == 10) // expected-warning{{Duplicate code detected}}
+#include "Inputs/clone-end-in-other-file.inc"
+  if (i == 10) // expected-note{{Similar code here}}
+#include "Inputs/clone-end-in-other-file.inc"
+}
Index: clang/test/Analysis/copypaste/Inputs/clone-end-in-other-file.inc
===
--- /dev/null
+++ clang/test/Analysis/copypaste/Inputs/clone-end-in-other-file.inc
@@ -0,0 +1 @@
+X
Index: clang/lib/Frontend/DiagnosticRenderer.cpp
===
--- clang/lib/Frontend/DiagnosticRenderer.cpp
+++ clang/lib/Frontend/DiagnosticRenderer.cpp
@@ -394,6 +394,9 @@
   }
 }
 
+if (Begin.isInvalid() || End.isInvalid() || BeginFileID != EndFileID)
+  continue;
+
 // Do the backtracking.
 SmallVector CommonArgExpansions;
 computeCommonMacroArgExpansionFileIDs(Begin, End, SM, CommonArgExpansions);


Index: clang/test/Frontend/crash-diagnostic-renderer.cpp
===
--- /dev/null
+++ clang/test/Frontend/crash-diagnostic-renderer.cpp
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -verify %s
+
+// This case reproduces a problem that is shown here:
+// https://bugs.llvm.org/show_bug.cgi?id=46540
+// No assertion should happen during printing of diagnostic messages.
+
+// expected-error@13{{'b' does not refer to a type name in pseudo-destructor expression; expected the name of type 'volatile long'}}
+// expected-error@13{{expected ')'}}
+// expected-note@13{{to match this '('}}
+// expected-error@13{{reference to pseudo-destructor must be called; did you mean to call it with no arguments?}}
+// expected-error@13{{cannot initialize a variable of type 'volatile long' with an rvalue of type 'void'}}
+// expected-error@13{{expected ';' after top level declarator}}
+volatile long a ( a .~b
Index: clang/test/Analysis/copypaste/clone-end-in-other-file.cpp
===
--- /dev/null
+++ clang/test/Analysis/copypaste/clone-end-in-other-file.cpp
@@ -0,0 +1,13 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.clone.CloneChecker -analyzer-config alpha.clone.CloneChecker:MinimumCloneComplexity=0 -verify %s
+
+// This test should verify that there is no crash if the detected clone range
+// starts in a file and ends in a different file.
+
+#define X while (true) {}
+
+void f1(int i) {
+  if (i == 10) // expected-warning{{Duplicate code detected}}
+#include "Inputs/clone-end-in-other-file.inc"
+  if (i == 10) // expected-note{{Similar code here}}
+#include "Inputs/clone-end-in-other-file.inc"
+}
Index: clang/test/Analysis/copypaste/Inputs/clone-end-in-other-file.inc
===
--- /dev/null
+++ clang/test/Analysis/copypaste/Inputs/clone-end-in-other-file.inc
@@ -0,0 +1 @@
+X
Index: clang/lib/Frontend/DiagnosticRenderer.cpp
===
--- c

[PATCH] D95608: [OpenCL][PR48896] Fix address space in binding of initializer lists to references

2021-02-03 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In D95608#2537316 , @rjmccall wrote:

> Thanks, LGTM.
>
> I think idiomatically we normally just use `(void)` instead of spelling it 
> out with `static_cast`, since there's only one possible meaning for a cast to 
> `void`.  I don't care deeply about it; if you make that change, feel free to 
> make it as part of committing.

Thanks, sure I will stick to the existing practices and update this. Thanks!


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

https://reviews.llvm.org/D95608

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


[clang-tools-extra] 54afcad - [clangd] Report xref for base methods.

2021-02-03 Thread Utkarsh Saxena via cfe-commits

Author: Utkarsh Saxena
Date: 2021-02-03T12:07:43+01:00
New Revision: 54afcade3bbcf4a085c8a8c3c22429921420e54d

URL: 
https://github.com/llvm/llvm-project/commit/54afcade3bbcf4a085c8a8c3c22429921420e54d
DIFF: 
https://github.com/llvm/llvm-project/commit/54afcade3bbcf4a085c8a8c3c22429921420e54d.diff

LOG: [clangd] Report xref for base methods.

See: https://github.com/clangd/clangd/issues/668

```
struct A { virtual void foo() = 0; };
struct B : A { void foo() override; };
```

Find refs on `B::foo()` will show:
- decls of `A::foo()` (new)
- decls of `B::foo()`
- refs to `A::foo()` (new)
- refs to `B::foo()`.

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

Added: 


Modified: 
clang-tools-extra/clangd/XRefs.cpp
clang-tools-extra/clangd/unittests/XRefsTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/XRefs.cpp 
b/clang-tools-extra/clangd/XRefs.cpp
index b6a0be4a0a0a..c4a73ebad3e8 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -1281,6 +1281,21 @@ std::vector findImplementations(ParsedAST 
&AST, Position Pos,
   return findImplementors(std::move(IDs), QueryKind, Index, *MainFilePath);
 }
 
+namespace {
+// Recursively finds all the overridden methods of `CMD` in complete type
+// hierarchy.
+void getOverriddenMethods(const CXXMethodDecl *CMD,
+  llvm::DenseSet &OverriddenMethods) {
+  if (!CMD)
+return;
+  for (const CXXMethodDecl *Base : CMD->overridden_methods()) {
+if (auto ID = getSymbolID(Base))
+  OverriddenMethods.insert(ID);
+getOverriddenMethods(Base, OverriddenMethods);
+  }
+}
+} // namespace
+
 ReferencesResult findReferences(ParsedAST &AST, Position Pos, uint32_t Limit,
 const SymbolIndex *Index) {
   if (!Limit)
@@ -1300,7 +1315,7 @@ ReferencesResult findReferences(ParsedAST &AST, Position 
Pos, uint32_t Limit,
 return {};
   }
 
-  llvm::DenseSet IDs;
+  llvm::DenseSet IDs, OverriddenMethods;
 
   const auto *IdentifierAtCursor =
   syntax::spelledIdentifierTouching(*CurLoc, AST.getTokens());
@@ -1343,13 +1358,16 @@ ReferencesResult findReferences(ParsedAST &AST, 
Position Pos, uint32_t Limit,
 if (Index) {
   OverriddenBy.Predicate = RelationKind::OverriddenBy;
   for (const NamedDecl *ND : Decls) {
-// Special case: Inlcude declaration of overridding methods.
+// Special case: For virtual methods, report decl/def of overrides and
+// references to all overridden methods in complete type hierarchy.
 if (const auto *CMD = llvm::dyn_cast(ND)) {
   if (CMD->isVirtual())
 if (IdentifierAtCursor && SM.getSpellingLoc(CMD->getLocation()) ==
-  IdentifierAtCursor->location())
+  IdentifierAtCursor->location()) {
   if (auto ID = getSymbolID(CMD))
 OverriddenBy.Subjects.insert(ID);
+  getOverriddenMethods(CMD, OverriddenMethods);
+}
 }
   }
 }
@@ -1415,7 +1433,8 @@ ReferencesResult findReferences(ParsedAST &AST, Position 
Pos, uint32_t Limit,
 }
   }
   // Now query the index for references from other files.
-  auto QueryIndex = [&](llvm::DenseSet IDs, bool AllowAttributes) {
+  auto QueryIndex = [&](llvm::DenseSet IDs, bool AllowAttributes,
+bool AllowMainFileSymbols) {
 RefsRequest Req;
 Req.IDs = std::move(IDs);
 Req.Limit = Limit;
@@ -1427,7 +1446,8 @@ ReferencesResult findReferences(ParsedAST &AST, Position 
Pos, uint32_t Limit,
 return;
   auto LSPLoc = toLSPLocation(R.Location, *MainFilePath);
   // Avoid indexed results for the main file - the AST is authoritative.
-  if (!LSPLoc || LSPLoc->uri.file() == *MainFilePath)
+  if (!LSPLoc ||
+  (!AllowMainFileSymbols && LSPLoc->uri.file() == *MainFilePath))
 return;
   ReferencesResult::Reference Result;
   Result.Loc = std::move(*LSPLoc);
@@ -1442,12 +1462,17 @@ ReferencesResult findReferences(ParsedAST &AST, 
Position Pos, uint32_t Limit,
   Results.References.push_back(std::move(Result));
 });
   };
-  QueryIndex(std::move(IDs), /*AllowAttributes=*/true);
+  QueryIndex(std::move(IDs), /*AllowAttributes=*/true,
+ /*AllowMainFileSymbols=*/false);
+  // For a virtual method: Occurrences of BaseMethod should be treated as refs
+  // and not as decl/def. Allow symbols from main file since AST does not 
report
+  // these.
+  QueryIndex(std::move(OverriddenMethods), /*AllowAttributes=*/false,
+ /*AllowMainFileSymbols=*/true);
   if (Results.References.size() > Limit) {
 Results.HasMore = true;
 Results.References.resize(Limit);
   }
-  // FIXME: Report refs of base methods.
   return Results;
 }
 

diff  --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp 
b/clang-tools-extr

[PATCH] D95852: [clangd] Report xref for base methods.

2021-02-03 Thread Utkarsh Saxena via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG54afcade3bbc: [clangd] Report xref for base methods. 
(authored by usaxena95).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95852

Files:
  clang-tools-extra/clangd/XRefs.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
@@ -1889,6 +1889,30 @@
   checkFindRefs(Test, /*UseIndex=*/true);
 }
 
+TEST(FindReferences, RefsToBaseMethod) {
+  llvm::StringRef Test =
+  R"cpp(
+class BaseBase {
+public:
+  virtual void [[func]]();
+};
+class Base : public BaseBase {
+public:
+  void [[func]]() override;
+};
+class Derived : public Base {
+public:
+  void $decl[[fu^nc]]() override;
+};
+void test(BaseBase* BB, Base* B, Derived* D) {
+  // refs to overridden methods in complete type hierarchy are reported.
+  BB->[[func]]();
+  B->[[func]]();
+  D->[[func]]();
+})cpp";
+  checkFindRefs(Test, /*UseIndex=*/true);
+}
+
 TEST(FindReferences, MainFileReferencesOnly) {
   llvm::StringRef Test =
   R"cpp(
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -1281,6 +1281,21 @@
   return findImplementors(std::move(IDs), QueryKind, Index, *MainFilePath);
 }
 
+namespace {
+// Recursively finds all the overridden methods of `CMD` in complete type
+// hierarchy.
+void getOverriddenMethods(const CXXMethodDecl *CMD,
+  llvm::DenseSet &OverriddenMethods) {
+  if (!CMD)
+return;
+  for (const CXXMethodDecl *Base : CMD->overridden_methods()) {
+if (auto ID = getSymbolID(Base))
+  OverriddenMethods.insert(ID);
+getOverriddenMethods(Base, OverriddenMethods);
+  }
+}
+} // namespace
+
 ReferencesResult findReferences(ParsedAST &AST, Position Pos, uint32_t Limit,
 const SymbolIndex *Index) {
   if (!Limit)
@@ -1300,7 +1315,7 @@
 return {};
   }
 
-  llvm::DenseSet IDs;
+  llvm::DenseSet IDs, OverriddenMethods;
 
   const auto *IdentifierAtCursor =
   syntax::spelledIdentifierTouching(*CurLoc, AST.getTokens());
@@ -1343,13 +1358,16 @@
 if (Index) {
   OverriddenBy.Predicate = RelationKind::OverriddenBy;
   for (const NamedDecl *ND : Decls) {
-// Special case: Inlcude declaration of overridding methods.
+// Special case: For virtual methods, report decl/def of overrides and
+// references to all overridden methods in complete type hierarchy.
 if (const auto *CMD = llvm::dyn_cast(ND)) {
   if (CMD->isVirtual())
 if (IdentifierAtCursor && SM.getSpellingLoc(CMD->getLocation()) ==
-  IdentifierAtCursor->location())
+  IdentifierAtCursor->location()) {
   if (auto ID = getSymbolID(CMD))
 OverriddenBy.Subjects.insert(ID);
+  getOverriddenMethods(CMD, OverriddenMethods);
+}
 }
   }
 }
@@ -1415,7 +1433,8 @@
 }
   }
   // Now query the index for references from other files.
-  auto QueryIndex = [&](llvm::DenseSet IDs, bool AllowAttributes) {
+  auto QueryIndex = [&](llvm::DenseSet IDs, bool AllowAttributes,
+bool AllowMainFileSymbols) {
 RefsRequest Req;
 Req.IDs = std::move(IDs);
 Req.Limit = Limit;
@@ -1427,7 +1446,8 @@
 return;
   auto LSPLoc = toLSPLocation(R.Location, *MainFilePath);
   // Avoid indexed results for the main file - the AST is authoritative.
-  if (!LSPLoc || LSPLoc->uri.file() == *MainFilePath)
+  if (!LSPLoc ||
+  (!AllowMainFileSymbols && LSPLoc->uri.file() == *MainFilePath))
 return;
   ReferencesResult::Reference Result;
   Result.Loc = std::move(*LSPLoc);
@@ -1442,12 +1462,17 @@
   Results.References.push_back(std::move(Result));
 });
   };
-  QueryIndex(std::move(IDs), /*AllowAttributes=*/true);
+  QueryIndex(std::move(IDs), /*AllowAttributes=*/true,
+ /*AllowMainFileSymbols=*/false);
+  // For a virtual method: Occurrences of BaseMethod should be treated as refs
+  // and not as decl/def. Allow symbols from main file since AST does not report
+  // these.
+  QueryIndex(std::move(OverriddenMethods), /*AllowAttributes=*/false,
+ /*AllowMainFileSymbols=*/true);
   if (Results.References.size() > Limit) {
 Results.HasMore = true;
 Results.References.resize(Limit

[PATCH] D95860: [clang][Frontend] Fix a crash in DiagnosticRenderer.

2021-02-03 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D95860#2538802 , @balazske wrote:

> Existing test moved to Frontend, added new test.

Awesome, thanks!

On the functional side of things, I'm not sure if we should skip or not.
But simply skipping those seems like you are treating the symptom, not the 
cause.
Could you please give a rationale why can't we implement the subsequent logic 
in a way that it does not require `BeginFileID == EndFileID` to hold?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95860

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


[PATCH] D95860: [clang][Frontend] Fix a crash in DiagnosticRenderer.

2021-02-03 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

I realized that the added test cases show different problems: One is when one 
of `Begin` or `End` is invalid, other if the FileID's are different. Probably 
we can find a better solution for the second problem. So the patch needs to be 
splitted and the case with the **crash-diagnostic-renderer.cpp** goes into the 
first part.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95860

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


[PATCH] D95935: [clang][CodeComplete] Fix crash on ParenListExprs

2021-02-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: hokein.
kadircet requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D95935

Files:
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/CodeCompletion/function-overloads.cpp
  clang/unittests/Sema/CodeCompleteTest.cpp


Index: clang/unittests/Sema/CodeCompleteTest.cpp
===
--- clang/unittests/Sema/CodeCompleteTest.cpp
+++ clang/unittests/Sema/CodeCompleteTest.cpp
@@ -488,6 +488,7 @@
 auto y = new decltype(&1)(^);
 // GNU decimal type extension is not supported in clang.
 auto z = new _Decimal128(^);
+void foo() { (void)(foo)(^); }
   )cpp";
   EXPECT_THAT(collectPreferredTypes(Code), Each("NULL TYPE"));
 }
Index: clang/test/CodeCompletion/function-overloads.cpp
===
--- clang/test/CodeCompletion/function-overloads.cpp
+++ clang/test/CodeCompletion/function-overloads.cpp
@@ -21,6 +21,8 @@
 void test_adl() {
   NS::X x;
   g(x, x);
+  (void)(f)(1, 2, 3);
+  (void)(test, test, test, f)(1, 2, 3);
 }
 
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:10:9 %s -o - | 
FileCheck -check-prefix=CHECK-CC1 %s
@@ -31,6 +33,10 @@
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:10:21 %s -o - | 
FileCheck -check-prefix=CHECK-CC4 %s
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:23:7 %s -o - | \
 // RUN:FileCheck -check-prefix=CHECK-CC5 %s
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:24:13 %s -o - | \
+// RUN:FileCheck -check-prefix=CHECK-CC1 %s
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:25:31 %s -o - | \
+// RUN:FileCheck -check-prefix=CHECK-CC1 %s
 // CHECK-CC1: OVERLOAD: [#int#]f(<#float x#>, float y)
 // CHECK-CC1: OVERLOAD: [#int#]f(<#int i#>)
 // CHECK-CC1-NOT, CHECK-CC2-NOT: OVERLOAD: A(
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -5597,12 +5597,16 @@
 QualType Sema::ProduceCallSignatureHelp(Scope *S, Expr *Fn,
 ArrayRef Args,
 SourceLocation OpenParLoc) {
-  if (!CodeCompleter)
+  if (!CodeCompleter || !Fn)
 return QualType();
 
+  // If we have a ParenListExpr for LHS, peel it off by chosing the last expr.
+  if (auto *PLE = llvm::dyn_cast(Fn))
+Fn = PLE->getExpr(PLE->getNumExprs() - 1);
+
   // FIXME: Provide support for variadic template functions.
   // Ignore type-dependent call expressions entirely.
-  if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args))
+  if (Fn->isTypeDependent() || anyNullArguments(Args))
 return QualType();
   // In presence of dependent args we surface all possible signatures using the
   // non-dependent args in the prefix. Afterwards we do a post filtering to 
make


Index: clang/unittests/Sema/CodeCompleteTest.cpp
===
--- clang/unittests/Sema/CodeCompleteTest.cpp
+++ clang/unittests/Sema/CodeCompleteTest.cpp
@@ -488,6 +488,7 @@
 auto y = new decltype(&1)(^);
 // GNU decimal type extension is not supported in clang.
 auto z = new _Decimal128(^);
+void foo() { (void)(foo)(^); }
   )cpp";
   EXPECT_THAT(collectPreferredTypes(Code), Each("NULL TYPE"));
 }
Index: clang/test/CodeCompletion/function-overloads.cpp
===
--- clang/test/CodeCompletion/function-overloads.cpp
+++ clang/test/CodeCompletion/function-overloads.cpp
@@ -21,6 +21,8 @@
 void test_adl() {
   NS::X x;
   g(x, x);
+  (void)(f)(1, 2, 3);
+  (void)(test, test, test, f)(1, 2, 3);
 }
 
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:10:9 %s -o - | FileCheck -check-prefix=CHECK-CC1 %s
@@ -31,6 +33,10 @@
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:10:21 %s -o - | FileCheck -check-prefix=CHECK-CC4 %s
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:23:7 %s -o - | \
 // RUN:FileCheck -check-prefix=CHECK-CC5 %s
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:24:13 %s -o - | \
+// RUN:FileCheck -check-prefix=CHECK-CC1 %s
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:25:31 %s -o - | \
+// RUN:FileCheck -check-prefix=CHECK-CC1 %s
 // CHECK-CC1: OVERLOAD: [#int#]f(<#float x#>, float y)
 // CHECK-CC1: OVERLOAD: [#int#]f(<#int i#>)
 // CHECK-CC1-NOT, CHECK-CC2-NOT: OVERLOAD: A(
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -5597,12 +5597,16 @@
 QualType Sema::ProduceCallSignatureHelp(Scope *S, Expr *Fn,
 ArrayRef Args,

[clang] 3fda262 - [clang][AVR][NFC] Fix a typo

2021-02-03 Thread Ben Shi via cfe-commits

Author: Ben Shi
Date: 2021-02-03T20:00:06+08:00
New Revision: 3fda262b7d7bdbf9db5b1d6602602733b4cf4f35

URL: 
https://github.com/llvm/llvm-project/commit/3fda262b7d7bdbf9db5b1d6602602733b4cf4f35
DIFF: 
https://github.com/llvm/llvm-project/commit/3fda262b7d7bdbf9db5b1d6602602733b4cf4f35.diff

LOG: [clang][AVR][NFC] Fix a typo

Fix a typo in commit d38973aa4d6a2c8be97b9781ca7325ca3eb0c40d

Added: 


Modified: 
clang/lib/Driver/ToolChains/AVR.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/AVR.cpp 
b/clang/lib/Driver/ToolChains/AVR.cpp
index 697623cbee3e..f4f8014ff387 100644
--- a/clang/lib/Driver/ToolChains/AVR.cpp
+++ b/clang/lib/Driver/ToolChains/AVR.cpp
@@ -43,7 +43,7 @@ const struct {
 {"at90s2323", "tiny-stack", "avr2", 0x800060},
 {"at90s2333", "tiny-stack", "avr2", 0x800060},
 {"at90s2343", "tiny-stack", "avr2", 0x800060},
-{"at90s4433", "tiny-stack", "avr2, 0x800060"},
+{"at90s4433", "tiny-stack", "avr2", 0x800060},
 {"attiny22", "tiny-stack", "avr2", 0x800060},
 {"attiny26", "tiny-stack", "avr2", 0x800060},
 {"at90s4414", "", "avr2", 0x800060},



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


[PATCH] D95925: [clangd] Detect rename conflicits within enclosing scope

2021-02-03 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 321050.
kbobyrev marked 3 inline comments as done.
kbobyrev added a comment.

Resolve review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95925

Files:
  clang-tools-extra/clangd/refactor/Rename.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp

Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1010,13 +1010,68 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
-  {R"cpp(// FIXME: detecting local variables is not supported yet.
+  {R"cpp(
 void func() {
   int Conflict;
-  int [[V^ar]];
+  int V^ar;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int Conflict = 42) {
+int V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int Conflict = 42) {
+  } else {
+bool V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int V^ar = 42) {
+  } else {
+bool Conflict;
+  }
 }
   )cpp",
-   nullptr, !HeaderFile, nullptr, "Conflict"},
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  while (int V^ar = 10) {
+bool Conflict = true;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  for (int Something = 9000, Anything = 14, Conflict = 42; Anything > 9;
+   ++Something) {
+int V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func(int Conflict) {
+  bool V^ar;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
 
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -15,8 +15,14 @@
 #include "index/SymbolCollector.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/AST/ParentMapContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/None.h"
@@ -318,13 +324,82 @@
   return Results;
 }
 
+// Detect name conflict with othter DeclStmts in the same enclosing scope.
+const NamedDecl *lookupSiblingWithinEnclosingScope(ASTContext &Ctx,
+   const NamedDecl &RenamedDecl,
+   StringRef NewName) {
+  DynTypedNodeList Parents = Ctx.getParents(RenamedDecl);
+  if (Parents.size() != 1 || !Parents.begin()->get())
+return nullptr;
+  Parents = Ctx.getParents(*Parents.begin()->get());
+  if (Parents.size() != 1)
+return nullptr;
+  // This helper checks if any statement within DeclStmt has NewName.
+  auto CheckDeclStmt = [&](const DeclStmt *DS) -> const NamedDecl * {
+for (const auto &Child : DS->getDeclGroup())
+  if (const auto *ND = dyn_cast(Child))
+if (ND != &RenamedDecl && ND->getName() == NewName)
+  return ND;
+return nullptr;
+  };
+  auto CheckCompoundStmt = [&](const CompoundStmt *CS) -> const NamedDecl * {
+if (!CS)
+  return nullptr;
+for (const auto *Node : CS->children())
+  if (const auto *DS = dyn_cast(Node))
+if (const auto *Result = CheckDeclStmt(DS))
+  return Result;
+return nullptr;
+  };
+  // This helper checks if there is a condition variable has NewName.
+  auto CheckConditionVariable = [&](const auto *Scope) -> const NamedDecl * {
+if (!Scope)
+  return nullptr;
+if (const auto *ConditionDS = Scope->getConditionVariableDeclStmt())
+  if (const auto *Result = CheckDeclStmt(ConditionDS))
+return Result;
+return nullptr;
+  };
+  const auto *ParentNode = Parents.begin();
+  if (const auto *EnclosingCS = ParentNode->get()) {
+if (const auto *Result = CheckCompoundStmt(EnclosingCS))
+  return Result;
+Parents = Ctx.getParents(*EnclosingCS);
+if (Parents.size() != 1)
+  return nullptr;
+cons

[PATCH] D95925: [clangd] Detect rename conflicits within enclosing scope

2021-02-03 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev added inline comments.



Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:339
+  if (const auto *If = ParentNode->get())
+if (const auto *Then = dyn_cast(If->getThen()))
+  EnclosingScope = Then;

hokein wrote:
> thinking more about the `if` case, I think else should be included as well? 
> no need to address in this patch.
> 
> like
> 
> ```
> if (int a = 0) {
> } else {
>   int s; // rename s=>a will cause a compiling error.
> }
> ```
This case is already supported: `else`'s `CompoundStmt` is attached to the same 
`IfStmt` with variable declaration and is checked just like the "main" branch.

The other one wasn't (renaming `a` into `s`) but I've added this and also added 
tests for this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95925

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


[PATCH] D95925: [clangd] Detect rename conflicits within enclosing scope

2021-02-03 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 321052.
kbobyrev added a comment.

Save few LOCs by checking for nullptr in CheckDeclStmt.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95925

Files:
  clang-tools-extra/clangd/refactor/Rename.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp

Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1010,13 +1010,68 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
-  {R"cpp(// FIXME: detecting local variables is not supported yet.
+  {R"cpp(
 void func() {
   int Conflict;
-  int [[V^ar]];
+  int V^ar;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int Conflict = 42) {
+int V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int Conflict = 42) {
+  } else {
+bool V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int V^ar = 42) {
+  } else {
+bool Conflict;
+  }
 }
   )cpp",
-   nullptr, !HeaderFile, nullptr, "Conflict"},
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  while (int V^ar = 10) {
+bool Conflict = true;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  for (int Something = 9000, Anything = 14, Conflict = 42; Anything > 9;
+   ++Something) {
+int V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func(int Conflict) {
+  bool V^ar;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
 
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -15,8 +15,14 @@
 #include "index/SymbolCollector.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/AST/ParentMapContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/None.h"
@@ -318,13 +324,83 @@
   return Results;
 }
 
+// Detect name conflict with othter DeclStmts in the same enclosing scope.
+const NamedDecl *lookupSiblingWithinEnclosingScope(ASTContext &Ctx,
+   const NamedDecl &RenamedDecl,
+   StringRef NewName) {
+  DynTypedNodeList Parents = Ctx.getParents(RenamedDecl);
+  if (Parents.size() != 1 || !Parents.begin()->get())
+return nullptr;
+  Parents = Ctx.getParents(*Parents.begin()->get());
+  if (Parents.size() != 1)
+return nullptr;
+  // This helper checks if any statement within DeclStmt has NewName.
+  auto CheckDeclStmt = [&](const DeclStmt *DS) -> const NamedDecl * {
+if (!DS)
+  return nullptr;
+for (const auto &Child : DS->getDeclGroup())
+  if (const auto *ND = dyn_cast(Child))
+if (ND != &RenamedDecl && ND->getName() == NewName)
+  return ND;
+return nullptr;
+  };
+  auto CheckCompoundStmt = [&](const CompoundStmt *CS) -> const NamedDecl * {
+if (!CS)
+  return nullptr;
+for (const auto *Node : CS->children())
+  if (const auto *Result = CheckDeclStmt(dyn_cast(Node)))
+return Result;
+return nullptr;
+  };
+  // This helper checks if there is a condition variable has NewName.
+  auto CheckConditionVariable = [&](const auto *Scope) -> const NamedDecl * {
+if (!Scope)
+  return nullptr;
+if (const auto *Result =
+CheckDeclStmt(Scope->getConditionVariableDeclStmt()))
+  return Result;
+return nullptr;
+  };
+  const auto *ParentNode = Parents.begin();
+  if (const auto *EnclosingCS = ParentNode->get()) {
+if (const auto *Result = CheckCompoundStmt(EnclosingCS))
+  return Result;
+Parents = Ctx.getParents(*EnclosingCS);
+if (Parents.size() != 1)
+  return nullptr;
+const auto *Parent = Parents.begin();
+if (const a

[PATCH] D95925: [clangd] Detect rename conflicits within enclosing scope

2021-02-03 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 321053.
kbobyrev added a comment.

Don't spell out DynTypedNodeList and don't include ParentMapContext.h


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95925

Files:
  clang-tools-extra/clangd/refactor/Rename.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp

Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1010,13 +1010,68 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
-  {R"cpp(// FIXME: detecting local variables is not supported yet.
+  {R"cpp(
 void func() {
   int Conflict;
-  int [[V^ar]];
+  int V^ar;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int Conflict = 42) {
+int V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int Conflict = 42) {
+  } else {
+bool V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int V^ar = 42) {
+  } else {
+bool Conflict;
+  }
 }
   )cpp",
-   nullptr, !HeaderFile, nullptr, "Conflict"},
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  while (int V^ar = 10) {
+bool Conflict = true;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  for (int Something = 9000, Anything = 14, Conflict = 42; Anything > 9;
+   ++Something) {
+int V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func(int Conflict) {
+  bool V^ar;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
 
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -15,8 +15,13 @@
 #include "index/SymbolCollector.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/None.h"
@@ -318,13 +323,83 @@
   return Results;
 }
 
+// Detect name conflict with othter DeclStmts in the same enclosing scope.
+const NamedDecl *lookupSiblingWithinEnclosingScope(ASTContext &Ctx,
+   const NamedDecl &RenamedDecl,
+   StringRef NewName) {
+  auto Parents = Ctx.getParents(RenamedDecl);
+  if (Parents.size() != 1 || !Parents.begin()->get())
+return nullptr;
+  Parents = Ctx.getParents(*Parents.begin()->get());
+  if (Parents.size() != 1)
+return nullptr;
+  // This helper checks if any statement within DeclStmt has NewName.
+  auto CheckDeclStmt = [&](const DeclStmt *DS) -> const NamedDecl * {
+if (!DS)
+  return nullptr;
+for (const auto &Child : DS->getDeclGroup())
+  if (const auto *ND = dyn_cast(Child))
+if (ND != &RenamedDecl && ND->getName() == NewName)
+  return ND;
+return nullptr;
+  };
+  auto CheckCompoundStmt = [&](const CompoundStmt *CS) -> const NamedDecl * {
+if (!CS)
+  return nullptr;
+for (const auto *Node : CS->children())
+  if (const auto *Result = CheckDeclStmt(dyn_cast(Node)))
+return Result;
+return nullptr;
+  };
+  // This helper checks if there is a condition variable has NewName.
+  auto CheckConditionVariable = [&](const auto *Scope) -> const NamedDecl * {
+if (!Scope)
+  return nullptr;
+if (const auto *Result =
+CheckDeclStmt(Scope->getConditionVariableDeclStmt()))
+  return Result;
+return nullptr;
+  };
+  const auto *ParentNode = Parents.begin();
+  if (const auto *EnclosingCS = ParentNode->get()) {
+if (const auto *Result = CheckCompoundStmt(EnclosingCS))
+  return Result;
+Parents = Ctx.getParents(*EnclosingCS);
+if (Parents.size() != 1)
+  return nullptr;
+const auto *Parent = Parents.begin();
+if (const auto *Result = CheckConditionVariable(Pa

[PATCH] D95935: [clang][CodeComplete] Fix crash on ParenListExprs

2021-02-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 321054.
kadircet added a comment.

- Also handle memberrefexpr case.

Fixes https://github.com/clangd/clangd/issues/676.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95935

Files:
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/CodeCompletion/function-overloads.cpp
  clang/test/CodeCompletion/member-access.c
  clang/unittests/Sema/CodeCompleteTest.cpp


Index: clang/unittests/Sema/CodeCompleteTest.cpp
===
--- clang/unittests/Sema/CodeCompleteTest.cpp
+++ clang/unittests/Sema/CodeCompleteTest.cpp
@@ -488,6 +488,7 @@
 auto y = new decltype(&1)(^);
 // GNU decimal type extension is not supported in clang.
 auto z = new _Decimal128(^);
+void foo() { (void)(foo)(^); }
   )cpp";
   EXPECT_THAT(collectPreferredTypes(Code), Each("NULL TYPE"));
 }
Index: clang/test/CodeCompletion/member-access.c
===
--- clang/test/CodeCompletion/member-access.c
+++ clang/test/CodeCompletion/member-access.c
@@ -29,3 +29,10 @@
 
 // RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits 
-code-completion-at=%s:24:5 %s -o - | FileCheck -check-prefix=CHECK-CC3 %s
 // CHECK-CC3: x (requires fix-it: {24:4-24:5} to "->")
+
+void test4(struct Point *p) {
+  (int)(p)->x;
+  (int)(0,1,2,3,4,p)->x;
+}
+// RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits 
-code-completion-at=%s:34:13 %s -o - | FileCheck -check-prefix=CHECK-CC1 %s
+// RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits 
-code-completion-at=%s:35:23 %s -o - | FileCheck -check-prefix=CHECK-CC1 %s
Index: clang/test/CodeCompletion/function-overloads.cpp
===
--- clang/test/CodeCompletion/function-overloads.cpp
+++ clang/test/CodeCompletion/function-overloads.cpp
@@ -21,6 +21,8 @@
 void test_adl() {
   NS::X x;
   g(x, x);
+  (void)(f)(1, 2, 3);
+  (void)(test, test, test, f)(1, 2, 3);
 }
 
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:10:9 %s -o - | 
FileCheck -check-prefix=CHECK-CC1 %s
@@ -31,6 +33,10 @@
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:10:21 %s -o - | 
FileCheck -check-prefix=CHECK-CC4 %s
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:23:7 %s -o - | \
 // RUN:FileCheck -check-prefix=CHECK-CC5 %s
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:24:13 %s -o - | \
+// RUN:FileCheck -check-prefix=CHECK-CC1 %s
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:25:31 %s -o - | \
+// RUN:FileCheck -check-prefix=CHECK-CC1 %s
 // CHECK-CC1: OVERLOAD: [#int#]f(<#float x#>, float y)
 // CHECK-CC1: OVERLOAD: [#int#]f(<#int i#>)
 // CHECK-CC1-NOT, CHECK-CC2-NOT: OVERLOAD: A(
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -5168,6 +5168,14 @@
   if (!Base || !CodeCompleter)
 return;
 
+  // Peel off the ParenListExpr by chosing the last one.
+  if (auto *PLE = llvm::dyn_cast(Base))
+Base = PLE->getExpr(PLE->getNumExprs() - 1);
+  if (OtherOpBase) {
+if (auto *PLE = llvm::dyn_cast(OtherOpBase))
+  OtherOpBase = PLE->getExpr(PLE->getNumExprs() - 1);
+  }
+
   ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
   if (ConvertedBase.isInvalid())
 return;
@@ -5597,12 +5605,16 @@
 QualType Sema::ProduceCallSignatureHelp(Scope *S, Expr *Fn,
 ArrayRef Args,
 SourceLocation OpenParLoc) {
-  if (!CodeCompleter)
+  if (!CodeCompleter || !Fn)
 return QualType();
 
+  // If we have a ParenListExpr for LHS, peel it off by chosing the last expr.
+  if (auto *PLE = llvm::dyn_cast(Fn))
+Fn = PLE->getExpr(PLE->getNumExprs() - 1);
+
   // FIXME: Provide support for variadic template functions.
   // Ignore type-dependent call expressions entirely.
-  if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args))
+  if (Fn->isTypeDependent() || anyNullArguments(Args))
 return QualType();
   // In presence of dependent args we surface all possible signatures using the
   // non-dependent args in the prefix. Afterwards we do a post filtering to 
make


Index: clang/unittests/Sema/CodeCompleteTest.cpp
===
--- clang/unittests/Sema/CodeCompleteTest.cpp
+++ clang/unittests/Sema/CodeCompleteTest.cpp
@@ -488,6 +488,7 @@
 auto y = new decltype(&1)(^);
 // GNU decimal type extension is not supported in clang.
 auto z = new _Decimal128(^);
+void foo() { (void)(foo)(^); }
   )cpp";
   EXPECT_THAT(collectPreferredTypes(Code), Each("NULL TYPE"));
 }
Index: clang/test/CodeCompletion/member-access.c
==

[PATCH] D95925: [clangd] Detect rename conflicits within enclosing scope

2021-02-03 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 321055.
kbobyrev added a comment.

Revert last change: leads to incomplete types.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95925

Files:
  clang-tools-extra/clangd/refactor/Rename.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp

Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1010,13 +1010,68 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
-  {R"cpp(// FIXME: detecting local variables is not supported yet.
+  {R"cpp(
 void func() {
   int Conflict;
-  int [[V^ar]];
+  int V^ar;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int Conflict = 42) {
+int V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int Conflict = 42) {
+  } else {
+bool V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int V^ar = 42) {
+  } else {
+bool Conflict;
+  }
 }
   )cpp",
-   nullptr, !HeaderFile, nullptr, "Conflict"},
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  while (int V^ar = 10) {
+bool Conflict = true;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  for (int Something = 9000, Anything = 14, Conflict = 42; Anything > 9;
+   ++Something) {
+int V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func(int Conflict) {
+  bool V^ar;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
 
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -15,8 +15,14 @@
 #include "index/SymbolCollector.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/AST/ParentMapContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/None.h"
@@ -318,13 +324,83 @@
   return Results;
 }
 
+// Detect name conflict with othter DeclStmts in the same enclosing scope.
+const NamedDecl *lookupSiblingWithinEnclosingScope(ASTContext &Ctx,
+   const NamedDecl &RenamedDecl,
+   StringRef NewName) {
+  DynTypedNodeList Parents = Ctx.getParents(RenamedDecl);
+  if (Parents.size() != 1 || !Parents.begin()->get())
+return nullptr;
+  Parents = Ctx.getParents(*Parents.begin()->get());
+  if (Parents.size() != 1)
+return nullptr;
+  // This helper checks if any statement within DeclStmt has NewName.
+  auto CheckDeclStmt = [&](const DeclStmt *DS) -> const NamedDecl * {
+if (!DS)
+  return nullptr;
+for (const auto &Child : DS->getDeclGroup())
+  if (const auto *ND = dyn_cast(Child))
+if (ND != &RenamedDecl && ND->getName() == NewName)
+  return ND;
+return nullptr;
+  };
+  auto CheckCompoundStmt = [&](const CompoundStmt *CS) -> const NamedDecl * {
+if (!CS)
+  return nullptr;
+for (const auto *Node : CS->children())
+  if (const auto *Result = CheckDeclStmt(dyn_cast(Node)))
+return Result;
+return nullptr;
+  };
+  // This helper checks if there is a condition variable has NewName.
+  auto CheckConditionVariable = [&](const auto *Scope) -> const NamedDecl * {
+if (!Scope)
+  return nullptr;
+if (const auto *Result =
+CheckDeclStmt(Scope->getConditionVariableDeclStmt()))
+  return Result;
+return nullptr;
+  };
+  const auto *ParentNode = Parents.begin();
+  if (const auto *EnclosingCS = ParentNode->get()) {
+if (const auto *Result = CheckCompoundStmt(EnclosingCS))
+  return Result;
+Parents = Ctx.getParents(*EnclosingCS);
+if (Parents.size() != 1)
+  return nullptr;
+const auto *Parent = Parents.begin();
+if (const auto *Resu

[clang] e635feb - [OpenCL] Fix address space in binding of initializer lists to referencs

2021-02-03 Thread Anastasia Stulova via cfe-commits

Author: Anastasia Stulova
Date: 2021-02-03T12:48:21Z
New Revision: e635feb15a91e6eeb77876031be2811e63d542f3

URL: 
https://github.com/llvm/llvm-project/commit/e635feb15a91e6eeb77876031be2811e63d542f3
DIFF: 
https://github.com/llvm/llvm-project/commit/e635feb15a91e6eeb77876031be2811e63d542f3.diff

LOG: [OpenCL] Fix address space in binding of initializer lists to referencs

Prevent materializing temporaries in the address space of the references
they are bind to. The temporaries should always be in the same address
space - private for OpenCL.

Tags: #clang

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

Added: 


Modified: 
clang/lib/Sema/SemaInit.cpp
clang/test/CodeGenOpenCLCXX/addrspace-references.cl
clang/test/SemaOpenCLCXX/address-space-references.cl

Removed: 




diff  --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index f4493d84238d..4e3547c5121f 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -4289,17 +4289,36 @@ static void TryReferenceListInitialization(Sema &S,
 if (Sequence.step_begin() != Sequence.step_end())
   Sequence.RewrapReferenceInitList(cv1T1, InitList);
   }
-
+  // Perform address space compatibility check.
+  QualType cv1T1IgnoreAS = cv1T1;
+  if (T1Quals.hasAddressSpace()) {
+Qualifiers T2Quals;
+(void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
+if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
+  Sequence.SetFailed(
+  InitializationSequence::FK_ReferenceInitDropsQualifiers);
+  return;
+}
+// Ignore address space of reference type at this point and perform address
+// space conversion after the reference binding step.
+cv1T1IgnoreAS =
+S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace());
+  }
   // Not reference-related. Create a temporary and bind to that.
-  InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
+  InitializedEntity TempEntity =
+  InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
 
   TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
 TreatUnavailableAsInvalid);
   if (Sequence) {
 if (DestType->isRValueReferenceType() ||
-(T1Quals.hasConst() && !T1Quals.hasVolatile()))
-  Sequence.AddReferenceBindingStep(cv1T1, /*BindingTemporary=*/true);
-else
+(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
+  Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
+   /*BindingTemporary=*/true);
+  if (T1Quals.hasAddressSpace())
+Sequence.AddQualificationConversionStep(
+cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
+} else
   Sequence.SetFailed(
   
InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
   }

diff  --git a/clang/test/CodeGenOpenCLCXX/addrspace-references.cl 
b/clang/test/CodeGenOpenCLCXX/addrspace-references.cl
index 056168684d2d..6d4bece1a624 100644
--- a/clang/test/CodeGenOpenCLCXX/addrspace-references.cl
+++ b/clang/test/CodeGenOpenCLCXX/addrspace-references.cl
@@ -1,8 +1,16 @@
-//RUN: %clang_cc1 %s -cl-std=clc++ -triple spir -emit-llvm -o - | FileCheck %s
+//RUN: %clang_cc1 %s -cl-std=clc++ -triple spir -emit-llvm -o - -O0 | 
FileCheck %s
+
+typedef short short2 __attribute__((ext_vector_type(2)));
 
 int bar(const unsigned int &i);
-// CHECK-LABEL: define{{.*}} spir_func void @_Z3foov() 
-void foo() {
+
+class C {
+public:
+  void bar(const short2 &);
+};
+
+// CHECK-LABEL: define{{.*}} spir_func void @_Z6scalarv()
+void scalar() {
   // The generic addr space reference parameter object will be bound
   // to a temporary value allocated in private addr space. We need an
   // addrspacecast before passing the value to the function.
@@ -12,3 +20,14 @@ void foo() {
   // CHECK: call spir_func i32 @_Z3barRU3AS4Kj(i32 addrspace(4)* align 4 
dereferenceable(4) [[REG]])
   bar(1);
 }
+
+// Test list initialization
+// CHECK-LABEL: define{{.*}} spir_func void @_Z4listv()
+void list() {
+  C c1;
+// CHECK: [[REF:%.*]] = alloca <2 x i16>
+// CHECK: store <2 x i16> , <2 x i16>* [[REF]]
+// CHECK: [[REG:%[.a-z0-9]+]] = addrspacecast <2 x i16>* [[REF]] to <2 x i16> 
addrspace(4)*
+// CHECK: call {{.*}}void @_ZNU3AS41C3barERU3AS4KDv2_s(%class.C addrspace(4)* 
{{.*}}, <2 x i16> addrspace(4)*{{.*}} [[REG]])
+  c1.bar({1, 2});
+}

diff  --git a/clang/test/SemaOpenCLCXX/address-space-references.cl 
b/clang/test/SemaOpenCLCXX/address-space-references.cl
index 66cd1c02e32f..05e789a7d4fd 100644
--- a/clang/test/SemaOpenCLCXX/address-space-references.cl
+++ b/clang/test/SemaOpenCLCXX/address-space-references.cl
@@ -10,8 +10,20 @@ int bar(const __global unsigned int &i); // 
expected-note{{passing argument to p
 // can't detect this case and therefore fails.
 int bar(const unsigned int &i);
 
+typedef short short2 __attribu

[PATCH] D95608: [OpenCL][PR48896] Fix address space in binding of initializer lists to references

2021-02-03 Thread Anastasia Stulova via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe635feb15a91: [OpenCL] Fix address space in binding of 
initializer lists to referencs (authored by Anastasia).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D95608?vs=320751&id=321057#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95608

Files:
  clang/lib/Sema/SemaInit.cpp
  clang/test/CodeGenOpenCLCXX/addrspace-references.cl
  clang/test/SemaOpenCLCXX/address-space-references.cl

Index: clang/test/SemaOpenCLCXX/address-space-references.cl
===
--- clang/test/SemaOpenCLCXX/address-space-references.cl
+++ clang/test/SemaOpenCLCXX/address-space-references.cl
@@ -10,8 +10,20 @@
 // can't detect this case and therefore fails.
 int bar(const unsigned int &i);
 
+typedef short short2 __attribute__((ext_vector_type(2)));
+class C {
+public:
+  void gen(const short2 &);
+  void glob(__global const short2 &); //expected-note{{passing argument to parameter here}}
+  void nested_list(const short2 (&)[2]);
+};
+
 void foo() {
   bar(1); // expected-error{{binding reference of type 'const __global unsigned int' to value of type 'int' changes address space}}
+  C c;
+  c.gen({1, 2});
+  c.glob({1, 2}); //expected-error{{binding reference of type 'const __global short2' (vector of 2 'short' values) to value of type 'void' changes address space}}
+  c.nested_list({{1, 2}, {3, 4}});
 }
 
 // Test addr space conversion with nested pointers
Index: clang/test/CodeGenOpenCLCXX/addrspace-references.cl
===
--- clang/test/CodeGenOpenCLCXX/addrspace-references.cl
+++ clang/test/CodeGenOpenCLCXX/addrspace-references.cl
@@ -1,8 +1,16 @@
-//RUN: %clang_cc1 %s -cl-std=clc++ -triple spir -emit-llvm -o - | FileCheck %s
+//RUN: %clang_cc1 %s -cl-std=clc++ -triple spir -emit-llvm -o - -O0 | FileCheck %s
+
+typedef short short2 __attribute__((ext_vector_type(2)));
 
 int bar(const unsigned int &i);
-// CHECK-LABEL: define{{.*}} spir_func void @_Z3foov() 
-void foo() {
+
+class C {
+public:
+  void bar(const short2 &);
+};
+
+// CHECK-LABEL: define{{.*}} spir_func void @_Z6scalarv()
+void scalar() {
   // The generic addr space reference parameter object will be bound
   // to a temporary value allocated in private addr space. We need an
   // addrspacecast before passing the value to the function.
@@ -12,3 +20,14 @@
   // CHECK: call spir_func i32 @_Z3barRU3AS4Kj(i32 addrspace(4)* align 4 dereferenceable(4) [[REG]])
   bar(1);
 }
+
+// Test list initialization
+// CHECK-LABEL: define{{.*}} spir_func void @_Z4listv()
+void list() {
+  C c1;
+// CHECK: [[REF:%.*]] = alloca <2 x i16>
+// CHECK: store <2 x i16> , <2 x i16>* [[REF]]
+// CHECK: [[REG:%[.a-z0-9]+]] = addrspacecast <2 x i16>* [[REF]] to <2 x i16> addrspace(4)*
+// CHECK: call {{.*}}void @_ZNU3AS41C3barERU3AS4KDv2_s(%class.C addrspace(4)* {{.*}}, <2 x i16> addrspace(4)*{{.*}} [[REG]])
+  c1.bar({1, 2});
+}
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -4289,17 +4289,36 @@
 if (Sequence.step_begin() != Sequence.step_end())
   Sequence.RewrapReferenceInitList(cv1T1, InitList);
   }
-
+  // Perform address space compatibility check.
+  QualType cv1T1IgnoreAS = cv1T1;
+  if (T1Quals.hasAddressSpace()) {
+Qualifiers T2Quals;
+(void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
+if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
+  Sequence.SetFailed(
+  InitializationSequence::FK_ReferenceInitDropsQualifiers);
+  return;
+}
+// Ignore address space of reference type at this point and perform address
+// space conversion after the reference binding step.
+cv1T1IgnoreAS =
+S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace());
+  }
   // Not reference-related. Create a temporary and bind to that.
-  InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
+  InitializedEntity TempEntity =
+  InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
 
   TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
 TreatUnavailableAsInvalid);
   if (Sequence) {
 if (DestType->isRValueReferenceType() ||
-(T1Quals.hasConst() && !T1Quals.hasVolatile()))
-  Sequence.AddReferenceBindingStep(cv1T1, /*BindingTemporary=*/true);
-else
+(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
+  Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
+   /*BindingTemporary=*/true);
+  if (T1Quals.hasAddressSpace())
+Sequence.AddQualificationConversionStep(
+cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
+

[PATCH] D95925: [clangd] Detect rename conflicits within enclosing scope

2021-02-03 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

thanks, looks better now, just some nits to improve the code readability.




Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:332
+  DynTypedNodeList Parents = Ctx.getParents(RenamedDecl);
+  if (Parents.size() != 1 || !Parents.begin()->get())
+return nullptr;

since we repeat this code multiple times, I think we can use wrap it with a 
lambda (e.g. getSingleParent etc).



Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:338
+  // This helper checks if any statement within DeclStmt has NewName.
+  auto CheckDeclStmt = [&](const DeclStmt *DS) -> const NamedDecl * {
+for (const auto &Child : DS->getDeclGroup())

maybe name it `LookupInDeclStmt` and pass the `Name` as a parameter, the same 
below.



Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:345
+  };
+  auto CheckCompoundStmt = [&](const CompoundStmt *CS) -> const NamedDecl * {
+if (!CS)

the same lookupInCompoundStmt.
nit: I would pass Stmt directly, and do the "compoundStmt" cast internally, to 
save some boilerplate cast in call sides :)



Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:350
+  if (const auto *DS = dyn_cast(Node))
+if (const auto *Result = CheckDeclStmt(DS))
+  return Result;

nit: can be just `return CheckDeclStmt(DS);`



Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:355
+  // This helper checks if there is a condition variable has NewName.
+  auto CheckConditionVariable = [&](const auto *Scope) -> const NamedDecl * {
+if (!Scope)

nit: explicit spell out the `auto` type?



Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:359
+if (const auto *ConditionDS = Scope->getConditionVariableDeclStmt())
+  if (const auto *Result = CheckDeclStmt(ConditionDS))
+return Result;

nit: the same here, `return CheckDeclStmt 
(Scope->getConditionVariableDeclStmt())`, just adding the nullptr handling in 
`CheckDeclStmt`.





Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:364
+  const auto *ParentNode = Parents.begin();
+  if (const auto *EnclosingCS = ParentNode->get()) {
+if (const auto *Result = CheckCompoundStmt(EnclosingCS))

I understand all cases of these if branches at the moment, but I think we'd 
better to add some comments, or examples here -- help us understand this code 
in case that we forget the context in the future :)



Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:382
+if (Parameter->getName() == NewName)
+  return Parameter;
+  }

I think we need a `return null` here (or use if-else pattern), otherwise, the 
following if-stmt will be examined as well, which seems no necessary.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95925

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


[PATCH] D95942: [clangd] Deduplicate scopes in IncludeFixer queries

2021-02-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: sammccall.
Herald added subscribers: usaxena95, arphaman.
kadircet requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D95942

Files:
  clang-tools-extra/clangd/IncludeFixer.cpp


Index: clang-tools-extra/clangd/IncludeFixer.cpp
===
--- clang-tools-extra/clangd/IncludeFixer.cpp
+++ clang-tools-extra/clangd/IncludeFixer.cpp
@@ -40,6 +40,7 @@
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/FormatVariadic.h"
+#include 
 #include 
 
 namespace clang {
@@ -313,18 +314,18 @@
 std::vector
 collectAccessibleScopes(Sema &Sem, const DeclarationNameInfo &Typo, Scope *S,
 Sema::LookupNameKind LookupKind) {
-  std::vector Scopes;
   VisitedContextCollector Collector;
   Sem.LookupVisibleDecls(S, LookupKind, Collector,
  /*IncludeGlobalScope=*/false,
  /*LoadExternal=*/false);
 
-  Scopes.push_back("");
+  std::set Scopes;
+  Scopes.insert("");
   for (const auto *Ctx : Collector.takeVisitedContexts()) {
 if (isa(Ctx))
-  Scopes.push_back(printNamespaceScope(*Ctx));
+  Scopes.insert(printNamespaceScope(*Ctx));
   }
-  return Scopes;
+  return {Scopes.begin(), Scopes.end()};
 }
 
 class IncludeFixer::UnresolvedNameRecorder : public ExternalSemaSource {


Index: clang-tools-extra/clangd/IncludeFixer.cpp
===
--- clang-tools-extra/clangd/IncludeFixer.cpp
+++ clang-tools-extra/clangd/IncludeFixer.cpp
@@ -40,6 +40,7 @@
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/FormatVariadic.h"
+#include 
 #include 
 
 namespace clang {
@@ -313,18 +314,18 @@
 std::vector
 collectAccessibleScopes(Sema &Sem, const DeclarationNameInfo &Typo, Scope *S,
 Sema::LookupNameKind LookupKind) {
-  std::vector Scopes;
   VisitedContextCollector Collector;
   Sem.LookupVisibleDecls(S, LookupKind, Collector,
  /*IncludeGlobalScope=*/false,
  /*LoadExternal=*/false);
 
-  Scopes.push_back("");
+  std::set Scopes;
+  Scopes.insert("");
   for (const auto *Ctx : Collector.takeVisitedContexts()) {
 if (isa(Ctx))
-  Scopes.push_back(printNamespaceScope(*Ctx));
+  Scopes.insert(printNamespaceScope(*Ctx));
   }
-  return Scopes;
+  return {Scopes.begin(), Scopes.end()};
 }
 
 class IncludeFixer::UnresolvedNameRecorder : public ExternalSemaSource {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95886: [OpenCL][Docs] Link page explaining tooling for offline compilation

2021-02-03 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh added inline comments.



Comment at: clang/docs/UsersManual.rst:2835
 `_
-to produce SPIR-V binary.
-
+to produce SPIR-V binary. More detail are provided in the following
+online resource - `the offline compilation from OpenCL kernel sources into

detail -> details

remove "the following"



Comment at: clang/docs/UsersManual.rst:2836
+to produce SPIR-V binary. More detail are provided in the following
+online resource - `the offline compilation from OpenCL kernel sources into
+SPIR-V using open source tools

Remove the `online resource - the`.


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

https://reviews.llvm.org/D95886

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


[PATCH] D95877: [analyzer] Fix static_cast on pointer-to-member handling

2021-02-03 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD updated this revision to Diff 321074.
RedDocMD added a comment.

Remoevd the use of std::list with llvm::SmallVector. Removed the need to delete 
elements.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95877

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
  clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
  clang/test/Analysis/pointer-to-member.cpp

Index: clang/test/Analysis/pointer-to-member.cpp
===
--- clang/test/Analysis/pointer-to-member.cpp
+++ clang/test/Analysis/pointer-to-member.cpp
@@ -287,3 +287,25 @@
   clang_analyzer_eval(a.*ep == 5); // expected-warning{{TRUE}}
 }
 } // namespace testAnonymousMember
+
+namespace testStaticCasting {
+// From bug #48739
+struct Grandfather {
+  int field;
+};
+
+struct Father : public Grandfather {};
+struct Son : public Father {};
+
+void test() {
+  int Son::*sf = &Son::field;
+  Grandfather grandpa;
+  grandpa.field = 10;
+  int Grandfather::*gpf1 = static_cast(sf);
+  int Grandfather::*gpf2 = static_cast(static_cast(sf));
+  int Grandfather::*gpf3 = static_cast(static_cast(static_cast(sf)));
+  clang_analyzer_eval(grandpa.*gpf1 == 10); // expected-warning{{TRUE}}
+  clang_analyzer_eval(grandpa.*gpf2 == 10); // expected-warning{{TRUE}}
+  clang_analyzer_eval(grandpa.*gpf3 == 10); // expected-warning{{TRUE}}
+}
+} // namespace testStaticCasting
Index: clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
@@ -526,10 +526,11 @@
   case CK_ReinterpretMemberPointer: {
 SVal V = state->getSVal(Ex, LCtx);
 if (auto PTMSV = V.getAs()) {
-  SVal CastedPTMSV = svalBuilder.makePointerToMember(
-  getBasicVals().accumCXXBase(
+  SVal CastedPTMSV =
+  svalBuilder.makePointerToMember(getBasicVals().accumCXXBase(
   llvm::make_range(
-  CastE->path_begin(), CastE->path_end()), *PTMSV));
+  CastE->path_begin(), CastE->path_end()),
+  *PTMSV, CastE->getCastKind()));
   state = state->BindExpr(CastE, LCtx, CastedPTMSV);
   Bldr.generateNode(CastE, Pred, state);
   continue;
Index: clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
===
--- clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
+++ clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
@@ -21,8 +21,11 @@
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/ImmutableList.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallVector.h"
+#include 
 #include 
 #include 
+#include 
 #include 
 
 using namespace clang;
@@ -178,7 +181,11 @@
 
 const PointerToMemberData *BasicValueFactory::accumCXXBase(
 llvm::iterator_range PathRange,
-const nonloc::PointerToMember &PTM) {
+const nonloc::PointerToMember &PTM, const CastKind &kind) {
+  assert((kind == CK_DerivedToBaseMemberPointer ||
+  kind == CK_BaseToDerivedMemberPointer ||
+  kind == CK_ReinterpretMemberPointer) &&
+ "accumCXXBase called with wrong CastKind");
   nonloc::PointerToMember::PTMDataType PTMDT = PTM.getPTMData();
   const NamedDecl *ND = nullptr;
   llvm::ImmutableList PathList;
@@ -195,8 +202,36 @@
 PathList = PTMD->getCXXBaseList();
   }
 
-  for (const auto &I : llvm::reverse(PathRange))
-PathList = prependCXXBase(I, PathList);
+  if (kind == CK_DerivedToBaseMemberPointer) {
+// Here we pop off matching CXXBaseSpecifiers from PathList.
+// Because, CK_DerivedToBaseMemberPointer comes from a static_cast and
+// serves to remove a matching implicit cast. Note that static_cast's that
+// are no-ops do not count since they produce an empty PathRange, a nice
+// thing about Clang AST.
+
+llvm::SmallVector, 64> BaseList;
+// Initially mark all CXXBaseSpecifier to be included
+for (const auto &I : PathList)
+  BaseList.push_back({I, true});
+
+for (const auto &I : PathRange) {
+  auto *it = std::find_if(
+  BaseList.begin(), BaseList.end(), [&](const auto &B) -> auto {
+return I->getType() == B.first->getType();
+  });
+  it->second = false;
+}
+auto BaseListFilteredRange = llvm::make_filter_range(
+llvm::make_range(BaseList.begin(), BaseList.end()),
+[](const auto &I) -> bool { return I.second; });
+
+PathList = CXXBaseListFactory.getEmptyList();
+for (const auto &I : BaseListFilteredRange)
+  PathList = CXXBaseListFactory.add(I.first, PathList);
+  } else {
+for (const auto &I : llvm::reverse(PathRange))
+  PathLi

[PATCH] D95948: Stop traping on sNaN in __builtin_isnan

2021-02-03 Thread Thomas Preud'homme via Phabricator via cfe-commits
thopre created this revision.
thopre added reviewers: efriedma, kpn, mibintc, sepavloff, rjmccall.
Herald added subscribers: dexonsmith, pengfei.
thopre requested review of this revision.
Herald added projects: clang, LLVM.
Herald added a subscriber: llvm-commits.

__builtin_isnan currently generates a floating-point compare operation
which triggers a trap when faced with a signaling NaN in StrictFP mode.
This commit uses integer operations instead to not generate any trap in
such a case.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D95948

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/X86/strictfp_builtins.c
  clang/test/CodeGen/strictfp_builtins.c
  clang/test/CodeGen/strictfp_fpclassify.c
  llvm/include/llvm/ADT/APFloat.h
  llvm/include/llvm/IR/Type.h

Index: llvm/include/llvm/IR/Type.h
===
--- llvm/include/llvm/IR/Type.h
+++ llvm/include/llvm/IR/Type.h
@@ -308,6 +308,10 @@
   /// ppc long double), this method returns -1.
   int getFPMantissaWidth() const;
 
+  /// Return whether the type is IEEE compatible, as defined by the eponymous
+  /// method in APFloat.
+  bool isIEEE() const { return APFloat::getZero(getFltSemantics()).isIEEE(); }
+
   /// If this is a vector type, return the element type, otherwise return
   /// 'this'.
   inline Type *getScalarType() const {
Index: llvm/include/llvm/ADT/APFloat.h
===
--- llvm/include/llvm/ADT/APFloat.h
+++ llvm/include/llvm/ADT/APFloat.h
@@ -1218,6 +1218,7 @@
   bool isSmallest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isSmallest()); }
   bool isLargest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isLargest()); }
   bool isInteger() const { APFLOAT_DISPATCH_ON_SEMANTICS(isInteger()); }
+  bool isIEEE() const { return usesLayout(getSemantics()); }
 
   APFloat &operator=(const APFloat &RHS) = default;
   APFloat &operator=(APFloat &&RHS) = default;
Index: clang/test/CodeGen/strictfp_builtins.c
===
--- clang/test/CodeGen/strictfp_builtins.c
+++ clang/test/CodeGen/strictfp_builtins.c
@@ -92,17 +92,38 @@
   return;
 }
 
-// CHECK-LABEL: @test_isnan(
+// CHECK-LABEL: @test_float_isnan(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[F_ADDR:%.*]] = alloca float, align 4
+// CHECK-NEXT:store float [[F:%.*]], float* [[F_ADDR]], align 4
+// CHECK-NEXT:[[TMP0:%.*]] = load float, float* [[F_ADDR]], align 4
+// CHECK-NEXT:[[BITCAST:%.*]] = bitcast float [[TMP0]] to i32
+// CHECK-NEXT:[[ABS:%.*]] = and i32 [[BITCAST]], [[#%u,0x7FFF]]
+// CHECK-NEXT:[[TMP1:%.*]] = sub i32 [[#%u,0x7F80]], [[ABS]]
+// CHECK-NEXT:[[ISNAN:%.*]] = lshr i32 [[TMP1]], 31
+// CHECK-NEXT:call void @p(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @.str.4, i64 0, i64 0), i32 [[ISNAN]]) [[ATTR4]]
+// CHECK-NEXT:ret void
+//
+void test_float_isnan(float f) {
+  P(isnan, (f));
+
+  return;
+}
+
+// CHECK-LABEL: @test_double_isnan(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[D_ADDR:%.*]] = alloca double, align 8
 // CHECK-NEXT:store double [[D:%.*]], double* [[D_ADDR]], align 8
 // CHECK-NEXT:[[TMP0:%.*]] = load double, double* [[D_ADDR]], align 8
-// CHECK-NEXT:[[CMP:%.*]] = call i1 @llvm.experimental.constrained.fcmp.f64(double [[TMP0]], double [[TMP0]], metadata !"uno", metadata !"fpexcept.strict") [[ATTR4]]
-// CHECK-NEXT:[[TMP1:%.*]] = zext i1 [[CMP]] to i32
-// CHECK-NEXT:call void @p(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @.str.4, i64 0, i64 0), i32 [[TMP1]]) [[ATTR4]]
+// CHECK-NEXT:[[BITCAST:%.*]] = bitcast double [[TMP0]] to i64
+// CHECK-NEXT:[[ABS:%.*]] = and i64 [[BITCAST]], [[#%u,0x7FFF]]
+// CHECK-NEXT:[[TMP1:%.*]] = sub i64 [[#%u,0x7FF0]], [[ABS]]
+// CHECK-NEXT:[[ISNAN:%.*]] = lshr i64 [[TMP1]], 63
+// CHECK-NEXT:[[RES:%.*]] = trunc i64 [[ISNAN]] to i32
+// CHECK-NEXT:call void @p(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @.str.5, i64 0, i64 0), i32 [[RES]]) [[ATTR4]]
 // CHECK-NEXT:ret void
 //
-void test_isnan(double d) {
+void test_double_isnan(double d) {
   P(isnan, (d));
 
   return;
@@ -120,7 +141,7 @@
 // CHECK-NEXT:[[AND:%.*]] = and i1 [[ISEQ]], [[ISINF]]
 // CHECK-NEXT:[[AND1:%.*]] = and i1 [[AND]], [[ISNORMAL]]
 // CHECK-NEXT:[[TMP2:%.*]] = zext i1 [[AND1]] to i32
-// CHECK-NEXT:call void @p(i8* getelementptr inbounds ([12 x i8], [12 x i8]* @.str.5, i64 0, i64 0), i32 [[TMP2]]) [[ATTR4]]
+// CHECK-NEXT:call void @p(i8* getelementptr inbounds ([12 x i8], [12 x i8]* @.str.6, i64 0, i64 0), i32 [[TMP2]]) [[ATTR4]]
 // CHECK-NEXT:ret void
 //
 void test_isnormal(double d) {
Index: clang/test/CodeGen/X86/strictfp_builtins.c
===
--- /dev/null
+++ clang/test/CodeGen/X86/strictfp_builtins.c
@@ -0,0 +1,46 @@
+// NOTE: Assertions have been autogenerated by u

[PATCH] D95877: [analyzer] Fix static_cast on pointer-to-member handling

2021-02-03 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD updated this revision to Diff 321078.
RedDocMD added a comment.

Made assertion more verbose


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95877

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
  clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
  clang/test/Analysis/pointer-to-member.cpp

Index: clang/test/Analysis/pointer-to-member.cpp
===
--- clang/test/Analysis/pointer-to-member.cpp
+++ clang/test/Analysis/pointer-to-member.cpp
@@ -287,3 +287,25 @@
   clang_analyzer_eval(a.*ep == 5); // expected-warning{{TRUE}}
 }
 } // namespace testAnonymousMember
+
+namespace testStaticCasting {
+// From bug #48739
+struct Grandfather {
+  int field;
+};
+
+struct Father : public Grandfather {};
+struct Son : public Father {};
+
+void test() {
+  int Son::*sf = &Son::field;
+  Grandfather grandpa;
+  grandpa.field = 10;
+  int Grandfather::*gpf1 = static_cast(sf);
+  int Grandfather::*gpf2 = static_cast(static_cast(sf));
+  int Grandfather::*gpf3 = static_cast(static_cast(static_cast(sf)));
+  clang_analyzer_eval(grandpa.*gpf1 == 10); // expected-warning{{TRUE}}
+  clang_analyzer_eval(grandpa.*gpf2 == 10); // expected-warning{{TRUE}}
+  clang_analyzer_eval(grandpa.*gpf3 == 10); // expected-warning{{TRUE}}
+}
+} // namespace testStaticCasting
Index: clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
@@ -526,10 +526,11 @@
   case CK_ReinterpretMemberPointer: {
 SVal V = state->getSVal(Ex, LCtx);
 if (auto PTMSV = V.getAs()) {
-  SVal CastedPTMSV = svalBuilder.makePointerToMember(
-  getBasicVals().accumCXXBase(
+  SVal CastedPTMSV =
+  svalBuilder.makePointerToMember(getBasicVals().accumCXXBase(
   llvm::make_range(
-  CastE->path_begin(), CastE->path_end()), *PTMSV));
+  CastE->path_begin(), CastE->path_end()),
+  *PTMSV, CastE->getCastKind()));
   state = state->BindExpr(CastE, LCtx, CastedPTMSV);
   Bldr.generateNode(CastE, Pred, state);
   continue;
Index: clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
===
--- clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
+++ clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
@@ -21,8 +21,11 @@
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/ImmutableList.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallVector.h"
+#include 
 #include 
 #include 
+#include 
 #include 
 
 using namespace clang;
@@ -178,7 +181,11 @@
 
 const PointerToMemberData *BasicValueFactory::accumCXXBase(
 llvm::iterator_range PathRange,
-const nonloc::PointerToMember &PTM) {
+const nonloc::PointerToMember &PTM, const CastKind &kind) {
+  assert((kind == CK_DerivedToBaseMemberPointer ||
+  kind == CK_BaseToDerivedMemberPointer ||
+  kind == CK_ReinterpretMemberPointer) &&
+ "accumCXXBase called with wrong CastKind");
   nonloc::PointerToMember::PTMDataType PTMDT = PTM.getPTMData();
   const NamedDecl *ND = nullptr;
   llvm::ImmutableList PathList;
@@ -195,8 +202,39 @@
 PathList = PTMD->getCXXBaseList();
   }
 
-  for (const auto &I : llvm::reverse(PathRange))
-PathList = prependCXXBase(I, PathList);
+  if (kind == CK_DerivedToBaseMemberPointer) {
+// Here we pop off matching CXXBaseSpecifiers from PathList.
+// Because, CK_DerivedToBaseMemberPointer comes from a static_cast and
+// serves to remove a matching implicit cast. Note that static_cast's that
+// are no-ops do not count since they produce an empty PathRange, a nice
+// thing about Clang AST.
+
+llvm::SmallVector, 64> BaseList;
+// Initially mark all CXXBaseSpecifier to be included
+for (const auto &I : PathList)
+  BaseList.push_back({I, true});
+
+for (const auto &I : PathRange) {
+  auto *it = std::find_if(
+  BaseList.begin(), BaseList.end(), [&](const auto &B) -> auto {
+return I->getType() == B.first->getType();
+  });
+  assert(it != BaseList.end() &&
+ "Underlying PointerToMemberData of PTM has insufficient number of "
+ "CXXBaseSpecifiers");
+  it->second = false;
+}
+auto BaseListFilteredRange = llvm::make_filter_range(
+llvm::make_range(BaseList.begin(), BaseList.end()),
+[](const auto &I) -> bool { return I.second; });
+
+PathList = CXXBaseListFactory.getEmptyList();
+for (const auto &I : BaseListFilteredRange)
+  PathList = CXXBaseListFactory.add(I.fi

[clang] e48f444 - [Sema] Fix -Warray-bounds false negative when casting an out-of-bounds array item

2021-02-03 Thread via cfe-commits

Author: Ilya Mirsky
Date: 2021-02-03T07:50:50-06:00
New Revision: e48f444751cf781c42934b242b81f549da77bad0

URL: 
https://github.com/llvm/llvm-project/commit/e48f444751cf781c42934b242b81f549da77bad0
DIFF: 
https://github.com/llvm/llvm-project/commit/e48f444751cf781c42934b242b81f549da77bad0.diff

LOG: [Sema] Fix -Warray-bounds false negative when casting an out-of-bounds 
array item

Patch by Ilya Mirsky!

Fixes: http://llvm.org/PR44343

Reviewed By: rsmith

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

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaChecking.cpp
clang/test/Parser/cxx-ambig-decl-expr.cpp
clang/test/SemaCXX/array-bounds.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 7f7c84eb1b1d..2fca81d25345 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -12310,7 +12310,7 @@ class Sema final {
   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
 const ArraySubscriptExpr *ASE=nullptr,
 bool AllowOnePastEnd=true, bool IndexNegated=false);
-  void CheckArrayAccess(const Expr *E);
+  void CheckArrayAccess(const Expr *E, int AllowOnePastEnd = 0);
   // Used to grab the relevant information from a FormatAttr and a
   // FunctionDeclaration.
   struct FormatStringInfo {

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 2d3d36f4adad..17dd5c9e8d99 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -14387,62 +14387,63 @@ void Sema::CheckArrayAccess(const Expr *BaseExpr, 
const Expr *IndexExpr,
 PDiag(diag::note_array_declared_here) << ND);
 }
 
-void Sema::CheckArrayAccess(const Expr *expr) {
-  int AllowOnePastEnd = 0;
-  while (expr) {
-expr = expr->IgnoreParenImpCasts();
-switch (expr->getStmtClass()) {
-  case Stmt::ArraySubscriptExprClass: {
-const ArraySubscriptExpr *ASE = cast(expr);
-CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
- AllowOnePastEnd > 0);
-expr = ASE->getBase();
-break;
-  }
-  case Stmt::MemberExprClass: {
-expr = cast(expr)->getBase();
-break;
-  }
-  case Stmt::OMPArraySectionExprClass: {
-const OMPArraySectionExpr *ASE = cast(expr);
-if (ASE->getLowerBound())
-  CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
-   /*ASE=*/nullptr, AllowOnePastEnd > 0);
-return;
-  }
-  case Stmt::UnaryOperatorClass: {
-// Only unwrap the * and & unary operators
-const UnaryOperator *UO = cast(expr);
-expr = UO->getSubExpr();
-switch (UO->getOpcode()) {
-  case UO_AddrOf:
-AllowOnePastEnd++;
-break;
-  case UO_Deref:
-AllowOnePastEnd--;
-break;
-  default:
-return;
-}
-break;
-  }
-  case Stmt::ConditionalOperatorClass: {
-const ConditionalOperator *cond = cast(expr);
-if (const Expr *lhs = cond->getLHS())
-  CheckArrayAccess(lhs);
-if (const Expr *rhs = cond->getRHS())
-  CheckArrayAccess(rhs);
-return;
-  }
-  case Stmt::CXXOperatorCallExprClass: {
-const auto *OCE = cast(expr);
-for (const auto *Arg : OCE->arguments())
-  CheckArrayAccess(Arg);
-return;
-  }
-  default:
-return;
+void Sema::CheckArrayAccess(const Expr *expr, int AllowOnePastEnd) {
+  if (!expr)
+return;
+
+  expr = expr->IgnoreParenCasts();
+  switch (expr->getStmtClass()) {
+  case Stmt::ArraySubscriptExprClass: {
+const ArraySubscriptExpr *ASE = cast(expr);
+CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, AllowOnePastEnd > 0);
+CheckArrayAccess(ASE->getBase(), AllowOnePastEnd);
+return;
+  }
+  case Stmt::MemberExprClass: {
+expr = cast(expr)->getBase();
+CheckArrayAccess(expr, /*AllowOnePastEnd=*/0);
+return;
+  }
+  case Stmt::OMPArraySectionExprClass: {
+const OMPArraySectionExpr *ASE = cast(expr);
+if (ASE->getLowerBound())
+  CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
+   /*ASE=*/nullptr, AllowOnePastEnd > 0);
+return;
+  }
+  case Stmt::UnaryOperatorClass: {
+// Only unwrap the * and & unary operators
+const UnaryOperator *UO = cast(expr);
+expr = UO->getSubExpr();
+switch (UO->getOpcode()) {
+case UO_AddrOf:
+  AllowOnePastEnd++;
+  break;
+case UO_Deref:
+  AllowOnePastEnd--;
+  break;
+default:
+  return;
 }
+CheckArrayAccess(expr, AllowOnePastEnd);
+return;
+  }
+  case Stmt::ConditionalOperatorClass: {
+const ConditionalOperator *cond = cast(expr);
+if (const Expr *lhs = co

[PATCH] D71714: [Sema] Fix -Warray-bounds false negative when casting an out-of-bounds array item

2021-02-03 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe48f444751cf: [Sema] Fix -Warray-bounds false negative when 
casting an out-of-bounds array… (authored by ilya, committed by einvbri 
).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D71714

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Parser/cxx-ambig-decl-expr.cpp
  clang/test/SemaCXX/array-bounds.cpp

Index: clang/test/SemaCXX/array-bounds.cpp
===
--- clang/test/SemaCXX/array-bounds.cpp
+++ clang/test/SemaCXX/array-bounds.cpp
@@ -27,7 +27,7 @@
 };
 
 void f1(int a[1]) {
-  int val = a[3]; // no warning for function argumnet
+  int val = a[3]; // no warning for function argument
 }
 
 void f2(const int (&a)[2]) { // expected-note {{declared here}}
@@ -133,7 +133,7 @@
 
 int test_sizeof_as_condition(int flag) {
   int arr[2] = { 0, 0 }; // expected-note {{array 'arr' declared here}}
-  if (flag) 
+  if (flag)
 return sizeof(char) != sizeof(char) ? arr[2] : arr[1];
   return sizeof(char) == sizeof(char) ? arr[2] : arr[1]; // expected-warning {{array index 2 is past the end of the array (which contains 2 elements)}}
 }
@@ -241,7 +241,7 @@
 }
 
 int test_pr11007_aux(const char * restrict, ...);
-  
+
 // Test checking with varargs.
 void test_pr11007() {
   double a[5]; // expected-note {{array 'a' declared here}}
@@ -320,3 +320,33 @@
   arr[1] = 0; // expected-warning {{array index 1 is past the end of the array (which contains 1 element)}}
 }
 } // namespace var_template_array
+
+namespace PR44343 {
+  const unsigned int array[2] = {0, 1}; // expected-note 5{{array 'array' declared here}}
+
+  const int i1 = (const int)array[2]; // expected-warning {{array index 2 is past the end of the array (which contains 2 elements)}}
+  const int i2 = static_cast(array[2]); // expected-warning {{array index 2 is past the end of the array (which contains 2 elements)}}
+  const int &i3 = reinterpret_cast(array[2]); // expected-warning {{array index 2 is past the end of the array (which contains 2 elements)}}
+  unsigned int &i4 = const_cast(array[2]); // expected-warning {{array index 2 is past the end of the array (which contains 2 elements)}}
+  int i5 = int(array[2]); // expected-warning {{array index 2 is past the end of the array (which contains 2 elements)}}
+  const unsigned int *i6 = &(1 > 0 ? array[2] : array[1]); // no warning for one-past-end element's address retrieval
+
+  // Test dynamic cast
+  struct Base {
+virtual ~Base();
+  };
+  struct Derived : Base {
+  };
+  Base baseArr[2]; // expected-note {{array 'baseArr' declared here}}
+  Derived *d1 = dynamic_cast(&baseArr[2]); // FIXME: Should actually warn because dynamic_cast accesses the vptr
+  Derived &d2 = dynamic_cast(baseArr[2]); // expected-warning {{array index 2 is past the end of the array (which contains 2 elements)}}
+
+  // Test operator `&` in combination with operators `.` and `->`
+  struct A {
+int n;
+  };
+  A a[2]; // expected-note {{array 'a' declared here}}
+  int *n = &a[2].n; // expected-warning {{array index 2 is past the end of the array (which contains 2 elements)}}
+  A *aPtr[2]; // expected-note {{array 'aPtr' declared here}}
+  int *n2 = &aPtr[2]->n; // expected-warning {{array index 2 is past the end of the array (which contains 2 elements)}}
+}
Index: clang/test/Parser/cxx-ambig-decl-expr.cpp
===
--- clang/test/Parser/cxx-ambig-decl-expr.cpp
+++ clang/test/Parser/cxx-ambig-decl-expr.cpp
@@ -24,7 +24,7 @@
 
   // This is array indexing not an array declarator because a comma expression
   // is not syntactically a constant-expression.
-  int(x[1,1]); // expected-warning 2{{unused}}
+  int(x[1,0]); // expected-warning 2{{unused}}
 
   // This is array indexing not an array declaration because a braced-init-list
   // is not syntactically a constant-expression.
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -14387,62 +14387,63 @@
 PDiag(diag::note_array_declared_here) << ND);
 }
 
-void Sema::CheckArrayAccess(const Expr *expr) {
-  int AllowOnePastEnd = 0;
-  while (expr) {
-expr = expr->IgnoreParenImpCasts();
-switch (expr->getStmtClass()) {
-  case Stmt::ArraySubscriptExprClass: {
-const ArraySubscriptExpr *ASE = cast(expr);
-CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
- AllowOnePastEnd > 0);
-expr = ASE->getBase();
-break;
-  }
-  case Stmt::MemberExprClass: {
-expr = cast(expr)->getBase();
-break;
-  }
-  case Stmt::OMPArraySectionExprClass: {
-const OMPArraySection

[PATCH] D95877: [analyzer] Fix static_cast on pointer-to-member handling

2021-02-03 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD added a comment.

@vsavchenko could you please see the current logic if it is better now?




Comment at: clang/test/Analysis/pointer-to-member.cpp:304
+  grandpa.field = 10;
+  int Grandfather::*gpf1 = static_cast(sf);
+  int Grandfather::*gpf2 = static_cast(static_cast(sf));

vsavchenko wrote:
> What about other type of casts?
I am looking into this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95877

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


[PATCH] D71714: [Sema] Fix -Warray-bounds false negative when casting an out-of-bounds array item

2021-02-03 Thread Vince Bridgers via Phabricator via cfe-commits
vabridgers added a comment.

Thanks @rsmith, will do. Best!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D71714

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


[PATCH] D95860: [clang][Frontend] Fix a crash in DiagnosticRenderer.

2021-02-03 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

But I do not know if there is a better solution, if the file ID is different 
these are in different files, one included from the other. If the "include 
locations" are not accessible in the same way as macro locations we can not get 
the place (of the #include statement) in the original file. Additionally this 
may be not always the best thing to display to the user.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95860

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


[PATCH] D93787: [analyzer] Fix crash caused by accessing empty map

2021-02-03 Thread Vince Bridgers via Phabricator via cfe-commits
vabridgers added a comment.

Abandoning this change request in favor of  @steakhal 's more comprehensive 
change @  https://reviews.llvm.org/D93222


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93787

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


[PATCH] D95695: [clang-tblgen] AnnotateAttr::printPretty has spurious comma when no variadic argument is specified

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

Thank you for the fix, the changes LGTM! Do you need me to commit on your 
behalf?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95695

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


[PATCH] D93787: [analyzer] Fix crash caused by accessing empty map

2021-02-03 Thread Vince Bridgers via Phabricator via cfe-commits
vabridgers abandoned this revision.
vabridgers added a comment.

Abandoning.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93787

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


[PATCH] D95877: [analyzer] Fix static_cast on pointer-to-member handling

2021-02-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

Also, all these `PathRange` and `PathList` don't really reflect what they stand 
for semantically and talk more about implementation.  It's not the problem of 
this patch, but it doesn't make your logic easier to comprehend.




Comment at: clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp:226
+llvm::make_range(BaseList.begin(), BaseList.end()),
+[](const auto &I) -> bool { return I.second; });
+

I think it's all a bit too complicated now.

Right now you have two nested loops:
  1. over `PathRange`
  2. over `BaseList` (in `find_if`)

It won't be a problem to put them in another order, so when you make a 
`filter_range`, you can have `llvm::find_if` which will iterate over 
`PathRange` and captures the given `BaseList` element. So, yes nested lambdas.

Here is a sketch of the solution:
```
auto BaseListFilteredRange = llvm::make_filter_range(
BaseList, // you don't need to make_range here, BaseList IS a range
[&PathRange](const CXXBaseSpecifier *Base) {
  return llvm::find_if(PathRange, [Base](const auto &It) {
return Base->getType() == It.first->getType();
  }) == PathRange.end();
});
```

Aaaand while I was writing that, it got me thinking that we don't need 
`BaseList` in the first place:
```
for (const CXXBaseSpecifier *Base : PathList)
  if (llvm::none_of(PathRange,
[Base](const auto &It) { return Base->getType() == 
It.first->getType(); })
  PathList = CXXBaseListFactory.add(Base, PathList);
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95877

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


[PATCH] D95876: [clang-cl] Remove the /fallback option

2021-02-03 Thread Hans Wennborg via Phabricator via cfe-commits
hans updated this revision to Diff 321080.
hans marked an inline comment as done.

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

https://reviews.llvm.org/D95876

Files:
  clang/docs/ReleaseNotes.rst
  clang/docs/UsersManual.rst
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticOptions.def
  clang/include/clang/Driver/Job.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/TextDiagnostic.h
  clang/lib/Driver/Job.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Clang.h
  clang/lib/Driver/ToolChains/MSVC.cpp
  clang/lib/Driver/ToolChains/MSVC.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/TextDiagnostic.cpp
  clang/lib/Frontend/TextDiagnosticPrinter.cpp
  clang/test/Driver/cl-fallback.c
  clang/test/Driver/cl-options.c
  clang/test/Driver/cl-pch.cpp
  clang/test/Misc/diag-format.c

Index: clang/test/Misc/diag-format.c
===
--- clang/test/Misc/diag-format.c
+++ clang/test/Misc/diag-format.c
@@ -20,11 +20,11 @@
 // RUN: %clang -fsyntax-only -fdiagnostics-format=msvc -fno-show-column -fmsc-version=1900 %s 2>&1 | FileCheck %s --strict-whitespace -check-prefix=MSVC2015_ORIG
 //
 // RUN: %clang -fsyntax-only -fno-show-column %s 2>&1 | FileCheck %s --strict-whitespace -check-prefix=NO_COLUMN
-//
-// RUN: not %clang -fsyntax-only -Werror -fdiagnostics-format=msvc-fallback -fmsc-version=1300 %s 2>&1 | FileCheck %s --strict-whitespace -check-prefix=MSVC2010-FALLBACK
-// RUN: not %clang -fsyntax-only -Werror -fdiagnostics-format=msvc-fallback -fms-compatibility-version=13.00 %s 2>&1 | FileCheck %s --strict-whitespace -check-prefix=MSVC2010-FALLBACK
-// RUN: not %clang -fsyntax-only -Werror -fdiagnostics-format=msvc-fallback -fmsc-version=1800 %s 2>&1 | FileCheck %s --strict-whitespace -check-prefix=MSVC2013-FALLBACK
-// RUN: not %clang -fsyntax-only -Werror -fdiagnostics-format=msvc-fallback -fmsc-version=1900 %s 2>&1 | FileCheck %s --strict-whitespace -check-prefix=MSVC2015-FALLBACK
+
+
+
+
+
 
 
 
@@ -42,7 +42,4 @@
 // VI: {{.*}} +36:8: warning: extra tokens at end of #endif directive [-Wextra-tokens]
 // MSVC2015_ORIG: {{.*}}(36): warning: extra tokens at end of #endif directive [-Wextra-tokens]
 // NO_COLUMN: {{.*}}:36: warning: extra tokens at end of #endif directive [-Wextra-tokens]
-// MSVC2010-FALLBACK: {{.*}}(36,7) : error(clang): extra tokens at end of #endif directive
-// MSVC2013-FALLBACK: {{.*}}(36,8) : error(clang): extra tokens at end of #endif directive
-// MSVC2015-FALLBACK: {{.*}}(36,8): error(clang): extra tokens at end of #endif directive
 int x;
Index: clang/test/Driver/cl-pch.cpp
===
--- clang/test/Driver/cl-pch.cpp
+++ clang/test/Driver/cl-pch.cpp
@@ -333,39 +333,6 @@
 // uses the last one.  This is true for e.g. /Fo too, so not warning on this
 // is self-consistent with clang-cl's flag handling.
 
-// Interaction with /fallback
-
-// /Yc /fallback => /Yc not passed on (but /FI is)
-// RUN: %clang_cl -Werror /Ycpchfile.h /FIpchfile.h /Fpfoo.pch /fallback /c -### -- %s 2>&1 \
-// RUN:   | FileCheck -check-prefix=CHECK-YC-FALLBACK %s
-// Note that in /fallback builds, if creation of the pch fails the main compile
-// does still run so that /fallback can have an effect (this part is not tested)
-// CHECK-YC-FALLBACK: cc1
-// CHECK-YC-FALLBACK: -emit-obj
-// CHECK-YC-FALLBACK: -include-pch
-// CHECK-YC-FALLBACK: foo.pch
-// CHECK-YC-FALLBACK: ||
-// CHECK-YC-FALLBACK: cl.exe
-// CHECK-YC-FALLBACK-NOT: -include-pch
-// CHECK-YC-FALLBACK-NOT: /Ycpchfile.h
-// CHECK-YC-FALLBACK: /FIpchfile.h
-// CHECK-YC-FALLBACK-NOT: /Fpfoo.pch
-
-// /Yu /fallback => /Yu not passed on (but /FI is)
-// RUN: %clang_cl -Werror /Yupchfile.h /FIpchfile.h /Fpfoo.pch /fallback /c -### -- %s 2>&1 \
-// RUN:   | FileCheck -check-prefix=CHECK-YU-FALLBACK %s
-// CHECK-YU-FALLBACK-NOT: -emit-pch
-// CHECK-YU-FALLBACK: cc1
-// CHECK-YU-FALLBACK: -emit-obj
-// CHECK-YU-FALLBACK: -include-pch
-// CHECK-YU-FALLBACK: foo.pch
-// CHECK-YU-FALLBACK: ||
-// CHECK-YU-FALLBACK: cl.exe
-// CHECK-YU-FALLBACK-NOT: -include-pch
-// CHECK-YU-FALLBACK-NOT: /Yupchfile.h
-// CHECK-YU-FALLBACK: /FIpchfile.h
-// CHECK-YU-FALLBACK-NOT: /Fpfoo.pch
-
 // /FI without /Yu => pch file not used, even if it exists (different from
 // -include, which picks up .gch files if they exist).
 // RUN: touch %t.pch
Index: clang/test/Driver/cl-options.c
===
--- clang/test/Driver/cl-options.c
+++ clang/test/Driver/cl-options.c
@@ -530,8 +530,6 @@
 // NoDllExportInlines: "-fno-dllexport-inlines"
 // RUN: %clang_cl /Zc:dllexportInlines /c -### -- %s 2>&1 | FileCheck -check-prefix=DllExportInlines %s
 // DllExportInlines-NOT: "-fno-dllexport-inlines"
-// RUN: %clang_cl /fallback /Zc:dllexportInlines- /c -### -- %

[PATCH] D95876: [clang-cl] Remove the /fallback option

2021-02-03 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

Please take another look.




Comment at: clang/lib/Driver/ToolChains/MSVC.cpp:669
 const InputInfoList &Inputs, const ArgList &Args,
 const char *LinkingOutput) const {
   ArgStringList CmdArgs;

thakis wrote:
> Doesn't this whole function exist only for /fallback? In what other cases do 
> we need to invoke cl.exe?
D'oh, not sure how I missed this.


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

https://reviews.llvm.org/D95876

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


[clang] 7a45f27 - [OpenCL][Docs] Fix command line flag in the example.

2021-02-03 Thread Anastasia Stulova via cfe-commits

Author: Anastasia Stulova
Date: 2021-02-03T14:07:46Z
New Revision: 7a45f27ba156e311bf1deaa42761ec08d8e34d05

URL: 
https://github.com/llvm/llvm-project/commit/7a45f27ba156e311bf1deaa42761ec08d8e34d05
DIFF: 
https://github.com/llvm/llvm-project/commit/7a45f27ba156e311bf1deaa42761ec08d8e34d05.diff

LOG: [OpenCL][Docs] Fix command line flag in the example.

Fixed incorrect example of clang command line with
the builtin function declarations in OpenCLSupport.

Tags: #clang

Added: 


Modified: 
clang/docs/OpenCLSupport.rst

Removed: 




diff  --git a/clang/docs/OpenCLSupport.rst b/clang/docs/OpenCLSupport.rst
index 64109b7fab48..716ce9953e35 100644
--- a/clang/docs/OpenCLSupport.rst
+++ b/clang/docs/OpenCLSupport.rst
@@ -253,7 +253,7 @@ if full functionality is required.
 
 .. code-block:: console
  
-  $ clang -Xclang -finclude-default-header test.cl
+  $ clang -Xclang -fdeclare-opencl-builtins test.cl
 
 Note that this is a frontend-only flag and therefore it requires the use of
 flags that forward options to the frontend, e.g. ``-cc1`` or ``-Xclang``.



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


[PATCH] D95925: [clangd] Detect rename conflicits within enclosing scope

2021-02-03 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 321086.
kbobyrev marked 6 inline comments as done.
kbobyrev added a comment.

Resolve most comments but one: some comments & examples in the code incoming in
the next diff.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95925

Files:
  clang-tools-extra/clangd/refactor/Rename.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp

Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1010,13 +1010,68 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
-  {R"cpp(// FIXME: detecting local variables is not supported yet.
+  {R"cpp(
 void func() {
   int Conflict;
-  int [[V^ar]];
+  int V^ar;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int Conflict = 42) {
+int V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int Conflict = 42) {
+  } else {
+bool V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int V^ar = 42) {
+  } else {
+bool Conflict;
+  }
 }
   )cpp",
-   nullptr, !HeaderFile, nullptr, "Conflict"},
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  while (int V^ar = 10) {
+bool Conflict = true;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  for (int Something = 9000, Anything = 14, Conflict = 42; Anything > 9;
+   ++Something) {
+int V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func(int Conflict) {
+  bool V^ar;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
 
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -15,8 +15,14 @@
 #include "index/SymbolCollector.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/AST/ParentMapContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/None.h"
@@ -318,13 +324,85 @@
   return Results;
 }
 
+// Detect name conflict with othter DeclStmts in the same enclosing scope.
+const NamedDecl *lookupSiblingWithinEnclosingScope(ASTContext &Ctx,
+   const NamedDecl &RenamedDecl,
+   StringRef NewName) {
+  // Store Parents list outside of GetSingleParent, so that returned pointer is
+  // not invalidated.
+  DynTypedNodeList Parents(DynTypedNode::create(RenamedDecl));
+  auto GetSingleParent = [&](DynTypedNode Node) -> const DynTypedNode * {
+Parents = Ctx.getParents(Node);
+return (Parents.size() == 1) ? Parents.begin() : nullptr;
+  };
+  auto *Parent = GetSingleParent(DynTypedNode::create(RenamedDecl));
+  if (!Parent || !Parent->get())
+return nullptr;
+  Parent = GetSingleParent(*Parent);
+  // This helper checks if any statement within DeclStmt has NewName.
+  auto CheckDeclStmt = [&](const DeclStmt *DS,
+   StringRef Name) -> const NamedDecl * {
+if (!DS)
+  return nullptr;
+for (const auto &Child : DS->getDeclGroup())
+  if (const auto *ND = dyn_cast(Child))
+if (ND != &RenamedDecl && ND->getName() == Name)
+  return ND;
+return nullptr;
+  };
+  auto CheckCompoundStmt = [&](const Stmt *S,
+   StringRef Name) -> const NamedDecl * {
+if (const auto *CS = dyn_cast_or_null(S))
+  for (const auto *Node : CS->children())
+return CheckDeclStmt(dyn_cast(Node), Name);
+return nullptr;
+  };
+  // This helper checks if there is a condition variable has Name.
+  auto CheckConditionVariable = [&](const auto *Scope,
+StringRef Name) -> const NamedDecl * {
+if (!Scope)
+  return nullptr;
+return CheckDeclS

[PATCH] D95951: [OpenCL] Add cl_khr_subgroup_non_uniform_arithmetic to TableGen BIFs

2021-02-03 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh created this revision.
svenvh added a reviewer: Anastasia.
svenvh added a project: clang.
Herald added a subscriber: yaxunl.
svenvh requested review of this revision.
Herald added a subscriber: cfe-commits.

Add the builtin functions brought by the cl_khr_subgroup_non_uniform_arithmetic 
extension to `-fdeclare-opencl-builtins`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D95951

Files:
  clang/lib/Sema/OpenCLBuiltins.td
  clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl


Index: clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
===
--- clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -37,6 +37,7 @@
 // Enable extensions that are enabled in opencl-c-base.h.
 #if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 200)
 #define cl_khr_subgroup_ballot 1
+#define cl_khr_subgroup_non_uniform_arithmetic 1
 #endif
 #endif
 
@@ -140,11 +141,13 @@
 #endif
 }
 
-kernel void extended_subgroup(global uint4 *out) {
+kernel void extended_subgroup(global uint4 *out, global int *scalar) {
   out[0] = get_sub_group_eq_mask();
+  scalar[0] = sub_group_non_uniform_scan_inclusive_or(3);
 #if __OPENCL_C_VERSION__ < CL_VERSION_2_0 && !defined(__OPENCL_CPP_VERSION__)
-  // expected-error@-2{{implicit declaration of function 
'get_sub_group_eq_mask' is invalid in OpenCL}}
-  // expected-error@-3{{implicit conversion changes signedness}}
+  // expected-error@-3{{implicit declaration of function 
'get_sub_group_eq_mask' is invalid in OpenCL}}
+  // expected-error@-4{{implicit conversion changes signedness}}
+  // expected-error@-4{{implicit declaration of function 
'sub_group_non_uniform_scan_inclusive_or' is invalid in OpenCL}}
 #endif
 }
 
Index: clang/lib/Sema/OpenCLBuiltins.td
===
--- clang/lib/Sema/OpenCLBuiltins.td
+++ clang/lib/Sema/OpenCLBuiltins.td
@@ -55,6 +55,7 @@
 def FuncExtKhrSubgroups  : 
FunctionExtension<"cl_khr_subgroups">;
 def FuncExtKhrSubgroupNonUniformVote : 
FunctionExtension<"cl_khr_subgroup_non_uniform_vote">;
 def FuncExtKhrSubgroupBallot : 
FunctionExtension<"cl_khr_subgroup_ballot">;
+def FuncExtKhrSubgroupNonUniformArithmetic: 
FunctionExtension<"cl_khr_subgroup_non_uniform_arithmetic">;
 def FuncExtKhrSubgroupShuffle: 
FunctionExtension<"cl_khr_subgroup_shuffle">;
 def FuncExtKhrSubgroupShuffleRelative: 
FunctionExtension<"cl_khr_subgroup_shuffle_relative">;
 def FuncExtKhrGlobalInt32BaseAtomics : 
FunctionExtension<"cl_khr_global_int32_base_atomics">;
@@ -1523,7 +1524,19 @@
 }
 
 // Section 38.7.1 - cl_khr_subgroup_non_uniform_arithmetic
-// TODO
+let Extension = FuncExtKhrSubgroupNonUniformArithmetic in {
+  foreach name = ["reduce_", "scan_exclusive_", "scan_inclusive_"] in {
+foreach op = ["add", "min", "max", "mul"] in {
+  def : Builtin<"sub_group_non_uniform_" # name # op, [AGenType1, 
AGenType1]>;
+}
+foreach op = ["and", "or", "xor"] in {
+  def : Builtin<"sub_group_non_uniform_" # name # op, [AIGenType1, 
AIGenType1]>;
+}
+foreach op = ["and", "or", "xor"] in {
+  def : Builtin<"sub_group_non_uniform_" # name # "logical_" # op, [Int, 
Int]>;
+}
+  }
+}
 
 // Section 38.8.1 - cl_khr_subgroup_shuffle
 let Extension = FuncExtKhrSubgroupShuffle in {


Index: clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
===
--- clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -37,6 +37,7 @@
 // Enable extensions that are enabled in opencl-c-base.h.
 #if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 200)
 #define cl_khr_subgroup_ballot 1
+#define cl_khr_subgroup_non_uniform_arithmetic 1
 #endif
 #endif
 
@@ -140,11 +141,13 @@
 #endif
 }
 
-kernel void extended_subgroup(global uint4 *out) {
+kernel void extended_subgroup(global uint4 *out, global int *scalar) {
   out[0] = get_sub_group_eq_mask();
+  scalar[0] = sub_group_non_uniform_scan_inclusive_or(3);
 #if __OPENCL_C_VERSION__ < CL_VERSION_2_0 && !defined(__OPENCL_CPP_VERSION__)
-  // expected-error@-2{{implicit declaration of function 'get_sub_group_eq_mask' is invalid in OpenCL}}
-  // expected-error@-3{{implicit conversion changes signedness}}
+  // expected-error@-3{{implicit declaration of function 'get_sub_group_eq_mask' is invalid in OpenCL}}
+  // expected-error@-4{{implicit conversion changes signedness}}
+  // expected-error@-4{{implicit declaration of function 'sub_group_non_uniform_scan_inclusive_or' is invalid in OpenCL}}
 #endif
 }
 
Index: clang/lib/Sema/OpenCLBuiltins.td
===
--- clang/lib/Sema/OpenCLBuiltins.td
+++ clang/lib/Sema/OpenCLBuiltins.td
@@ -55,6 +55,7 @@
 def FuncExtKhrSubgroups  : FunctionExtension<"cl_khr_sub

[PATCH] D95877: [analyzer] Fix static_cast on pointer-to-member handling

2021-02-03 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD added a comment.






Comment at: clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp:226
+llvm::make_range(BaseList.begin(), BaseList.end()),
+[](const auto &I) -> bool { return I.second; });
+

vsavchenko wrote:
> I think it's all a bit too complicated now.
> 
> Right now you have two nested loops:
>   1. over `PathRange`
>   2. over `BaseList` (in `find_if`)
> 
> It won't be a problem to put them in another order, so when you make a 
> `filter_range`, you can have `llvm::find_if` which will iterate over 
> `PathRange` and captures the given `BaseList` element. So, yes nested lambdas.
> 
> Here is a sketch of the solution:
> ```
> auto BaseListFilteredRange = llvm::make_filter_range(
> BaseList, // you don't need to make_range here, BaseList IS a range
> [&PathRange](const CXXBaseSpecifier *Base) {
>   return llvm::find_if(PathRange, [Base](const auto &It) {
> return Base->getType() == It.first->getType();
>   }) == PathRange.end();
> });
> ```
> 
> Aaaand while I was writing that, it got me thinking that we don't need 
> `BaseList` in the first place:
> ```
> for (const CXXBaseSpecifier *Base : PathList)
>   if (llvm::none_of(PathRange,
> [Base](const auto &It) { return Base->getType() == 
> It.first->getType(); })
>   PathList = CXXBaseListFactory.add(Base, PathList);
> ```
Hmm, I really should brush up on my functional programming and think more in 
terms of STL/LLVM algorithms. Thank you for pointing out this solution, 
@vsavchenko!

One thing I noticed though, the shortened logic that you suggested removes all 
matching instances from PathList, while my intention was to remove only the 
first one of every kind. If there are no repetitions, it is the same. And, 
normally, repetitions should not be present in the PathList retrieved from PTM. 
It is a bug elsewhere if that happens. So should I add an assert for that here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95877

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


[PATCH] D95925: [clangd] Detect rename conflicits within enclosing scope

2021-02-03 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev added inline comments.



Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:355
+  // This helper checks if there is a condition variable has NewName.
+  auto CheckConditionVariable = [&](const auto *Scope) -> const NamedDecl * {
+if (!Scope)

hokein wrote:
> nit: explicit spell out the `auto` type?
That's the idea behind this helper: it's used both on `IfStmt` and `WhileStmt`, 
so the point here is that `getConditionVariableDeclStmt()` is available in both 
but not via interface/inheritance.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95925

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


[clang] e59d336 - [test] Use host platform specific error message substitution in lit tests - continued

2021-02-03 Thread Abhina Sreeskantharajan via cfe-commits

Author: Abhina Sreeskantharajan
Date: 2021-02-03T09:53:22-05:00
New Revision: e59d336e75f4670b1a702c2281b3fed27ba4c426

URL: 
https://github.com/llvm/llvm-project/commit/e59d336e75f4670b1a702c2281b3fed27ba4c426
DIFF: 
https://github.com/llvm/llvm-project/commit/e59d336e75f4670b1a702c2281b3fed27ba4c426.diff

LOG: [test] Use host platform specific error message substitution in lit tests 
- continued

On z/OS, other error messages are not matched correctly in lit tests.

```
EDC5121I Invalid argument.
EDC5111I Permission denied.
```

This patch adds a lit substitution to fix it.

Reviewed By: jhenderson

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

Added: 


Modified: 
clang/test/Analysis/taint-generic.c
clang/test/Format/style-on-command-line.cpp
lld/test/COFF/thinlto-emit-imports.ll
lld/test/ELF/lto/resolution-err.ll
lld/test/ELF/lto/thinlto-cant-write-index.ll
lld/test/ELF/lto/thinlto-emit-imports.ll
llvm/docs/TestingGuide.rst
llvm/test/tools/llvm-ar/error-opening-permission.test
llvm/test/tools/llvm-elfabi/fail-file-write.test
llvm/test/tools/yaml2obj/ELF/DWARF/debug-gnu-pubnames.yaml
llvm/utils/lit/lit/llvm/config.py

Removed: 




diff  --git a/clang/test/Analysis/taint-generic.c 
b/clang/test/Analysis/taint-generic.c
index 1cc1913eb9a8..2cbd580168ba 100644
--- a/clang/test/Analysis/taint-generic.c
+++ b/clang/test/Analysis/taint-generic.c
@@ -28,11 +28,11 @@
 // RUN:   -analyzer-checker=alpha.security.taint \
 // RUN:   -analyzer-config \
 // RUN: 
alpha.security.taint.TaintPropagation:Config=%S/Inputs/taint-generic-config-ill-formed.yaml
 \
-// RUN:   2>&1 | FileCheck %s -check-prefix=CHECK-ILL-FORMED
+// RUN:   2>&1 | FileCheck -DMSG=%errc_EINVAL %s -check-prefix=CHECK-ILL-FORMED
 
 // CHECK-ILL-FORMED: (frontend): invalid input for checker option
 // CHECK-ILL-FORMED-SAME:
'alpha.security.taint.TaintPropagation:Config',
-// CHECK-ILL-FORMED-SAME:that expects a valid yaml file: 
{{[Ii]}}nvalid argument
+// CHECK-ILL-FORMED-SAME:that expects a valid yaml file: [[MSG]]
 
 // RUN: not %clang_analyze_cc1 -verify %s \
 // RUN:   -analyzer-checker=alpha.security.taint \

diff  --git a/clang/test/Format/style-on-command-line.cpp 
b/clang/test/Format/style-on-command-line.cpp
index ba06babee35a..3fd89f587dc6 100644
--- a/clang/test/Format/style-on-command-line.cpp
+++ b/clang/test/Format/style-on-command-line.cpp
@@ -1,7 +1,7 @@
 // RUN: clang-format -style="{BasedOnStyle: Google, IndentWidth: 8}" %s | 
FileCheck -strict-whitespace -check-prefix=CHECK1 %s
 // RUN: clang-format -style="{BasedOnStyle: LLVM, IndentWidth: 7}" %s | 
FileCheck -strict-whitespace -check-prefix=CHECK2 %s
-// RUN: not clang-format -style="{BasedOnStyle: invalid, IndentWidth: 7}" 
-fallback-style=LLVM %s 2>&1 | FileCheck -strict-whitespace 
-check-prefix=CHECK3 %s
-// RUN: not clang-format -style="{lsjd}" %s -fallback-style=LLVM 2>&1 | 
FileCheck -strict-whitespace -check-prefix=CHECK4 %s
+// RUN: not clang-format -style="{BasedOnStyle: invalid, IndentWidth: 7}" 
-fallback-style=LLVM %s 2>&1 | FileCheck -DMSG=%errc_EINVAL -strict-whitespace 
-check-prefix=CHECK3 %s
+// RUN: not clang-format -style="{lsjd}" %s -fallback-style=LLVM 2>&1 | 
FileCheck -DMSG=%errc_EINVAL -strict-whitespace -check-prefix=CHECK4 %s
 // RUN: mkdir -p %t
 // RUN: printf "BasedOnStyle: google\nIndentWidth: 5\n" > %t/.clang-format
 // RUN: clang-format -style=file -assume-filename=%t/foo.cpp < %s | FileCheck 
-strict-whitespace -check-prefix=CHECK5 %s
@@ -24,8 +24,8 @@ void f() {
 // CHECK1: {{^int\* i;$}}
 // CHECK2: {{^   int \*i;$}}
 // CHECK3: Unknown value for BasedOnStyle: invalid
-// CHECK3: Error parsing -style: {{I|i}}nvalid argument
-// CHECK4: Error parsing -style: {{I|i}}nvalid argument
+// CHECK3: Error parsing -style: [[MSG]]
+// CHECK4: Error parsing -style: [[MSG]]
 // CHECK5: {{^ int\* i;$}}
 // CHECK6: {{^Error reading .*\.clang-format: (I|i)nvalid argument}}
 // CHECK7: {{^  int\* i;$}}

diff  --git a/lld/test/COFF/thinlto-emit-imports.ll 
b/lld/test/COFF/thinlto-emit-imports.ll
index 9ffe3b267701..a9f22c1dc2dc 100644
--- a/lld/test/COFF/thinlto-emit-imports.ll
+++ b/lld/test/COFF/thinlto-emit-imports.ll
@@ -34,8 +34,8 @@
 ; RUN: chmod 400 %t3.obj.imports
 ; RUN: not lld-link -entry:main -thinlto-index-only \
 ; RUN: -thinlto-emit-imports-files %t1.obj %t2.obj %t3.obj \
-; RUN: -out:%t4.exe 2>&1 | FileCheck %s --check-prefix=ERR
-; ERR: cannot open {{.*}}3.obj.imports: {{P|p}}ermission denied
+; RUN: -out:%t4.exe 2>&1 | FileCheck -DMSG=%errc_EACCES %s 
--check-prefix=ERR
+; ERR: cannot open {{.*}}3.obj.imports: [[MSG]]
 
 ; Ensure lld doesn't generate import files when thinlto-index-only is not 
enabled
 ; RUN: rm -f %t1.obj.imports

diff  --git a/lld/test/ELF/lto/resolution-err.ll 
b/lld/test/ELF/lto/resolution-err.ll
index 00cdd94059ac..ae07

[PATCH] D95808: [test] Use host platform specific error message substitution in lit tests - continued

2021-02-03 Thread Abhina Sree via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe59d336e75f4: [test] Use host platform specific error 
message substitution in lit tests… (authored by abhina.sreeskantharajan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95808

Files:
  clang/test/Analysis/taint-generic.c
  clang/test/Format/style-on-command-line.cpp
  lld/test/COFF/thinlto-emit-imports.ll
  lld/test/ELF/lto/resolution-err.ll
  lld/test/ELF/lto/thinlto-cant-write-index.ll
  lld/test/ELF/lto/thinlto-emit-imports.ll
  llvm/docs/TestingGuide.rst
  llvm/test/tools/llvm-ar/error-opening-permission.test
  llvm/test/tools/llvm-elfabi/fail-file-write.test
  llvm/test/tools/yaml2obj/ELF/DWARF/debug-gnu-pubnames.yaml
  llvm/utils/lit/lit/llvm/config.py

Index: llvm/utils/lit/lit/llvm/config.py
===
--- llvm/utils/lit/lit/llvm/config.py
+++ llvm/utils/lit/lit/llvm/config.py
@@ -349,12 +349,18 @@
 if (sys.platform == 'zos'):
 self.config.substitutions.append(('%errc_ENOENT', '\'EDC5129I No such file or directory.\''))
 self.config.substitutions.append(('%errc_EISDIR', '\'EDC5123I Is a directory.\''))
+self.config.substitutions.append(('%errc_EINVAL', '\'EDC5121I Invalid argument.\''))
+self.config.substitutions.append(('%errc_EACCES', '\'EDC5111I Permission denied.\''))
 elif (sys.platform == 'win32'):
 self.config.substitutions.append(('%errc_ENOENT', '\'no such file or directory\''))
 self.config.substitutions.append(('%errc_EISDIR', '\'is a directory\''))
+self.config.substitutions.append(('%errc_EINVAL', '\'invalid argument\''))
+self.config.substitutions.append(('%errc_EACCES', '\'permission denied\''))
 else:
 self.config.substitutions.append(('%errc_ENOENT', '\'No such file or directory\''))
 self.config.substitutions.append(('%errc_EISDIR', '\'Is a directory\''))
+self.config.substitutions.append(('%errc_EINVAL', '\'Invalid argument\''))
+self.config.substitutions.append(('%errc_EACCES', '\'Permission denied\''))
 
 def use_default_substitutions(self):
 tool_patterns = [
Index: llvm/test/tools/yaml2obj/ELF/DWARF/debug-gnu-pubnames.yaml
===
--- llvm/test/tools/yaml2obj/ELF/DWARF/debug-gnu-pubnames.yaml
+++ llvm/test/tools/yaml2obj/ELF/DWARF/debug-gnu-pubnames.yaml
@@ -225,12 +225,12 @@
 
 ## h) Test that yaml2obj emits an error if 'Descriptor' is missing.
 
-# RUN: not yaml2obj --docnum=8 %s -o %t8.o 2>&1 | FileCheck %s --check-prefix=MISSING-KEY --ignore-case
+# RUN: not yaml2obj --docnum=8 %s -o %t8.o 2>&1 | FileCheck -DMSG=%errc_EINVAL %s --check-prefix=MISSING-KEY --ignore-case
 
 #  MISSING-KEY: YAML:{{.*}}:9: error: missing required key 'Descriptor'
 # MISSING-KEY-NEXT:   - DieOffset: 0x12345678
 # MISSING-KEY-NEXT: ^
-# MISSING-KEY-NEXT: yaml2obj: error: failed to parse YAML input: Invalid argument
+# MISSING-KEY-NEXT: yaml2obj: error: failed to parse YAML input: [[MSG]]
 
 --- !ELF
 FileHeader:
Index: llvm/test/tools/llvm-elfabi/fail-file-write.test
===
--- llvm/test/tools/llvm-elfabi/fail-file-write.test
+++ llvm/test/tools/llvm-elfabi/fail-file-write.test
@@ -5,7 +5,7 @@
 # RUN: mkdir %t.TestDir
 # RUN: touch %t.TestDir/Output.TestFile
 # RUN: chmod 400 %t.TestDir
-# RUN: not llvm-elfabi %s --output-target=elf64-little %t.TestDir/Output.TestFile 2>&1 | FileCheck %s --check-prefix=ERR
+# RUN: not llvm-elfabi %s --output-target=elf64-little %t.TestDir/Output.TestFile 2>&1 | FileCheck -DMSG=%errc_EACCES %s --check-prefix=ERR
 # RUN: chmod 777 %t.TestDir
 # RUN: rm -rf %t.TestDir
 
@@ -15,4 +15,4 @@
 Symbols: {}
 ...
 
-# ERR: {{.*}}Permission denied{{.*}} when trying to open `{{.*}}.TestDir/Output.TestFile` for writing
+# ERR: [[MSG]] when trying to open `{{.*}}.TestDir/Output.TestFile` for writing
Index: llvm/test/tools/llvm-ar/error-opening-permission.test
===
--- llvm/test/tools/llvm-ar/error-opening-permission.test
+++ llvm/test/tools/llvm-ar/error-opening-permission.test
@@ -9,6 +9,6 @@
 # RUN: llvm-ar rc %t/permission.b %t/1.txt
 # RUN: chmod 100 %t/permission.b
 # RUN: not llvm-ar p %t/permission.b 2>&1 | \
-# RUN:   FileCheck %s --check-prefix=NO-PERMISSION -DARCHIVE=%t/permission.b
+# RUN:   FileCheck %s --check-prefix=NO-PERMISSION -DARCHIVE=%t/permission.b -DMSG=%errc_EACCES
 
-# NO-PERMISSION: error: unable to open '[[ARCHIVE]]': {{.*}}{{[pP]}}ermission denied
+# NO-PERMISSION: error: unable to open '[[ARCHIVE]]': [[MSG]]
Index: llvm/docs/TestingGuide.rst
===

[PATCH] D95877: [analyzer] Fix static_cast on pointer-to-member handling

2021-02-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp:226
+llvm::make_range(BaseList.begin(), BaseList.end()),
+[](const auto &I) -> bool { return I.second; });
+

RedDocMD wrote:
> vsavchenko wrote:
> > I think it's all a bit too complicated now.
> > 
> > Right now you have two nested loops:
> >   1. over `PathRange`
> >   2. over `BaseList` (in `find_if`)
> > 
> > It won't be a problem to put them in another order, so when you make a 
> > `filter_range`, you can have `llvm::find_if` which will iterate over 
> > `PathRange` and captures the given `BaseList` element. So, yes nested 
> > lambdas.
> > 
> > Here is a sketch of the solution:
> > ```
> > auto BaseListFilteredRange = llvm::make_filter_range(
> > BaseList, // you don't need to make_range here, BaseList IS a range
> > [&PathRange](const CXXBaseSpecifier *Base) {
> >   return llvm::find_if(PathRange, [Base](const auto &It) {
> > return Base->getType() == It.first->getType();
> >   }) == PathRange.end();
> > });
> > ```
> > 
> > Aaaand while I was writing that, it got me thinking that we don't need 
> > `BaseList` in the first place:
> > ```
> > for (const CXXBaseSpecifier *Base : PathList)
> >   if (llvm::none_of(PathRange,
> > [Base](const auto &It) { return Base->getType() == 
> > It.first->getType(); })
> >   PathList = CXXBaseListFactory.add(Base, PathList);
> > ```
> Hmm, I really should brush up on my functional programming and think more in 
> terms of STL/LLVM algorithms. Thank you for pointing out this solution, 
> @vsavchenko!
> 
> One thing I noticed though, the shortened logic that you suggested removes 
> all matching instances from PathList, while my intention was to remove only 
> the first one of every kind. If there are no repetitions, it is the same. 
> And, normally, repetitions should not be present in the PathList retrieved 
> from PTM. It is a bug elsewhere if that happens. So should I add an assert 
> for that here?
Yes, that's true.
Assertions will usually make intensions of the original author more clear for 
future readers.
Plus, I think it can be also good to add a comment (something similar to your 
summary for this change) to describe what is going on here and WHY it is done.



Comment at: clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp:531-532
+  svalBuilder.makePointerToMember(getBasicVals().accumCXXBase(
   llvm::make_range(
-  CastE->path_begin(), CastE->path_end()), *PTMSV));
+  CastE->path_begin(), CastE->path_end()),
+  *PTMSV, CastE->getCastKind()));

BTW, it looks like this can be replaced by `CastE->path()`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95877

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


[PATCH] D95925: [clangd] Detect rename conflicits within enclosing scope

2021-02-03 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 321095.
kbobyrev marked an inline comment as done.
kbobyrev added a comment.

Add comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95925

Files:
  clang-tools-extra/clangd/refactor/Rename.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp

Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1010,13 +1010,68 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
-  {R"cpp(// FIXME: detecting local variables is not supported yet.
+  {R"cpp(
 void func() {
   int Conflict;
-  int [[V^ar]];
+  int V^ar;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int Conflict = 42) {
+int V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int Conflict = 42) {
+  } else {
+bool V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  if (int V^ar = 42) {
+  } else {
+bool Conflict;
+  }
 }
   )cpp",
-   nullptr, !HeaderFile, nullptr, "Conflict"},
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  while (int V^ar = 10) {
+bool Conflict = true;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func() {
+  for (int Something = 9000, Anything = 14, Conflict = 42; Anything > 9;
+   ++Something) {
+int V^ar;
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func(int Conflict) {
+  bool V^ar;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
 
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -15,8 +15,14 @@
 #include "index/SymbolCollector.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/AST/ParentMapContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/None.h"
@@ -318,13 +324,100 @@
   return Results;
 }
 
+// Detect name conflict with othter DeclStmts in the same enclosing scope.
+const NamedDecl *lookupSiblingWithinEnclosingScope(ASTContext &Ctx,
+   const NamedDecl &RenamedDecl,
+   StringRef NewName) {
+  // Store Parents list outside of GetSingleParent, so that returned pointer is
+  // not invalidated.
+  DynTypedNodeList Parents(DynTypedNode::create(RenamedDecl));
+  auto GetSingleParent = [&](DynTypedNode Node) -> const DynTypedNode * {
+Parents = Ctx.getParents(Node);
+return (Parents.size() == 1) ? Parents.begin() : nullptr;
+  };
+
+  // We need to get to the enclosing scope: NamedDecl's parent is typically
+  // DeclStmt, so enclosing scope would be the second order parent.
+  auto *Parent = GetSingleParent(DynTypedNode::create(RenamedDecl));
+  if (!Parent || !Parent->get())
+return nullptr;
+  Parent = GetSingleParent(*Parent);
+
+  // The following helpers check corresponding AST nodes for variable
+  // declarations with the name collision.
+  auto CheckDeclStmt = [&](const DeclStmt *DS,
+   StringRef Name) -> const NamedDecl * {
+if (!DS)
+  return nullptr;
+for (const auto &Child : DS->getDeclGroup())
+  if (const auto *ND = dyn_cast(Child))
+if (ND != &RenamedDecl && ND->getName() == Name)
+  return ND;
+return nullptr;
+  };
+  auto CheckCompoundStmt = [&](const Stmt *S,
+   StringRef Name) -> const NamedDecl * {
+if (const auto *CS = dyn_cast_or_null(S))
+  for (const auto *Node : CS->children())
+return CheckDeclStmt(dyn_cast(Node), Name);
+return nullptr;
+  };
+  auto CheckConditionVariable = [&](const auto *Scope,
+StringRef Name) -> const NamedDecl * {
+if (!Scope)

[PATCH] D89870: [clangd] Drop template argument lists from completions followed by

2021-02-03 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev added a comment.

@sammccall Ping, this is a real patch :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89870

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


[clang] 0682903 - Revert "[ConstantFold] Fold more operations to poison"

2021-02-03 Thread Juneyoung Lee via cfe-commits

Author: Juneyoung Lee
Date: 2021-02-04T00:24:02+09:00
New Revision: 06829034ca64b8c83a5b20d8abe5ddbfe7af0004

URL: 
https://github.com/llvm/llvm-project/commit/06829034ca64b8c83a5b20d8abe5ddbfe7af0004
DIFF: 
https://github.com/llvm/llvm-project/commit/06829034ca64b8c83a5b20d8abe5ddbfe7af0004.diff

LOG: Revert "[ConstantFold] Fold more operations to poison"

This reverts commit 53040a968dc2ff20931661e55f05da2ef8b964a0 due to its
bad interaction with select i1 -> and/or i1 transformation.

This fixes:
https://bugs.llvm.org/show_bug.cgi?id=49005
https://bugs.llvm.org/show_bug.cgi?id=48435

Added: 


Modified: 
clang/test/Frontend/fixed_point_unary.c
llvm/lib/IR/ConstantFold.cpp
llvm/test/CodeGen/AMDGPU/amdgpu-codegenprepare-fold-binop-select.ll
llvm/test/Transforms/InstCombine/apint-shift.ll
llvm/test/Transforms/InstCombine/canonicalize-ashr-shl-to-masking.ll
llvm/test/Transforms/InstCombine/canonicalize-lshr-shl-to-masking.ll
llvm/test/Transforms/InstCombine/canonicalize-shl-lshr-to-masking.ll
llvm/test/Transforms/InstCombine/icmp.ll

llvm/test/Transforms/InstCombine/partally-redundant-left-shift-input-masking-after-truncation-variant-a.ll

llvm/test/Transforms/InstCombine/partally-redundant-left-shift-input-masking-after-truncation-variant-b.ll

llvm/test/Transforms/InstCombine/partally-redundant-left-shift-input-masking-after-truncation-variant-c.ll

llvm/test/Transforms/InstCombine/partally-redundant-left-shift-input-masking-after-truncation-variant-d.ll

llvm/test/Transforms/InstCombine/partally-redundant-left-shift-input-masking-after-truncation-variant-e.ll

llvm/test/Transforms/InstCombine/partally-redundant-left-shift-input-masking-variant-a.ll

llvm/test/Transforms/InstCombine/partally-redundant-left-shift-input-masking-variant-b.ll

llvm/test/Transforms/InstCombine/partally-redundant-left-shift-input-masking-variant-c.ll

llvm/test/Transforms/InstCombine/partally-redundant-left-shift-input-masking-variant-d.ll

llvm/test/Transforms/InstCombine/partally-redundant-left-shift-input-masking-variant-e.ll
llvm/test/Transforms/InstCombine/select-of-bittest.ll
llvm/test/Transforms/InstCombine/shift-add-inseltpoison.ll
llvm/test/Transforms/InstCombine/shift-add.ll
llvm/test/Transforms/InstSimplify/ConstProp/InsertElement-inseltpoison.ll
llvm/test/Transforms/InstSimplify/ConstProp/InsertElement.ll
llvm/test/Transforms/InstSimplify/ConstProp/cast.ll
llvm/test/Transforms/InstSimplify/ConstProp/poison.ll
llvm/test/Transforms/InstSimplify/ConstProp/shift.ll

llvm/test/Transforms/InstSimplify/ConstProp/vector-undef-elts-inseltpoison.ll
llvm/test/Transforms/InstSimplify/ConstProp/vector-undef-elts.ll
llvm/test/Transforms/InstSimplify/ConstProp/vscale-inseltpoison.ll
llvm/test/Transforms/InstSimplify/ConstProp/vscale.ll
llvm/test/Transforms/InstSimplify/div.ll
llvm/test/Transforms/InstSimplify/rem.ll
llvm/test/Transforms/InstSimplify/undef.ll
llvm/test/Transforms/SROA/phi-gep.ll
llvm/test/Transforms/SROA/select-gep.ll
llvm/test/Transforms/VectorCombine/X86/insert-binop-inseltpoison.ll
llvm/test/Transforms/VectorCombine/X86/insert-binop-with-constant.ll
llvm/test/Transforms/VectorCombine/X86/insert-binop.ll
llvm/unittests/IR/ConstantsTest.cpp

Removed: 




diff  --git a/clang/test/Frontend/fixed_point_unary.c 
b/clang/test/Frontend/fixed_point_unary.c
index 6ce760daba11..849e38a94bc4 100644
--- a/clang/test/Frontend/fixed_point_unary.c
+++ b/clang/test/Frontend/fixed_point_unary.c
@@ -90,7 +90,7 @@ void inc_usa() {
 // SIGNED-LABEL: @inc_uf(
 // SIGNED-NEXT:  entry:
 // SIGNED-NEXT:[[TMP0:%.*]] = load i16, i16* @uf, align 2
-// SIGNED-NEXT:[[TMP1:%.*]] = add i16 [[TMP0]], poison
+// SIGNED-NEXT:[[TMP1:%.*]] = add i16 [[TMP0]], undef
 // SIGNED-NEXT:store i16 [[TMP1]], i16* @uf, align 2
 // SIGNED-NEXT:ret void
 //
@@ -271,7 +271,7 @@ void dec_usa() {
 // SIGNED-LABEL: @dec_uf(
 // SIGNED-NEXT:  entry:
 // SIGNED-NEXT:[[TMP0:%.*]] = load i16, i16* @uf, align 2
-// SIGNED-NEXT:[[TMP1:%.*]] = sub i16 [[TMP0]], poison
+// SIGNED-NEXT:[[TMP1:%.*]] = sub i16 [[TMP0]], undef
 // SIGNED-NEXT:store i16 [[TMP1]], i16* @uf, align 2
 // SIGNED-NEXT:ret void
 //

diff  --git a/llvm/lib/IR/ConstantFold.cpp b/llvm/lib/IR/ConstantFold.cpp
index 03cb108cc485..95dd55237e5f 100644
--- a/llvm/lib/IR/ConstantFold.cpp
+++ b/llvm/lib/IR/ConstantFold.cpp
@@ -630,7 +630,7 @@ Constant *llvm::ConstantFoldCastInstruction(unsigned opc, 
Constant *V,
   V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored)) {
 // Undefined behavior invoked - the destination type can't represent
 // the input constant.
-return PoisonValue::get(DestTy);
+return UndefValue::get(DestTy);
   }
   return ConstantInt::get(FPC->getConte

[PATCH] D92270: [ConstantFold] Fold more operations to poison

2021-02-03 Thread Juneyoung Lee via Phabricator via cfe-commits
aqjune added a comment.

In D92270#2538713 , @RKSimon wrote:

> https://bugs.llvm.org/show_bug.cgi?id=49005 seems to be due to this (either 
> directly or it has unearthed an existing problem)

I reverted this commit; I'll reland this after the underlying problem is 
resolved.
I'll push the revert commit to 12.x branch as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92270

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


[PATCH] D88299: [clang-format] Add MacroUnexpander.

2021-02-03 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Thanks a lot for all the time explaining, I get this at least at a high level 
now.
I have trouble following the ins and outs of the algorithm, but I think I 
understand most of it and tests cover the rest.

Regarding tests: I have trouble reasoning about whether all cases are tested. I 
wonder if we can easily throw this against (internal) coverage + mutation 
testing infrastructure? I'm not a massive believer in that stuff usually, but 
this seems like a good candidate.

Lots of comments around making this easier for confused people like me to 
understand, partly because I don't understand it well enough to suggest more 
substantive changes.
Throughout, I think it'd be nice to be explicit about:

- which structure tokens/lines are part of: spelled/expanded/unexpanded. 
(Including getting rid of input/output/incoming/original, which AFAICT are 
synonyms for these)
- which lines are complete, and which are partial (being added to as we go)

It took me a while to understand the control flow and to tell "who's driving" - 
I think it was hard for me to see that processNextUnexpanded was basically a 
leaf, and that 
unexpand/startUnexpansion/endUnexpansion/continueUnexpansionUntil were the 
layer above, and add() was the top. Maybe there's naming that would clarify 
this better, but I don't have great suggestions, and I'm not sure if this is a 
problem other people would have.
Maybe an example trace showing the internal method calls when parsing a small 
example might help... but again, not sure.




Comment at: clang/lib/Format/MacroUnexpander.cpp:52
+// the token, its parent and whether it is the first token in the line.
+void MacroUnexpander::forEachToken(
+const UnwrappedLine &Line,

this doesn't use any state, right?

it could be static or even private to the impl file.

replacing std::function with a template param allow this loop to be specialized 
for the one callsite - up to you, maybe it doesn't matter much, but it's not 
very invasive



Comment at: clang/lib/Format/MacroUnexpander.cpp:66
+
+// Unexand \p Token, given its parent \p OriginalParent in the incoming
+// unwrapped line. \p First specifies whether it is the first token in a given

I find using all of spelled/expanded/unexpanded, 
input/incoming/output/outgoing, and original, unclear.
(Particularly after OriginalParent is propagated around by that name without 
comment, and because "original" refers to the expanded structure, which is 
*not* the first one created)
Can we call this "ExpandedParent in the expanded unwrapped line"?



Comment at: clang/lib/Format/MacroUnexpander.cpp:66
+
+// Unexand \p Token, given its parent \p OriginalParent in the incoming
+// unwrapped line. \p First specifies whether it is the first token in a given

sammccall wrote:
> I find using all of spelled/expanded/unexpanded, 
> input/incoming/output/outgoing, and original, unclear.
> (Particularly after OriginalParent is propagated around by that name without 
> comment, and because "original" refers to the expanded structure, which is 
> *not* the first one created)
> Can we call this "ExpandedParent in the expanded unwrapped line"?
Unexand -> unexpand



Comment at: clang/lib/Format/MacroUnexpander.cpp:77
+  // stream, we need to continue the unexpansion until we find the right token
+  // if it is part of the unexpanded token stream.
+  // Note that hidden tokens can be part of the unexpanded stream in nested

I can't work out what "it" refers to in this sentence.

(and "spelled" token stream?)



Comment at: clang/lib/Format/MacroUnexpander.cpp:80
+  // macro calls.
+  // For example, given: BRACED(a) {a}
+  // And the call: BRACED(BRACED(x))

(in these examples throughout, #define BRACED(a) {a} would make it clearer that 
this is a macro definition and not code)



Comment at: clang/lib/Format/MacroUnexpander.cpp:82
+  // And the call: BRACED(BRACED(x))
+  // The outer macro call will be BRACED({a}), and the hidden tokens '{' and
+  // '}' can be found in the unexpanded macro stream of that level.

It would be helpful to complete the example by spelling out which token you're 
adding, which the correct parent is, and which tokens you need to "expand over" 
to make it available.

I *think* the answer to the first two is - when you're adding the `a` then its 
proper parent is the inner `(` in `BRACED(BRACED(`... but I don't know the last 
part.



Comment at: clang/lib/Format/MacroUnexpander.cpp:84
+  // '}' can be found in the unexpanded macro stream of that level.
+  if (!Unexpanded.empty() && Token->MacroCtx &&
+  (Token->MacroCtx->Role != MR_Hidden ||

is it possible that you may need to unexpand more than the innermost macro?

e.g. BRACED(ID(ID(BRACED(ID(ID(a)) expands to {{a}} and the parents o

[PATCH] D95948: Stop traping on sNaN in __builtin_isnan

2021-02-03 Thread Melanie Blower via Phabricator via cfe-commits
mibintc added inline comments.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:2988
 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
-// FIXME: for strictfp/IEEE-754 we need to not trap on SNaN here.
 Value *V = EmitScalarExpr(E->getArg(0));

What about all the other FIXME related to strictfp, are we going to pick them 
off piecemeal? It would be nice to have a holistic approach, it would be more 
clear, and less duplicated code. For example, presumably the test at line 2991 
is common.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:3001
+// NaN has all exp bits set and a non zero significand. Therefore:
+// isnan(V) == ((abs(V) & exp mask) - exp mask < 0)
+unsigned bitsize = Ty->getScalarSizeInBits();

Are you using a reference (e.g. existing implementation) for this rewrite, or 
is this invention? If a reference can you please tell me what it is.  The 
expression you have written here doesn't match the codegen below. I don't see 
the comparison to zero. Can you provide full parenthesization--the compare to 
zero is lower than subtract?



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:3010
+Value *Sub =
+Builder.CreateSub(llvm::ConstantInt::get(IntTy, ExpMask), AbsV);
+V = Builder.CreateLShr(Sub, llvm::ConstantInt::get(IntTy, bitsize - 1));

compared to the comment above at line 3001, lhs and rhs are swapped in the sub



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:3011
+Builder.CreateSub(llvm::ConstantInt::get(IntTy, ExpMask), AbsV);
+V = Builder.CreateLShr(Sub, llvm::ConstantInt::get(IntTy, bitsize - 1));
+if (bitsize > 32)

the comment at line 3001 doesn't show the lshr or the compare to zero



Comment at: clang/test/CodeGen/X86/strictfp_builtins.c:1
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 %s -emit-llvm -ffp-exception-behavior=maytrap -o - -triple 
x86_64-unknown-unknown | FileCheck %s

Why did you put long double into this new test case instead of putting it with 
the float and double in strictfp_builtins?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95948

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


[PATCH] D95942: [clangd] Deduplicate scopes in IncludeFixer queries

2021-02-03 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/IncludeFixer.cpp:322
 
-  Scopes.push_back("");
+  std::set Scopes;
+  Scopes.insert("");

nit: sort+erase-unique is probably cheaper than constructing a set and then 
copying it

(probably not a huge deal but we do this for each typo I think)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95942

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


[PATCH] D93787: [analyzer] Fix crash caused by accessing empty map

2021-02-03 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D93787#2539111 , @vabridgers wrote:

> Abandoning this change request in favor of  @steakhal 's more comprehensive 
> change @  https://reviews.llvm.org/D93222

Let me know if that patch-stack resolves your crash.
I don't mind extending the macro expansion test cases, it's a tricky area.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93787

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


[PATCH] D89909: [SYCL] Implement SYCL address space attributes handling

2021-02-03 Thread Alexey Bader via Phabricator via cfe-commits
bader added a comment.

> Anastasia added a comment.
> In D89909#2536331  
> https://reviews.llvm.org/D89909#2536331, @bader wrote:
>
>> In D89909#2536157  
>> https://reviews.llvm.org/D89909#2536157, @Anastasia wrote:
>>
>>> In D89909#2534790  
>>> https://reviews.llvm.org/D89909#2534790, @bader wrote:
>>>
> Regarding SYCLDevice and SYCLAddrSpaceMap I am still not very convinced 
> about the flow. Have you had any design discussion regarding this already 
> that you could point to?

 We discussed this with you in https://github.com/intel/llvm/pull/1039/.
>>>
>>> I can't see.
>>
>> The mapping has been discussed in this comment: 
>> https://github.com/intel/llvm/pull/1039/#discussion_r369667791.
>
> The discussion you cite is in the separate Github project, but you should 
> have a discussion using LLVM channels about the design you propose for 
> llvm-project repo. Also I don't think citing resources with many comments and 
> no conclusions is making the review process very productive.

Sorry, I forgot to mentioned that this change was also discussed in the mailing 
list: 
http://clang-developers.42468.n3.nabble.com/RFC-Re-use-OpenCL-address-space-attributes-for-SYCL-td4068754.html.
There are no objections from the community.

What is not covered by this thread and probably worth to discuss separately is 
changing `OpenCL private` mapping to non-zero LLVM AS to avoid the mangler 
component change. I expect significant impact on SPIR LLVM IR consumers and 
long transition period if the change is accepted.

> My main concern is that I am not sure it fits with the main design of 
> Clang - producing IR that is to be consumed by multiple targets rather 
> than only one specific target or even an external tool. Why do you add a 
> triple component that is used only for one target SPIR:
>
> How would existing toolchains that consume LLVM-IR for SPIR cope with the 
> fact that the Default address space is different for C++ and SYCL.

 High level languages differences doesn't matter for toolchains consuming 
 LLVM IR - it can python, D or SYCL. Toolchains are assuming that LLVM IR 
 follows the sematic defined in SPIR-1.2 document - 
 https://www.khronos.org/registry/SPIR/specs/spir_spec-1.2.pdf.
>>>
>>> I can't understand what you mean by "doesn't matter"?
>>
>> LLVM has it's own sematic which toolchains rely on. Toolchains consuming 
>> LLVM IR doesn't know if this LLVM IR was emitted by C++ compiler or written 
>> manually - they can rely only on LLVM IR semantic defined by 
>> https://llvm.org/docs/LangRef.html.
>>
>>> If you compiler from C++ you get one address space as `Default` and if you 
>>> compile from SYCL you get a different one for the same target - how do you 
>>> expect the toolchain consuming the IR to handle that?
>>
>> Technically clang changes SPIR target mapping for Default address space only 
>> for `sycldevice` environment component of the target triple, so it doesn't 
>> depend on the input language i.e. Default is mapped to the same LLVM address 
>> space for C++ and SYCL.
>
> If you are suggesting to add SYCL as a component for other languages 
> supported by clang this deserves a separate review probably with different 
> reviewers and a wider discussion with the community.

No, but clang doesn't couple input language with environment component of the 
target triple. As I mentioned above, community doesn't have any objections to 
this approach.

>>> FYI, the document is no longer describing the current SPIR target 
>>> adequately as implementation deviated quite a bit from the original 
>>> documentation.
>>
>> This is unfortunate. Do you know if there are any plans to provide 
>> up-to-date documentation? It's critical for non-clang front-ends targeting 
>> SPIR-V format.
>
> I am not aware of any plan. FYI SPIR has not been added or designed for 
> SPIR-V. It is only used for SPIR-V as a workaround by some external projects 
> but it is not the only use case even if perhaps an important one for the 
> community.

I'm aware of SPIR target history and design - I was on the team contributed 
SPIR-1.2 support to clang, although I was involved into compiler back-end 
development.
We designed and contributed SPIR-1.2 support to clang aiming to provide a tool 
producing stable portable binary format for OpenCL programs.
SPIR format evolved from SPIR-1.2 to SPIR-V, which is not based on LLVM-based, 
but AFAIK the goal of SPIR target in clang tool has not changed and it is still 
to produce binary format for Khronos APIs (even though part of the toolchain is 
hosted outside of LLVM project).
It's great if there are other uses of SPIR target in LLVM project. Do you know 
where I can learn more about this?

> Why is changing of `the address space map necessary for SPIR but not the 
> other targets?

[PATCH] D95948: Stop traping on sNaN in __builtin_isnan

2021-02-03 Thread Thomas Preud'homme via Phabricator via cfe-commits
thopre marked 2 inline comments as done.
thopre added inline comments.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:2988
 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
-// FIXME: for strictfp/IEEE-754 we need to not trap on SNaN here.
 Value *V = EmitScalarExpr(E->getArg(0));

mibintc wrote:
> What about all the other FIXME related to strictfp, are we going to pick them 
> off piecemeal? It would be nice to have a holistic approach, it would be more 
> clear, and less duplicated code. For example, presumably the test at line 
> 2991 is common.
I do want to do isinf and other similar builtin but I would prefer to have a 
review of this to see if there's anything wrong with my approach before I work 
on other builtins. Once I do I'll factor things out as needed.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:3010
+Value *Sub =
+Builder.CreateSub(llvm::ConstantInt::get(IntTy, ExpMask), AbsV);
+V = Builder.CreateLShr(Sub, llvm::ConstantInt::get(IntTy, bitsize - 1));

mibintc wrote:
> compared to the comment above at line 3001, lhs and rhs are swapped in the sub
My bad, the comment needs to be fixed.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:3011
+Builder.CreateSub(llvm::ConstantInt::get(IntTy, ExpMask), AbsV);
+V = Builder.CreateLShr(Sub, llvm::ConstantInt::get(IntTy, bitsize - 1));
+if (bitsize > 32)

mibintc wrote:
> the comment at line 3001 doesn't show the lshr or the compare to zero
This logical right shift will move the sign bit to bit0 and set all other bits 
to 0. The result will be 1 (true) if sign bit is set (sub is negative) or 0 
(false) otherwise. That matches the comment. Would you like me to add a comment 
here to make it more explicit?



Comment at: clang/test/CodeGen/X86/strictfp_builtins.c:1
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 %s -emit-llvm -ffp-exception-behavior=maytrap -o - -triple 
x86_64-unknown-unknown | FileCheck %s

mibintc wrote:
> Why did you put long double into this new test case instead of putting it 
> with the float and double in strictfp_builtins?
long double is implemented differently for each target. x86 uses an 80 bit 
extended precision format, AFAIK AArch64 uses a 128bit IEEE format, etc.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95948

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


[PATCH] D95948: Stop traping on sNaN in __builtin_isnan

2021-02-03 Thread Thomas Preud'homme via Phabricator via cfe-commits
thopre marked 2 inline comments as done.
thopre added inline comments.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:2995
+Builder.getDefaultConstrainedExcept() == fp::ebIgnore ||
+!Ty->isIEEE()) {
+  V = Builder.CreateFCmpUNO(V, V, "cmp");

I'm not too sure if that's enough to check isIEEE here. x86 extended precision 
behaves a bit different to IEEE single and double precision, esp. wrt. infinite 
and NaN. I've decided to ignore NaN values that are deprecated since the 8087.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:3001
+// NaN has all exp bits set and a non zero significand. Therefore:
+// isnan(V) == ((abs(V) & exp mask) - exp mask < 0)
+unsigned bitsize = Ty->getScalarSizeInBits();

mibintc wrote:
> Are you using a reference (e.g. existing implementation) for this rewrite, or 
> is this invention? If a reference can you please tell me what it is.  The 
> expression you have written here doesn't match the codegen below. I don't see 
> the comparison to zero. Can you provide full parenthesization--the compare to 
> zero is lower than subtract?
I've noticed glibc isnan implementation does not trigger a trap so I've looked 
at the assembly it generates for the float case. This is the generalized 
version for double and long double as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95948

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


[PATCH] D94745: [OpenMP][deviceRTLs] Build the deviceRTLs with OpenMP instead of target dependent language

2021-02-03 Thread Joachim Protze via Phabricator via cfe-commits
protze.joachim added a comment.

For me this patch breaks building llvm. Before this patch, I successfully built 
llvm using a llvm/10 installation on the system. What is probably special with 
our llvm installation is that we by default use libc++ rather than libstdc++.

  FAILED: 
projects/openmp/libomptarget/deviceRTLs/nvptx/loop.cu-cuda_110-sm_60.bc 
  cd BUILD/projects/openmp/libomptarget/deviceRTLs/nvptx && 
/home/pj416018/sw/UTIL/ccache/bin/clang -S -x c++ -target nvptx64 -Xclang 
-emit-llvm-bc -Xclang -aux-triple -Xclang x86_64-unknown-linux-gnu -fopenmp 
-fopenmp-cuda-mode -Xclang -fopenmp-is-device -D__CUDACC__ 
-I${llvm-SOURCE}/openmp/libomptarget/deviceRTLs 
-I${llvm-SOURCE}/openmp/libomptarget/deviceRTLs/nvptx/src 
-DOMPTARGET_NVPTX_DEBUG=0 -Xclang -target-cpu -Xclang sm_60 -D__CUDA_ARCH__=600 
-Xclang -target-feature -Xclang +ptx70 -DCUDA_VERSION=11000 
${llvm-SOURCE}/openmp/libomptarget/deviceRTLs/common/src/loop.cu -o 
loop.cu-cuda_110-sm_60.bc
  In file included from 
${llvm-SOURCE}/openmp/libomptarget/deviceRTLs/common/src/loop.cu:16:
  In file included from 
${llvm-SOURCE}/openmp/libomptarget/deviceRTLs/common/omptarget.h:18:
  In file included from 
${llvm-SOURCE}/openmp/libomptarget/deviceRTLs/common/debug.h:31:
  In file included from 
${llvm-SOURCE}/openmp/libomptarget/deviceRTLs/common/device_environment.h:16:
  In file included from 
${llvm-SOURCE}/openmp/libomptarget/deviceRTLs/nvptx/src/target_impl.h:18:
  In file included from 
${llvm-INSTALL}/10.0.0/bin/../include/c++/v1/stdlib.h:100:
  In file included from ${llvm-INSTALL}/10.0.0/bin/../include/c++/v1/math.h:312:
  ${llvm-INSTALL}/10.0.0/bin/../include/c++/v1/limits:406:89: error: host 
requires 128 bit size 'std::__1::__libcpp_numeric_limits::type' (aka 'long double') type support, but device 'nvptx64' does not 
support it
  _LIBCPP_INLINE_VISIBILITY static _LIBCPP_CONSTEXPR type lowest() 
_NOEXCEPT {return -max();}

  ^

My cmake call looks like:

  cmake -GNinja -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=$INSTALLDIR \
-DLLVM_ENABLE_LIBCXX=ON \
-DCLANG_DEFAULT_CXX_STDLIB=libc++ \
-DCLANG_OPENMP_NVPTX_DEFAULT_ARCH=sm_70 \
-DLIBOMPTARGET_ENABLE_DEBUG=on \
-DLIBOMPTARGET_NVPTX_ENABLE_BCLIB=true \
-DLIBOMPTARGET_NVPTX_COMPUTE_CAPABILITIES=35,60,70 \

-DLLVM_ENABLE_PROJECTS="clang;compiler-rt;libcxxabi;libcxx;libunwind;openmp" \
-DCMAKE_BUILD_WITH_INSTALL_RPATH=ON \
$LLVM_SOURCE

I also tried to build using my newest installed llvm build 
(7dd198852b4db52ae22242dfeda4eccda83aa8b2 
):

  In file included from 
${llvm-SOURCE}/openmp/libomptarget/deviceRTLs/nvptx/src/target_impl.cu:14:
  In file included from 
${llvm-SOURCE}/openmp/libomptarget/deviceRTLs/nvptx/src/target_impl.h:18:
  ${llvm-INSTALL}/bin/../include/c++/v1/stdlib.h:128:10: error: 
'__builtin_fabsl' requires 128 bit size 'long double' type support, but device 
'nvptx64' does not support it
return __builtin_fabsl(__lcpp_x);
   ^


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94745

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


[PATCH] D95790: [WIP][clang][cli] Documentation of CompilerInvocation parsing/generation

2021-02-03 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 321103.
jansvoboda11 added a comment.
Herald added a reviewer: jdoerfert.
Herald added a subscriber: sstefan1.

Polish, document ImpliedByAnyOf and ShouldParse


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95790

Files:
  clang/docs/InternalsManual.rst

Index: clang/docs/InternalsManual.rst
===
--- clang/docs/InternalsManual.rst
+++ clang/docs/InternalsManual.rst
@@ -572,6 +572,275 @@
 The Frontend library contains functionality useful for building tools on top of
 the Clang libraries, for example several methods for outputting diagnostics.
 
+Compiler Invocation
+---
+
+One of the classes provided by the Frontend library is ``CompilerInvocation``,
+which holds information that describe current invocation of the Clang frontend.
+The information typically comes from the command line constructed by the Clang
+driver, or directly from clients performing custom initialization. The data
+structure is split into logical units used by different parts of the compiler,
+for example ``PreprocessorOptions``, ``LanguageOptions`` or ``CodeGenOptions``.
+
+Command Line Interface
+--
+
+The command line interface of the Clang ``-cc1`` frontend is defined alongside
+the driver options in ``clang/Driver/Options.td``. The information making up an
+option definition include the name and prefix (for example ``-std=``), form and
+position of the option value, help text, aliases and more. Each option may
+belong to a certain group and can be marked with zero or more flags. Options
+accepted by the ``-cc1`` frontend are marked with the ``CC1Option`` flag.
+
+Command Line Parsing
+
+
+Option definitions are processed by the ``-gen-opt-parser-defs`` tablegen
+backend, transformed into a list of invocations of the ``OPTION`` macro and
+stored in ``clang/Driver/Driver.inc``. This file is then used to create instance
+of ``llvm::opt::OptTable``, which acts as a command line preprocessor. The
+preprocessed command line is stored in ``llvm::opt::ArgList``, an object that
+provides an API for performing simple queries on the contents of the command
+line.
+
+Finally, the ``CompilerInvocation::CreateFromArgs`` function is responsible for
+the actual parsing of command line arguments. It maps the contents of the
+``ArgList`` onto fields of ``CompilerInvocation``, normalizing the values in the
+process.
+
+Command Line Generation
+---
+
+Any valid ``CompilerInvocation`` created from a ``-cc1`` command line  can be
+also serialized back into semantically equivalent command line in a
+deterministic manner. This enables features such as implicitly discovered,
+explicitly built modules.
+
+..
+  TODO: Create and link corresponding section in Modules.rst.
+
+Option Marshalling infrastructure
+-
+
+The obvious way to parse command line arguments is to write the code that
+queries ``ArgList`` and constructs ``CompilerInvocation`` manually. However,
+given that behavior of most command line options is the same, this approach
+would result in lots of repetitive code. This is the reason why most of the
+code for parsing and generating arguments is automatically generated from
+``Marshalling`` annotations on the tablegen option definitions. This section
+goes through the basics of the automatic marshalling system.
+
+To read and modify contents of ``CompilerInvocation``, the system uses key
+paths, which are declared in two steps. First, a tablegen definition for the
+``CompilerInvocation`` member is created by inheriting from ``KeyPathAndMacro``.
+
+.. code-block::
+
+  // Options.td
+
+  class LangOpts : KeyPathAndMacro<"LangOpts->", field, "LANG_"> {}
+  //   CompilerInvocation member  ^^
+  //OPTION_WITH_MARSHALLING prefix ^
+
+The first argument to the parent class is the beginning of the key path that
+references the ``CompilerInvocation`` member. This argument ends with ``->`` if
+the member is a pointer type or with ``.`` if it's a value type. The second
+argument is the only parameter passed to the child class. The child class can be
+used like so: ``LangOpts<"IgnoreExceptions">``, constructing a key path to the
+field ``LangOpts->IgnoreExceptions``. The third argument passed to the parent
+class is a string that the tablegen backend uses as a prefix to the
+``OPTION_WITH_MARSHALLING``. Using the key path then instructs the backend to
+generate the following code.
+
+.. code-block:: c++
+
+  // Options.inc
+
+  #ifdef LANG_OPTION_WITH_MARSHALLING
+  LANG_OPTION_WITH_MARSHALLING([...], LangOpts->IgnoreExceptions, [...])
+  #endif // LANG_OPTION_WITH_MARSHALLING
+
+Such definition can be used used in the parsing and generating functions:
+
+.. code-block:: c++
+
+  // CompilerInvoatio

[PATCH] D86295: [analyzer] Reorder the layout of MemRegion and cache by hand for optimal size

2021-02-03 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D86295#2519851 , @ASDenysPetrov 
wrote:

> What about this change? Did you make more measurements?

IMO it needs more justification and measurement to land it.

If my measurement was correct then it would decrease the readability of the 
code without any benefit.
It could be the case due to the allocation strategy & alignment stuff that we 
don't gain anything by making its layout more compact.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86295

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


[PATCH] D95168: [clang-format] Add InsertBraces option

2021-02-03 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:17996
+format(ForSourceLong, Style));
+}
+

MyDeveloperDay wrote:
> MyDeveloperDay wrote:
> > MyDeveloperDay wrote:
> > > are you testing do/while? 
> > whilst people discuss the ethics of modifying the code ;-) 
> > 
> > Can you add some comment based examples
> > 
> > ```
> > if (condition) // my test
> >   you_do_you();
> > 
> > if (condition)
> >   you_do_you(); // my test
> > ```
> bonus points..
> 
> ```
> if /*condition*/ (condition) /*condition*/
> /*condition*/  you_do_you(); /*condition*/
> ```
Should also add test for chained conditionals just to make sure the semantics 
of the code doesn't change.
```lang=c
if (A)
  if (B)
callAB();
  else
callA();
else if (B)
  callB();
else
  call();```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95168

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


[PATCH] D94973: [clang][OpenMP] Use OpenMPIRBuilder for workshare loops.

2021-02-03 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

This seems sensible. The clang parts look OK but I haven't thought everything 
through to the last detail. I left some questions below, I guess we can go down 
this road and slowly transition to the new scheme.




Comment at: clang/lib/AST/Stmt.cpp:1275
-->isScalarType())) &&
-"captures by copy are expected to have a scalar type!");
 break;

Why does this have to go? Is that avoidable?



Comment at: clang/lib/Sema/SemaExpr.cpp:17274
+  if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
+ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
+  } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {

This doesn't impact anyone else negatively? I don't understand why we need this 
now.



Comment at: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h:305
 
+  /// Modifies the canonical loop to be a workshare loop.
+  CanonicalLoopInfo *createWorkshareLoop(const LocationDescription &Loc,

Nit: Add the argument description (from above).



Comment at: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h:865
 
+  Function *getFunction() const { return Header->getParent(); }
+

Nit: documentation, also above.



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:986
+  if (BodyGenCB)
+BodyGenCB(CL->getBodyIP(), CL->getIndVar());
 

I'm unsure I understand when it would make sense to not have a body generator.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94973

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


[PATCH] D94745: [OpenMP][deviceRTLs] Build the deviceRTLs with OpenMP instead of target dependent language

2021-02-03 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

In D94745#2539405 , @protze.joachim 
wrote:

> For me this patch breaks building llvm. Before this patch, I successfully 
> built llvm using a llvm/10 installation on the system. What is probably 
> special with our llvm installation is that we by default use libc++ rather 
> than libstdc++.
>
>   FAILED: 
> projects/openmp/libomptarget/deviceRTLs/nvptx/loop.cu-cuda_110-sm_60.bc 
>   cd BUILD/projects/openmp/libomptarget/deviceRTLs/nvptx && 
> /home/pj416018/sw/UTIL/ccache/bin/clang -S -x c++ -target nvptx64 -Xclang 
> -emit-llvm-bc -Xclang -aux-triple -Xclang x86_64-unknown-linux-gnu -fopenmp 
> -fopenmp-cuda-mode -Xclang -fopenmp-is-device -D__CUDACC__ 
> -I${llvm-SOURCE}/openmp/libomptarget/deviceRTLs 
> -I${llvm-SOURCE}/openmp/libomptarget/deviceRTLs/nvptx/src 
> -DOMPTARGET_NVPTX_DEBUG=0 -Xclang -target-cpu -Xclang sm_60 
> -D__CUDA_ARCH__=600 -Xclang -target-feature -Xclang +ptx70 
> -DCUDA_VERSION=11000 
> ${llvm-SOURCE}/openmp/libomptarget/deviceRTLs/common/src/loop.cu -o 
> loop.cu-cuda_110-sm_60.bc
>   In file included from 
> ${llvm-SOURCE}/openmp/libomptarget/deviceRTLs/common/src/loop.cu:16:
>   In file included from 
> ${llvm-SOURCE}/openmp/libomptarget/deviceRTLs/common/omptarget.h:18:
>   In file included from 
> ${llvm-SOURCE}/openmp/libomptarget/deviceRTLs/common/debug.h:31:
>   In file included from 
> ${llvm-SOURCE}/openmp/libomptarget/deviceRTLs/common/device_environment.h:16:
>   In file included from 
> ${llvm-SOURCE}/openmp/libomptarget/deviceRTLs/nvptx/src/target_impl.h:18:
>   In file included from 
> ${llvm-INSTALL}/10.0.0/bin/../include/c++/v1/stdlib.h:100:
>   In file included from 
> ${llvm-INSTALL}/10.0.0/bin/../include/c++/v1/math.h:312:
>   ${llvm-INSTALL}/10.0.0/bin/../include/c++/v1/limits:406:89: error: host 
> requires 128 bit size 'std::__1::__libcpp_numeric_limits true>::type' (aka 'long double') type support, but device 'nvptx64' does not 
> support it
>   _LIBCPP_INLINE_VISIBILITY static _LIBCPP_CONSTEXPR type lowest() 
> _NOEXCEPT {return -max();}
>   
> ^
>
> My cmake call looks like:
>
>   cmake -GNinja -DCMAKE_BUILD_TYPE=Release \
> -DCMAKE_INSTALL_PREFIX=$INSTALLDIR \
> -DLLVM_ENABLE_LIBCXX=ON \
> -DCLANG_DEFAULT_CXX_STDLIB=libc++ \
> -DCLANG_OPENMP_NVPTX_DEFAULT_ARCH=sm_70 \
> -DLIBOMPTARGET_ENABLE_DEBUG=on \
> -DLIBOMPTARGET_NVPTX_ENABLE_BCLIB=true \
> -DLIBOMPTARGET_NVPTX_COMPUTE_CAPABILITIES=35,60,70 \
> 
> -DLLVM_ENABLE_PROJECTS="clang;compiler-rt;libcxxabi;libcxx;libunwind;openmp" \
> -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON \
> $LLVM_SOURCE
>
> I also tried to build using my newest installed llvm build 
> (7dd198852b4db52ae22242dfeda4eccda83aa8b2 
> ):
>
>   In file included from 
> ${llvm-SOURCE}/openmp/libomptarget/deviceRTLs/nvptx/src/target_impl.cu:14:
>   In file included from 
> ${llvm-SOURCE}/openmp/libomptarget/deviceRTLs/nvptx/src/target_impl.h:18:
>   ${llvm-INSTALL}/bin/../include/c++/v1/stdlib.h:128:10: error: 
> '__builtin_fabsl' requires 128 bit size 'long double' type support, but 
> device 'nvptx64' does not support it
> return __builtin_fabsl(__lcpp_x);
>^

This is tracked in PR48933, could you give D95928 
 and it's two dependences a try?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94745

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


[PATCH] D95860: [clang][Frontend] Fix a crash in DiagnosticRenderer.

2021-02-03 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

Probably it is not worth to find a better solution. In the case of CloneChecker 
the range starts and ends on different line that is not possible to print on a 
single line in the output.
This code could work:

  // Then, crawl the expansion chain for the end of the range.
  if (BeginFileID != EndFileID) {
while (End.isMacroID() && !BeginLocsMap.count(EndFileID)) {
  auto Exp = SM->getImmediateExpansionRange(End);
  IsTokenRange = Exp.isTokenRange();
  End = Exp.getEnd();
  EndFileID = SM->getFileID(End);
}
if (End.isMacroID()) {
  Begin = BeginLocsMap[EndFileID];
  BeginFileID = EndFileID;
} else if (BeginFileID != EndFileID) {
  assert(!BeginLocsMap.count(EndFileID));
  //if (SM->getIncludeLoc(BeginFileID).isValid() && 
SM->getIncludeLoc(EndFileID).isValid())
  //  continue;
  if (SM->getIncludeLoc(BeginFileID).isValid()) {
while (Begin.isValid() && BeginFileID != EndFileID) {
  Begin = SM->getIncludeLoc(BeginFileID);
  BeginFileID = SM->getFileID(Begin);
}
  } else if (SM->getIncludeLoc(EndFileID).isValid()) {
while (End.isValid() && BeginFileID != EndFileID) {
  End = SM->getIncludeLoc(EndFileID);
  EndFileID = SM->getFileID(End);
}
  } else {
llvm_unreachable("Got unacceptable source range with begin and end in 
different translation unit?");
  }
}
  }
  
  if (Begin.isInvalid() || End.isInvalid())
continue;
  
  // Do the backtracking.

With this solution the following result is printed:

  llvm-project/clang/test/Analysis/copypaste/clone-end-in-other-file.cpp:9:3: 
warning: Duplicate code detected [alpha.clone.CloneChecker]
if (i == 10) // expected-warning{{Duplicate code detected}}
^~~
  llvm-project/clang/test/Analysis/copypaste/clone-end-in-other-file.cpp:11:3: 
note: Similar code here
if (i == 10) // expected-note{{Similar code here}}
^~
  1 warning generated.

This is not better than the result with the existing code:

  llvm-project/clang/test/Analysis/copypaste/clone-end-in-other-file.cpp:9:3: 
warning: Duplicate code detected [alpha.clone.CloneChecker]
if (i == 10) // expected-warning{{Duplicate code detected}}
^
  llvm-project/clang/test/Analysis/copypaste/clone-end-in-other-file.cpp:11:3: 
note: Similar code here
if (i == 10) // expected-note{{Similar code here}}
^
  1 warning generated.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95860

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


[PATCH] D94745: [OpenMP][deviceRTLs] Build the deviceRTLs with OpenMP instead of target dependent language

2021-02-03 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added a comment.

I think there's a bug report about this. Sycl (iirc) introduced a change that 
caught invalid things with types that were previously ignored. @jdoerfert is on 
point I think.

`-DLLVM_ENABLE_PROJECTS="clang;compiler-rt;libcxxabi;libcxx;libunwind;openmp" `
^ That works, if the compiler in question can build things like an nvptx 
devicertl, which essentially means if it's a (sometimes very) recent clang. A 
generally easier path is
`-DLLVM_ENABLE_RUNTIMES="openmp"`
as that will build clang first, then use that clang to build openmp.

Won't help in this particular instance - if I understand correctly, it's a 
misfire from using glibc headers on the nvptx subsystem - though that stdlib.h 
looks like it shipped as part of libc++.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94745

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


[PATCH] D95918: [Coverage] Propogate counter to condition of conditional operator

2021-02-03 Thread Vedant Kumar via Phabricator via cfe-commits
vsk accepted this revision.
vsk added a comment.
This revision is now accepted and ready to land.

Thanks, lgtm.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95918

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


[PATCH] D95915: [clang][driver] Only warn once about invalid -stdlib value

2021-02-03 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

Drive by: I don't believe a static variable is a good idea. Also the name is 
not really informative. A member in `ToolChain` with a proper name would be 
nicer (IMHO).


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

https://reviews.llvm.org/D95915

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


[PATCH] D95948: Stop traping on sNaN in __builtin_isnan

2021-02-03 Thread Thomas Preud'homme via Phabricator via cfe-commits
thopre updated this revision to Diff 321107.
thopre marked 2 inline comments as done.
thopre added a comment.

- Fix order of sub operands in comments and use fully parenthesized expression
- Explain how LShr is equivalent to < 0


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95948

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/X86/strictfp_builtins.c
  clang/test/CodeGen/strictfp_builtins.c
  clang/test/CodeGen/strictfp_fpclassify.c
  llvm/include/llvm/ADT/APFloat.h
  llvm/include/llvm/IR/Type.h

Index: llvm/include/llvm/IR/Type.h
===
--- llvm/include/llvm/IR/Type.h
+++ llvm/include/llvm/IR/Type.h
@@ -308,6 +308,10 @@
   /// ppc long double), this method returns -1.
   int getFPMantissaWidth() const;
 
+  /// Return whether the type is IEEE compatible, as defined by the eponymous
+  /// method in APFloat.
+  bool isIEEE() const { return APFloat::getZero(getFltSemantics()).isIEEE(); }
+
   /// If this is a vector type, return the element type, otherwise return
   /// 'this'.
   inline Type *getScalarType() const {
Index: llvm/include/llvm/ADT/APFloat.h
===
--- llvm/include/llvm/ADT/APFloat.h
+++ llvm/include/llvm/ADT/APFloat.h
@@ -1218,6 +1218,7 @@
   bool isSmallest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isSmallest()); }
   bool isLargest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isLargest()); }
   bool isInteger() const { APFLOAT_DISPATCH_ON_SEMANTICS(isInteger()); }
+  bool isIEEE() const { return usesLayout(getSemantics()); }
 
   APFloat &operator=(const APFloat &RHS) = default;
   APFloat &operator=(APFloat &&RHS) = default;
Index: clang/test/CodeGen/strictfp_builtins.c
===
--- clang/test/CodeGen/strictfp_builtins.c
+++ clang/test/CodeGen/strictfp_builtins.c
@@ -92,17 +92,38 @@
   return;
 }
 
-// CHECK-LABEL: @test_isnan(
+// CHECK-LABEL: @test_float_isnan(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[F_ADDR:%.*]] = alloca float, align 4
+// CHECK-NEXT:store float [[F:%.*]], float* [[F_ADDR]], align 4
+// CHECK-NEXT:[[TMP0:%.*]] = load float, float* [[F_ADDR]], align 4
+// CHECK-NEXT:[[BITCAST:%.*]] = bitcast float [[TMP0]] to i32
+// CHECK-NEXT:[[ABS:%.*]] = and i32 [[BITCAST]], [[#%u,0x7FFF]]
+// CHECK-NEXT:[[TMP1:%.*]] = sub i32 [[#%u,0x7F80]], [[ABS]]
+// CHECK-NEXT:[[ISNAN:%.*]] = lshr i32 [[TMP1]], 31
+// CHECK-NEXT:call void @p(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @.str.4, i64 0, i64 0), i32 [[ISNAN]]) [[ATTR4]]
+// CHECK-NEXT:ret void
+//
+void test_float_isnan(float f) {
+  P(isnan, (f));
+
+  return;
+}
+
+// CHECK-LABEL: @test_double_isnan(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[D_ADDR:%.*]] = alloca double, align 8
 // CHECK-NEXT:store double [[D:%.*]], double* [[D_ADDR]], align 8
 // CHECK-NEXT:[[TMP0:%.*]] = load double, double* [[D_ADDR]], align 8
-// CHECK-NEXT:[[CMP:%.*]] = call i1 @llvm.experimental.constrained.fcmp.f64(double [[TMP0]], double [[TMP0]], metadata !"uno", metadata !"fpexcept.strict") [[ATTR4]]
-// CHECK-NEXT:[[TMP1:%.*]] = zext i1 [[CMP]] to i32
-// CHECK-NEXT:call void @p(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @.str.4, i64 0, i64 0), i32 [[TMP1]]) [[ATTR4]]
+// CHECK-NEXT:[[BITCAST:%.*]] = bitcast double [[TMP0]] to i64
+// CHECK-NEXT:[[ABS:%.*]] = and i64 [[BITCAST]], [[#%u,0x7FFF]]
+// CHECK-NEXT:[[TMP1:%.*]] = sub i64 [[#%u,0x7FF0]], [[ABS]]
+// CHECK-NEXT:[[ISNAN:%.*]] = lshr i64 [[TMP1]], 63
+// CHECK-NEXT:[[RES:%.*]] = trunc i64 [[ISNAN]] to i32
+// CHECK-NEXT:call void @p(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @.str.5, i64 0, i64 0), i32 [[RES]]) [[ATTR4]]
 // CHECK-NEXT:ret void
 //
-void test_isnan(double d) {
+void test_double_isnan(double d) {
   P(isnan, (d));
 
   return;
@@ -120,7 +141,7 @@
 // CHECK-NEXT:[[AND:%.*]] = and i1 [[ISEQ]], [[ISINF]]
 // CHECK-NEXT:[[AND1:%.*]] = and i1 [[AND]], [[ISNORMAL]]
 // CHECK-NEXT:[[TMP2:%.*]] = zext i1 [[AND1]] to i32
-// CHECK-NEXT:call void @p(i8* getelementptr inbounds ([12 x i8], [12 x i8]* @.str.5, i64 0, i64 0), i32 [[TMP2]]) [[ATTR4]]
+// CHECK-NEXT:call void @p(i8* getelementptr inbounds ([12 x i8], [12 x i8]* @.str.6, i64 0, i64 0), i32 [[TMP2]]) [[ATTR4]]
 // CHECK-NEXT:ret void
 //
 void test_isnormal(double d) {
Index: clang/test/CodeGen/X86/strictfp_builtins.c
===
--- /dev/null
+++ clang/test/CodeGen/X86/strictfp_builtins.c
@@ -0,0 +1,46 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 %s -emit-llvm -ffp-exception-behavior=maytrap -o - -triple x86_64-unknown-unknown | FileCheck %s
+
+// Test that the constrained intrinsics are pick

[clang] 81b6987 - [FPEnv][X86] Platform builtins edition: clang should get from the AST the metadata for constrained FP builtins

2021-02-03 Thread Kevin P. Neal via cfe-commits

Author: Kevin P. Neal
Date: 2021-02-03T11:49:17-05:00
New Revision: 81b69879c946533c71cc484bd8d9202bf1e34bfe

URL: 
https://github.com/llvm/llvm-project/commit/81b69879c946533c71cc484bd8d9202bf1e34bfe
DIFF: 
https://github.com/llvm/llvm-project/commit/81b69879c946533c71cc484bd8d9202bf1e34bfe.diff

LOG: [FPEnv][X86] Platform builtins edition: clang should get from the AST the 
metadata for constrained FP builtins

Currently clang is not correctly retrieving from the AST the metadata for
constrained FP builtins. This patch fixes that for the X86 specific builtins.

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

Added: 
clang/test/CodeGen/X86/avx512dq-builtins-constrained.c

Modified: 
clang/lib/CodeGen/CGBuiltin.cpp
clang/test/CodeGen/X86/avx-builtins-constrained-cmp.c
clang/test/CodeGen/X86/avx512f-builtins-constrained.c
clang/test/CodeGen/X86/fma-builtins-constrained.c
clang/test/CodeGen/X86/sse-builtins-constrained.c

Removed: 




diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 973a20f2f58c..d8bb1bc84daa 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -11664,7 +11664,7 @@ static Value *EmitX86ConvertToMask(CodeGenFunction 
&CGF, Value *In) {
   return EmitX86MaskedCompare(CGF, 1, true, { In, Zero });
 }
 
-static Value *EmitX86ConvertIntToFp(CodeGenFunction &CGF,
+static Value *EmitX86ConvertIntToFp(CodeGenFunction &CGF, const CallExpr *E,
 ArrayRef Ops, bool IsSigned) {
   unsigned Rnd = cast(Ops[3])->getZExtValue();
   llvm::Type *Ty = Ops[1]->getType();
@@ -11676,6 +11676,7 @@ static Value *EmitX86ConvertIntToFp(CodeGenFunction 
&CGF,
 Function *F = CGF.CGM.getIntrinsic(IID, { Ty, Ops[0]->getType() });
 Res = CGF.Builder.CreateCall(F, { Ops[0], Ops[3] });
   } else {
+CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
 Res = IsSigned ? CGF.Builder.CreateSIToFP(Ops[0], Ty)
: CGF.Builder.CreateUIToFP(Ops[0], Ty);
   }
@@ -11684,8 +11685,9 @@ static Value *EmitX86ConvertIntToFp(CodeGenFunction 
&CGF,
 }
 
 // Lowers X86 FMA intrinsics to IR.
-static Value *EmitX86FMAExpr(CodeGenFunction &CGF, ArrayRef Ops,
- unsigned BuiltinID, bool IsAddSub) {
+static Value *EmitX86FMAExpr(CodeGenFunction &CGF, const CallExpr *E,
+ ArrayRef Ops, unsigned BuiltinID,
+ bool IsAddSub) {
 
   bool Subtract = false;
   Intrinsic::ID IID = Intrinsic::not_intrinsic;
@@ -11742,6 +11744,7 @@ static Value *EmitX86FMAExpr(CodeGenFunction &CGF, 
ArrayRef Ops,
 llvm::Type *Ty = A->getType();
 Function *FMA;
 if (CGF.Builder.getIsFPConstrained()) {
+  CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
   FMA = CGF.CGM.getIntrinsic(Intrinsic::experimental_constrained_fma, Ty);
   Res = CGF.Builder.CreateConstrainedFPCall(FMA, {A, B, C});
 } else {
@@ -11783,10 +11786,10 @@ static Value *EmitX86FMAExpr(CodeGenFunction &CGF, 
ArrayRef Ops,
   return Res;
 }
 
-static Value *
-EmitScalarFMAExpr(CodeGenFunction &CGF, MutableArrayRef Ops,
-  Value *Upper, bool ZeroMask = false, unsigned PTIdx = 0,
-  bool NegAcc = false) {
+static Value *EmitScalarFMAExpr(CodeGenFunction &CGF, const CallExpr *E,
+MutableArrayRef Ops, Value *Upper,
+bool ZeroMask = false, unsigned PTIdx = 0,
+bool NegAcc = false) {
   unsigned Rnd = 4;
   if (Ops.size() > 4)
 Rnd = cast(Ops[4])->getZExtValue();
@@ -11805,6 +11808,7 @@ EmitScalarFMAExpr(CodeGenFunction &CGF, 
MutableArrayRef Ops,
 Res = CGF.Builder.CreateCall(CGF.CGM.getIntrinsic(IID),
  {Ops[0], Ops[1], Ops[2], Ops[4]});
   } else if (CGF.Builder.getIsFPConstrained()) {
+CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
 Function *FMA = CGF.CGM.getIntrinsic(
 Intrinsic::experimental_constrained_fma, Ops[0]->getType());
 Res = CGF.Builder.CreateConstrainedFPCall(FMA, Ops.slice(0, 3));
@@ -12142,8 +12146,9 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned 
BuiltinID,
   // TODO: The builtins could be removed if the SSE header files used vector
   // extension comparisons directly (vector ordered/unordered may need
   // additional support via __builtin_isnan()).
-  auto getVectorFCmpIR = [this, &Ops](CmpInst::Predicate Pred,
-  bool IsSignaling) {
+  auto getVectorFCmpIR = [this, &Ops, E](CmpInst::Predicate Pred,
+ bool IsSignaling) {
+CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
 Value *Cmp;
 if (IsSignaling)
   Cmp = Builder.CreateFCmpS(Pred, Ops[0], Ops[1]);
@@ -12385,31 +12390,31 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned 
Bui

[PATCH] D94614: [FPEnv][X86] Platform builtins edition: clang should get from the AST the metadata for constrained FP builtins

2021-02-03 Thread Kevin P. Neal via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG81b69879c946: [FPEnv][X86] Platform builtins edition: clang 
should get from the AST the… (authored by kpn).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94614

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/X86/avx-builtins-constrained-cmp.c
  clang/test/CodeGen/X86/avx512dq-builtins-constrained.c
  clang/test/CodeGen/X86/avx512f-builtins-constrained.c
  clang/test/CodeGen/X86/fma-builtins-constrained.c
  clang/test/CodeGen/X86/sse-builtins-constrained.c

Index: clang/test/CodeGen/X86/sse-builtins-constrained.c
===
--- clang/test/CodeGen/X86/sse-builtins-constrained.c
+++ clang/test/CodeGen/X86/sse-builtins-constrained.c
@@ -1,8 +1,15 @@
 // REQUIRES: x86-registered-target
 // RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +sse -emit-llvm -o - -Wall -Werror | FileCheck %s --check-prefix=UNCONSTRAINED --check-prefix=COMMON --check-prefix=COMMONIR
-// RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +sse -ffp-exception-behavior=strict -emit-llvm -o - -Wall -Werror | FileCheck %s --check-prefix=CONSTRAINED --check-prefix=COMMON --check-prefix=COMMONIR
+// RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +sse -ffp-exception-behavior=maytrap -DSTRICT=1 -emit-llvm -o - -Wall -Werror | FileCheck %s --check-prefix=CONSTRAINED --check-prefix=COMMON --check-prefix=COMMONIR
 // RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +sse -S %s -o - -Wall -Werror | FileCheck %s --check-prefix=CHECK-ASM --check-prefix=COMMON
-// RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +sse -ffp-exception-behavior=strict -S %s -o - -Wall -Werror | FileCheck %s --check-prefix=CHECK-ASM --check-prefix=COMMON
+// RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +sse -ffp-exception-behavior=maytrap -DSTRICT=1 -S %s -o - -Wall -Werror | FileCheck %s --check-prefix=CHECK-ASM --check-prefix=COMMON
+
+#ifdef STRICT
+// Test that the constrained intrinsics are picking up the exception
+// metadata from the AST instead of the global default from the command line.
+
+#pragma float_control(except, on)
+#endif
 
 
 #include 
Index: clang/test/CodeGen/X86/fma-builtins-constrained.c
===
--- clang/test/CodeGen/X86/fma-builtins-constrained.c
+++ clang/test/CodeGen/X86/fma-builtins-constrained.c
@@ -1,8 +1,15 @@
 // REQUIRES: x86-registered-target
 // RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +fma -O2 -emit-llvm -o - | FileCheck %s --check-prefixes=COMMON,COMMONIR,UNCONSTRAINED
-// RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +fma -ffp-exception-behavior=strict -O2 -emit-llvm -o - | FileCheck %s --check-prefixes=COMMON,COMMONIR,CONSTRAINED
+// RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +fma -ffp-exception-behavior=maytrap -DSTRICT=1 -O2 -emit-llvm -o - | FileCheck %s --check-prefixes=COMMON,COMMONIR,CONSTRAINED
 // RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +fma -O2 -S -o - | FileCheck %s --check-prefixes=COMMON,CHECK-ASM
-// RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +fma -O2 -ffp-exception-behavior=strict -S -o - | FileCheck %s --check-prefixes=COMMON,CHECK-ASM
+// RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +fma -O2 -ffp-exception-behavior=maytrap -DSTRICT=1 -S -o - | FileCheck %s --check-prefixes=COMMON,CHECK-ASM
+
+#ifdef STRICT
+// Test that the constrained intrinsics are picking up the exception
+// metadata from the AST instead of the global default from the command line.
+
+#pragma float_control(except, on)
+#endif
 
 #include 
 
Index: clang/test/CodeGen/X86/avx512f-builtins-constrained.c
===
--- clang/test/CodeGen/X86/avx512f-builtins-constrained.c
+++ clang/test/CodeGen/X86/avx512f-builtins-constrained.c
@@ -1,10 +1,17 @@
 // REQUIRES: x86-registered-target
 // RUN: %clang_cc1 -fexperimental-new-pass-manager -flax-vector-conversions=none -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +avx512f -emit-llvm -o - -Wall -Werror | FileCheck --check-prefix=COMMON --check-prefix=COMMONIR --check-prefix=UNCONSTRAINED %s
 // RUN: %clang_cc1 -fexperimental-new-pass-manager -flax-vector-conversions=none -fms-extensions -fms-compatibility -ffreestanding %s -triple=x86_64-windows-msvc -target-feature +avx512f -emit-llvm -o - -Wall -Werror | FileCheck --check-prefix=COMMON --check-prefix=COMMONIR --check-prefix=UNCONSTRA

[PATCH] D78979: OpenCL: Include builtin header by default

2021-02-03 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In D78979#2536661 , @arsenm wrote:

> In D78979#2536590 , @Anastasia wrote:
>
>> @arsenm I would like to see if we can finalize this patch soon. Do you think 
>> you will have a capacity for this in the next weeks? Otherwise I would be 
>> happy to help too.
>
> I don't think I'll have time soon, you can take over
>
>> It looks in a good shape, we just need to decide if we go ahead with the new 
>> flag you are adding or reuse `-nostdinc`. Do you have any preference 
>> yourself?
>
> Not really sure. No real preference

Thanks, after brainstorming more with other developers I have decided to change 
the direction slightly that I have explained in the RFC:
https://lists.llvm.org/pipermail/cfe-dev/2021-February/067610.html

I believe this achieves similar goal but it also addresses the long parsing 
speed that has always been a concern for the default header within the OpenCL 
community.

Let me know if you have any feedback and either way we decide to go your patch 
will be a good base point.


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

https://reviews.llvm.org/D78979

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


[PATCH] D95942: [clangd] Deduplicate scopes in IncludeFixer queries

2021-02-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 321118.
kadircet added a comment.
Herald added a subscriber: mgrang.

- sort+unique+erase instead of using a set
- Inline visitor and directly collect scopes there.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95942

Files:
  clang-tools-extra/clangd/IncludeFixer.cpp


Index: clang-tools-extra/clangd/IncludeFixer.cpp
===
--- clang-tools-extra/clangd/IncludeFixer.cpp
+++ clang-tools-extra/clangd/IncludeFixer.cpp
@@ -40,31 +40,14 @@
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/FormatVariadic.h"
+#include 
+#include 
+#include 
 #include 
 
 namespace clang {
 namespace clangd {
 
-namespace {
-
-// Collects contexts visited during a Sema name lookup.
-class VisitedContextCollector : public VisibleDeclConsumer {
-public:
-  void EnteredContext(DeclContext *Ctx) override { Visited.push_back(Ctx); }
-
-  void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
- bool InBaseClass) override {}
-
-  std::vector takeVisitedContexts() {
-return std::move(Visited);
-  }
-
-private:
-  std::vector Visited;
-};
-
-} // namespace
-
 std::vector IncludeFixer::fix(DiagnosticsEngine::Level DiagLevel,
const clang::Diagnostic &Info) const {
   switch (Info.getID()) {
@@ -313,17 +296,25 @@
 std::vector
 collectAccessibleScopes(Sema &Sem, const DeclarationNameInfo &Typo, Scope *S,
 Sema::LookupNameKind LookupKind) {
+  // Collects contexts visited during a Sema name lookup.
+  struct VisitedContextCollector : public VisibleDeclConsumer {
+VisitedContextCollector(std::vector &Out) : Out(Out) {}
+void EnteredContext(DeclContext *Ctx) override {
+  if (llvm::isa(Ctx))
+Out.push_back(printNamespaceScope(*Ctx));
+}
+void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
+   bool InBaseClass) override {}
+std::vector &Out;
+  };
+
   std::vector Scopes;
-  VisitedContextCollector Collector;
+  VisitedContextCollector Collector(Scopes);
   Sem.LookupVisibleDecls(S, LookupKind, Collector,
  /*IncludeGlobalScope=*/false,
  /*LoadExternal=*/false);
-
-  Scopes.push_back("");
-  for (const auto *Ctx : Collector.takeVisitedContexts()) {
-if (isa(Ctx))
-  Scopes.push_back(printNamespaceScope(*Ctx));
-  }
+  std::sort(Scopes.begin(), Scopes.end());
+  Scopes.erase(std::unique(Scopes.begin(), Scopes.end()), Scopes.end());
   return Scopes;
 }
 


Index: clang-tools-extra/clangd/IncludeFixer.cpp
===
--- clang-tools-extra/clangd/IncludeFixer.cpp
+++ clang-tools-extra/clangd/IncludeFixer.cpp
@@ -40,31 +40,14 @@
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/FormatVariadic.h"
+#include 
+#include 
+#include 
 #include 
 
 namespace clang {
 namespace clangd {
 
-namespace {
-
-// Collects contexts visited during a Sema name lookup.
-class VisitedContextCollector : public VisibleDeclConsumer {
-public:
-  void EnteredContext(DeclContext *Ctx) override { Visited.push_back(Ctx); }
-
-  void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
- bool InBaseClass) override {}
-
-  std::vector takeVisitedContexts() {
-return std::move(Visited);
-  }
-
-private:
-  std::vector Visited;
-};
-
-} // namespace
-
 std::vector IncludeFixer::fix(DiagnosticsEngine::Level DiagLevel,
const clang::Diagnostic &Info) const {
   switch (Info.getID()) {
@@ -313,17 +296,25 @@
 std::vector
 collectAccessibleScopes(Sema &Sem, const DeclarationNameInfo &Typo, Scope *S,
 Sema::LookupNameKind LookupKind) {
+  // Collects contexts visited during a Sema name lookup.
+  struct VisitedContextCollector : public VisibleDeclConsumer {
+VisitedContextCollector(std::vector &Out) : Out(Out) {}
+void EnteredContext(DeclContext *Ctx) override {
+  if (llvm::isa(Ctx))
+Out.push_back(printNamespaceScope(*Ctx));
+}
+void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
+   bool InBaseClass) override {}
+std::vector &Out;
+  };
+
   std::vector Scopes;
-  VisitedContextCollector Collector;
+  VisitedContextCollector Collector(Scopes);
   Sem.LookupVisibleDecls(S, LookupKind, Collector,
  /*IncludeGlobalScope=*/false,
  /*LoadExternal=*/false);
-
-  Scopes.push_back("");
-  for (const auto *Ctx : Collector.takeVisitedContexts()) {
-if (isa(Ctx))
-  Scopes.push_back(printNamespaceScope(*Ctx));
-  }
+  std::sort(Scopes.begin(), Scopes.end());
+  Scopes.erase(std::unique(Scopes.begin(), Scopes.end()), Scopes.end());
   return Scopes;
 }
 

[PATCH] D95581: Frontend: Refactor compileModuleAndReadAST, NFC

2021-02-03 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 accepted this revision.
jansvoboda11 added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95581

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


[PATCH] D95942: [clangd] Deduplicate scopes in IncludeFixer queries

2021-02-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 321120.
kadircet added a comment.

- add back the global scope.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95942

Files:
  clang-tools-extra/clangd/IncludeFixer.cpp


Index: clang-tools-extra/clangd/IncludeFixer.cpp
===
--- clang-tools-extra/clangd/IncludeFixer.cpp
+++ clang-tools-extra/clangd/IncludeFixer.cpp
@@ -40,31 +40,14 @@
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/FormatVariadic.h"
+#include 
+#include 
+#include 
 #include 
 
 namespace clang {
 namespace clangd {
 
-namespace {
-
-// Collects contexts visited during a Sema name lookup.
-class VisitedContextCollector : public VisibleDeclConsumer {
-public:
-  void EnteredContext(DeclContext *Ctx) override { Visited.push_back(Ctx); }
-
-  void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
- bool InBaseClass) override {}
-
-  std::vector takeVisitedContexts() {
-return std::move(Visited);
-  }
-
-private:
-  std::vector Visited;
-};
-
-} // namespace
-
 std::vector IncludeFixer::fix(DiagnosticsEngine::Level DiagLevel,
const clang::Diagnostic &Info) const {
   switch (Info.getID()) {
@@ -313,17 +296,26 @@
 std::vector
 collectAccessibleScopes(Sema &Sem, const DeclarationNameInfo &Typo, Scope *S,
 Sema::LookupNameKind LookupKind) {
+  // Collects contexts visited during a Sema name lookup.
+  struct VisitedContextCollector : public VisibleDeclConsumer {
+VisitedContextCollector(std::vector &Out) : Out(Out) {}
+void EnteredContext(DeclContext *Ctx) override {
+  if (llvm::isa(Ctx))
+Out.push_back(printNamespaceScope(*Ctx));
+}
+void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
+   bool InBaseClass) override {}
+std::vector &Out;
+  };
+
   std::vector Scopes;
-  VisitedContextCollector Collector;
+  Scopes.push_back("");
+  VisitedContextCollector Collector(Scopes);
   Sem.LookupVisibleDecls(S, LookupKind, Collector,
  /*IncludeGlobalScope=*/false,
  /*LoadExternal=*/false);
-
-  Scopes.push_back("");
-  for (const auto *Ctx : Collector.takeVisitedContexts()) {
-if (isa(Ctx))
-  Scopes.push_back(printNamespaceScope(*Ctx));
-  }
+  std::sort(Scopes.begin(), Scopes.end());
+  Scopes.erase(std::unique(Scopes.begin(), Scopes.end()), Scopes.end());
   return Scopes;
 }
 


Index: clang-tools-extra/clangd/IncludeFixer.cpp
===
--- clang-tools-extra/clangd/IncludeFixer.cpp
+++ clang-tools-extra/clangd/IncludeFixer.cpp
@@ -40,31 +40,14 @@
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/FormatVariadic.h"
+#include 
+#include 
+#include 
 #include 
 
 namespace clang {
 namespace clangd {
 
-namespace {
-
-// Collects contexts visited during a Sema name lookup.
-class VisitedContextCollector : public VisibleDeclConsumer {
-public:
-  void EnteredContext(DeclContext *Ctx) override { Visited.push_back(Ctx); }
-
-  void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
- bool InBaseClass) override {}
-
-  std::vector takeVisitedContexts() {
-return std::move(Visited);
-  }
-
-private:
-  std::vector Visited;
-};
-
-} // namespace
-
 std::vector IncludeFixer::fix(DiagnosticsEngine::Level DiagLevel,
const clang::Diagnostic &Info) const {
   switch (Info.getID()) {
@@ -313,17 +296,26 @@
 std::vector
 collectAccessibleScopes(Sema &Sem, const DeclarationNameInfo &Typo, Scope *S,
 Sema::LookupNameKind LookupKind) {
+  // Collects contexts visited during a Sema name lookup.
+  struct VisitedContextCollector : public VisibleDeclConsumer {
+VisitedContextCollector(std::vector &Out) : Out(Out) {}
+void EnteredContext(DeclContext *Ctx) override {
+  if (llvm::isa(Ctx))
+Out.push_back(printNamespaceScope(*Ctx));
+}
+void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
+   bool InBaseClass) override {}
+std::vector &Out;
+  };
+
   std::vector Scopes;
-  VisitedContextCollector Collector;
+  Scopes.push_back("");
+  VisitedContextCollector Collector(Scopes);
   Sem.LookupVisibleDecls(S, LookupKind, Collector,
  /*IncludeGlobalScope=*/false,
  /*LoadExternal=*/false);
-
-  Scopes.push_back("");
-  for (const auto *Ctx : Collector.takeVisitedContexts()) {
-if (isa(Ctx))
-  Scopes.push_back(printNamespaceScope(*Ctx));
-  }
+  std::sort(Scopes.begin(), Scopes.end());
+  Scopes.erase(std::unique(Scopes.begin(), Scopes.end()), Scopes.end());
   return Scopes;
 }
 
___
cfe-commits mai

[PATCH] D95915: [clang][driver] Only warn once about invalid -stdlib value

2021-02-03 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D95915#2539483 , @jdoerfert wrote:

> I don't believe a static variable is a good idea. Also the name is not really 
> informative. Members in `ToolChain` with a proper names would be nicer (IMHO).
>
> Tests missing. Also, now you don't warn for different missing runtimes, which 
> seems odd.

+1

I agree with Johannes about static variable usage. We should avoid using static 
variables since they are not thread safe and become hurdles when we want to 
parallelize the driver.

Is it possible to emit the diag in a lambda and use std::call_once with it?


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

https://reviews.llvm.org/D95915

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


[PATCH] D95793: [clang][cli] Generate and round-trip language options

2021-02-03 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 321131.
jansvoboda11 added a comment.

Fix failures of tests that invoke -cc1 directly


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95793

Files:
  clang/include/clang/Basic/Sanitizers.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Basic/Sanitizers.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/unittests/Basic/CMakeLists.txt
  clang/unittests/Basic/SanitizersTest.cpp

Index: clang/unittests/Basic/SanitizersTest.cpp
===
--- /dev/null
+++ clang/unittests/Basic/SanitizersTest.cpp
@@ -0,0 +1,49 @@
+//===- unittests/Basic/SanitizersTest.cpp - Test Sanitizers ---===//
+//
+// 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/Basic/Sanitizers.h"
+
+#include "gmock/gmock-matchers.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+
+using testing::Contains;
+using testing::Not;
+
+TEST(SanitizersTest, serializeSanitizers) {
+  SanitizerSet Set;
+  Set.set(parseSanitizerValue("memory", false), true);
+  Set.set(parseSanitizerValue("nullability-arg", false), true);
+
+  SmallVector Serialized;
+  serializeSanitizerSet(Set, Serialized);
+
+  ASSERT_EQ(Serialized.size(), 2u);
+  ASSERT_THAT(Serialized, Contains("memory"));
+  ASSERT_THAT(Serialized, Contains("nullability-arg"));
+}
+
+TEST(SanitizersTest, serializeSanitizersIndividual) {
+  SanitizerSet Set;
+  Set.set(parseSanitizerValue("memory", false), true);
+  Set.set(parseSanitizerValue("nullability-arg", false), true);
+  Set.set(parseSanitizerValue("nullability-assign", false), true);
+  Set.set(parseSanitizerValue("nullability-return", false), true);
+
+  SmallVector Serialized;
+  serializeSanitizerSet(Set, Serialized);
+
+  ASSERT_EQ(Serialized.size(), 4u);
+  ASSERT_THAT(Serialized, Contains("memory"));
+  ASSERT_THAT(Serialized, Contains("nullability-arg"));
+  ASSERT_THAT(Serialized, Contains("nullability-assign"));
+  ASSERT_THAT(Serialized, Contains("nullability-return"));
+  // Individual sanitizers don't get squashed into a single group.
+  ASSERT_THAT(Serialized, Not(Contains("nullability")));
+}
Index: clang/unittests/Basic/CMakeLists.txt
===
--- clang/unittests/Basic/CMakeLists.txt
+++ clang/unittests/Basic/CMakeLists.txt
@@ -8,6 +8,7 @@
   FileEntryTest.cpp
   FileManagerTest.cpp
   LineOffsetMappingTest.cpp
+  SanitizersTest.cpp
   SourceManagerTest.cpp
   )
 
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -214,6 +214,7 @@
 Args.push_back(SA(Value));
 break;
   case Option::JoinedClass:
+  case Option::CommaJoinedClass:
 Args.push_back(SA(Twine(Spelling) + Value));
 break;
   default:
@@ -1195,16 +1196,28 @@
   return Success;
 }
 
-static void parseSanitizerKinds(StringRef FlagName,
+static bool parseSanitizerKinds(StringRef FlagName,
 const std::vector &Sanitizers,
 DiagnosticsEngine &Diags, SanitizerSet &S) {
+  bool Success = true;
+
   for (const auto &Sanitizer : Sanitizers) {
 SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
-if (K == SanitizerMask())
+if (K == SanitizerMask()) {
   Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
+  Success = false;
+}
 else
   S.set(K, true);
   }
+
+  return Success;
+}
+
+static SmallVector serializeSanitizerKinds(SanitizerSet S) {
+  SmallVector Values;
+  serializeSanitizerSet(S, Values);
+  return Values;
 }
 
 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
@@ -2628,21 +2641,232 @@
   llvm_unreachable("unknown input language");
 }
 
-static void GenerateLangArgs(const LangOptions &Opts,
- SmallVectorImpl &Args,
- CompilerInvocation::StringAllocator SA) {
+void CompilerInvocation::GenerateLangArgs(const LangOptions &Opts,
+  SmallVectorImpl &Args,
+  StringAllocator SA,
+  const llvm::Triple &T) {
+  OptSpecifier StdOpt;
+  switch (Opts.LangStd) {
+  case LangStandard::lang_opencl10:
+  case LangStandard::lang_opencl11:
+  case LangStandard::lang_opencl12:
+  case LangStandard::lang_opencl20:
+  case LangStandard::lang_opencl30:
+  case LangStandard::lang_openclcpp:
+StdOpt = OPT_cl_std_E

[PATCH] D86694: [scudo] Allow -fsanitize=scudo on Linux and Windows (WIP, don't land as is)

2021-02-03 Thread Russell Gallop via Phabricator via cfe-commits
russell.gallop added a comment.

I've focussed on the test test-global-init-nonzero-sm-pic.ll which fails 
writing to an address which (I believe) should be in the .data section but 
isn't.

With some breakpoints in SectionMemoryManager.cpp it appears that this fails 
when the top 32bits of the .text allocated address and the .data allocated 
address are different:

  Allocating Data section ".data"
  Returning aligned address 0x01ed 30f6 of size 0x0004
  Allocating code section ".text"
  Returning aligned address 0x022d 3105 of size 0x003a

And work when they happen to be the same. When this fails, the address causing 
the access violation is the top 32bits of the .text address and the bottom 
32bits of the .data address, e.g. 0x022d 30f6. This doesn't fail 
without scudo as the top 32bits of the addresses seem to always be the same.

With assertions enabled this is causing an assert:

  
f:\git\llvm-project\stage1_scudo>"f:\git\llvm-project\stage1_scudo\bin\lli.exe" 
"-mtriple=x86_64-pc-windows-msvc-elf" "-relocation-model=pic" 
"-code-model=small" 
"f:\git\llvm-project\llvm\test\ExecutionEngine\MCJIT\test-global-init-nonzero-sm-pic.ll"
  Assertion failed: isInt<32>(RealOffset), file 
F:\git\llvm-project\llvm\lib\ExecutionEngine\RuntimeDyld\RuntimeDyldELF.cpp, 
line 300
  PLEASE submit a bug report to https://bugs.llvm.org/ and include the crash 
backtrace.
  Stack dump:
  0.  Program arguments: f:\\git\\llvm-project\\stage1_scudo\\bin\\lli.exe 
-mtriple=x86_64-pc-windows-msvc-elf -relocation-model=pic -code-model=small 
f:\\git\\llvm-project\\llvm\\test\\ExecutionEngine\\MCJIT\\test-global-init-nonzero-sm-pic.ll
   #0 0x7ff63eb423c5 HandleAbort 
F:\git\llvm-project\llvm\lib\Support\Windows\Signals.inc:408:0
   #1 0x7ff63f89d951 raise 
minkernel\crts\ucrt\src\appcrt\misc\signal.cpp:547:0
   #2 0x7ff63f8617cc abort 
minkernel\crts\ucrt\src\appcrt\startup\abort.cpp:71:0
   #3 0x7ff63f8825b8 common_assert_to_stderr 
minkernel\crts\ucrt\src\appcrt\startup\assert.cpp:175:0
   #4 0x7ff63f882d42 _wassert 
minkernel\crts\ucrt\src\appcrt\startup\assert.cpp:443:0
   #5 0x7ff63e749e96 llvm::RuntimeDyldELF::resolveX86_64Relocation(class 
llvm::SectionEntry const &, unsigned __int64, unsigned __int64, unsigned int, 
__int64, unsigned __int64) 
F:\git\llvm-project\llvm\lib\ExecutionEngine\RuntimeDyld\RuntimeDyldELF.cpp:302:0
   #6 0x7ff63e7496be llvm::RuntimeDyldELF::resolveRelocation(class 
llvm::RelocationEntry const &, unsigned __int64) 
F:\git\llvm-project\llvm\lib\ExecutionEngine\RuntimeDyld\RuntimeDyldELF.cpp:932:0
   #7 0x7ff63e72e656 llvm::RuntimeDyldImpl::resolveRelocationList(class 
llvm::SmallVector const &, unsigned __int64) 
F:\git\llvm-project\llvm\lib\ExecutionEngine\RuntimeDyld\RuntimeDyld.cpp:1077:0
   #8 0x7ff63e72e52c ::operator++ C:\Program Files (x86)\Microsoft Visual 
Studio\2019\Professional\VC\Tools\MSVC\14.28.29333\include\list:166:0
   #9 0x7ff63e72e52c ::operator++ C:\Program Files (x86)\Microsoft Visual 
Studio\2019\Professional\VC\Tools\MSVC\14.28.29333\include\list:247:0
  #10 0x7ff63e72e52c llvm::RuntimeDyldImpl::resolveLocalRelocations(void) 
F:\git\llvm-project\llvm\lib\ExecutionEngine\RuntimeDyld\RuntimeDyld.cpp:145:0
  #11 0x7ff63e72e872 llvm::RuntimeDyldImpl::resolveRelocations(void) 
F:\git\llvm-project\llvm\lib\ExecutionEngine\RuntimeDyld\RuntimeDyld.cpp:139:0
  #12 0x7ff63e532601 llvm::MCJIT::finalizeLoadedModules(void) 
F:\git\llvm-project\llvm\lib\ExecutionEngine\MCJIT\MCJIT.cpp:245:0
  #13 0x7ff63e532bfd ::{dtor} 
F:\git\llvm-project\llvm\include\llvm\ADT\SmallVector.h:1045:0
  #14 0x7ff63e532bfd llvm::MCJIT::finalizeObject(void) 
F:\git\llvm-project\llvm\lib\ExecutionEngine\MCJIT\MCJIT.cpp:271:0
  #15 0x7ff63dcfa06c main F:\git\llvm-project\llvm\tools\lli\lli.cpp:633:0
  #16 0x7ff63f81527c invoke_main 
d:\agent\_work\63\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl:78:0
  #17 0x7ff63f81527c __scrt_common_main_seh 
d:\agent\_work\63\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl:288:0
  #18 0x7ffd145a7034 (C:\WINDOWS\System32\KERNEL32.DLL+0x17034)
  #19 0x7ffd1657d0d1 (C:\WINDOWS\SYSTEM32\ntdll.dll+0x4d0d1)


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

https://reviews.llvm.org/D86694

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


[PATCH] D95793: [clang][cli] Generate and round-trip language options

2021-02-03 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 321135.
jansvoboda11 added a comment.

Revert reporting failure when parsing sanitizers


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95793

Files:
  clang/include/clang/Basic/Sanitizers.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Basic/Sanitizers.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/unittests/Basic/CMakeLists.txt
  clang/unittests/Basic/SanitizersTest.cpp

Index: clang/unittests/Basic/SanitizersTest.cpp
===
--- /dev/null
+++ clang/unittests/Basic/SanitizersTest.cpp
@@ -0,0 +1,49 @@
+//===- unittests/Basic/SanitizersTest.cpp - Test Sanitizers ---===//
+//
+// 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/Basic/Sanitizers.h"
+
+#include "gmock/gmock-matchers.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+
+using testing::Contains;
+using testing::Not;
+
+TEST(SanitizersTest, serializeSanitizers) {
+  SanitizerSet Set;
+  Set.set(parseSanitizerValue("memory", false), true);
+  Set.set(parseSanitizerValue("nullability-arg", false), true);
+
+  SmallVector Serialized;
+  serializeSanitizerSet(Set, Serialized);
+
+  ASSERT_EQ(Serialized.size(), 2u);
+  ASSERT_THAT(Serialized, Contains("memory"));
+  ASSERT_THAT(Serialized, Contains("nullability-arg"));
+}
+
+TEST(SanitizersTest, serializeSanitizersIndividual) {
+  SanitizerSet Set;
+  Set.set(parseSanitizerValue("memory", false), true);
+  Set.set(parseSanitizerValue("nullability-arg", false), true);
+  Set.set(parseSanitizerValue("nullability-assign", false), true);
+  Set.set(parseSanitizerValue("nullability-return", false), true);
+
+  SmallVector Serialized;
+  serializeSanitizerSet(Set, Serialized);
+
+  ASSERT_EQ(Serialized.size(), 4u);
+  ASSERT_THAT(Serialized, Contains("memory"));
+  ASSERT_THAT(Serialized, Contains("nullability-arg"));
+  ASSERT_THAT(Serialized, Contains("nullability-assign"));
+  ASSERT_THAT(Serialized, Contains("nullability-return"));
+  // Individual sanitizers don't get squashed into a single group.
+  ASSERT_THAT(Serialized, Not(Contains("nullability")));
+}
Index: clang/unittests/Basic/CMakeLists.txt
===
--- clang/unittests/Basic/CMakeLists.txt
+++ clang/unittests/Basic/CMakeLists.txt
@@ -8,6 +8,7 @@
   FileEntryTest.cpp
   FileManagerTest.cpp
   LineOffsetMappingTest.cpp
+  SanitizersTest.cpp
   SourceManagerTest.cpp
   )
 
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -214,6 +214,7 @@
 Args.push_back(SA(Value));
 break;
   case Option::JoinedClass:
+  case Option::CommaJoinedClass:
 Args.push_back(SA(Twine(Spelling) + Value));
 break;
   default:
@@ -1200,13 +1201,20 @@
 DiagnosticsEngine &Diags, SanitizerSet &S) {
   for (const auto &Sanitizer : Sanitizers) {
 SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
-if (K == SanitizerMask())
+if (K == SanitizerMask()) {
   Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
+}
 else
   S.set(K, true);
   }
 }
 
+static SmallVector serializeSanitizerKinds(SanitizerSet S) {
+  SmallVector Values;
+  serializeSanitizerSet(S, Values);
+  return Values;
+}
+
 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
ArgList &Args, DiagnosticsEngine &D,
XRayInstrSet &S) {
@@ -2628,19 +2636,231 @@
   llvm_unreachable("unknown input language");
 }
 
-static void GenerateLangArgs(const LangOptions &Opts,
- SmallVectorImpl &Args,
- CompilerInvocation::StringAllocator SA) {
+void CompilerInvocation::GenerateLangArgs(const LangOptions &Opts,
+  SmallVectorImpl &Args,
+  StringAllocator SA,
+  const llvm::Triple &T) {
+  OptSpecifier StdOpt;
+  switch (Opts.LangStd) {
+  case LangStandard::lang_opencl10:
+  case LangStandard::lang_opencl11:
+  case LangStandard::lang_opencl12:
+  case LangStandard::lang_opencl20:
+  case LangStandard::lang_opencl30:
+  case LangStandard::lang_openclcpp:
+StdOpt = OPT_cl_std_EQ;
+break;
+  default:
+StdOpt = OPT_std_EQ;
+break;
+  }
+
+  auto LangStandard = LangStandard::getLangStan

[PATCH] D95792: [clang][cli] Report result of ParseLangArgs

2021-02-03 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 321136.
jansvoboda11 added a comment.

Rely on DiagnosticsEngine when reporting parsing result


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95792

Files:
  clang/include/clang/Basic/Diagnostic.h
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Frontend/CompilerInvocation.cpp


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -2637,10 +2637,12 @@
 GenerateArg(Args, OPT_fdeclare_opencl_builtins, SA);
 }
 
-void CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
+bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
InputKind IK, const llvm::Triple &T,
std::vector &Includes,
DiagnosticsEngine &Diags) {
+  unsigned NumErrorsBefore = Diags.getNumErrors();
+
   // FIXME: Cleanup per-file based stuff.
   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
   if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
@@ -3069,6 +3071,8 @@
   }
 }
   }
+
+  return Success && Diags.getNumErrors() == NumErrorsBefore;
 }
 
 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
@@ -3409,8 +3413,8 @@
   } else {
 // Other LangOpts are only initialized when the input is not AST or LLVM 
IR.
 // FIXME: Should we really be calling this for an Language::Asm input?
-ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
-  Diags);
+Success &= ParseLangArgs(LangOpts, Args, DashX, T,
+ Res.getPreprocessorOpts().Includes, Diags);
 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
   LangOpts.ObjCExceptions = 1;
 if (T.isOSDarwin() && DashX.isPreprocessed()) {
Index: clang/include/clang/Frontend/CompilerInvocation.h
===
--- clang/include/clang/Frontend/CompilerInvocation.h
+++ clang/include/clang/Frontend/CompilerInvocation.h
@@ -249,7 +249,7 @@
DiagnosticsEngine &Diags);
 
   /// Parse command line options that map to LangOptions.
-  static void ParseLangArgs(LangOptions &Opts, llvm::opt::ArgList &Args,
+  static bool ParseLangArgs(LangOptions &Opts, llvm::opt::ArgList &Args,
 InputKind IK, const llvm::Triple &T,
 std::vector &Includes,
 DiagnosticsEngine &Diags);
Index: clang/include/clang/Basic/Diagnostic.h
===
--- clang/include/clang/Basic/Diagnostic.h
+++ clang/include/clang/Basic/Diagnostic.h
@@ -806,6 +806,7 @@
 return FatalErrorOccurred || UnrecoverableErrorOccurred;
   }
 
+  unsigned getNumErrors() const { return NumErrors; }
   unsigned getNumWarnings() const { return NumWarnings; }
 
   void setNumWarnings(unsigned NumWarnings) {


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -2637,10 +2637,12 @@
 GenerateArg(Args, OPT_fdeclare_opencl_builtins, SA);
 }
 
-void CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
+bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
InputKind IK, const llvm::Triple &T,
std::vector &Includes,
DiagnosticsEngine &Diags) {
+  unsigned NumErrorsBefore = Diags.getNumErrors();
+
   // FIXME: Cleanup per-file based stuff.
   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
   if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
@@ -3069,6 +3071,8 @@
   }
 }
   }
+
+  return Success && Diags.getNumErrors() == NumErrorsBefore;
 }
 
 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
@@ -3409,8 +3413,8 @@
   } else {
 // Other LangOpts are only initialized when the input is not AST or LLVM IR.
 // FIXME: Should we really be calling this for an Language::Asm input?
-ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
-  Diags);
+Success &= ParseLangArgs(LangOpts, Args, DashX, T,
+ Res.getPreprocessorOpts().Includes, Diags);
 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
   LangOpts.ObjCExceptions = 1;
 if (T.isOSDarwin() && DashX.isPreprocessed()) {
Index: clang/include/clang/Frontend/CompilerInvocation.h
===
--- clang/include/clang/Fr

[PATCH] D94745: [OpenMP][deviceRTLs] Build the deviceRTLs with OpenMP instead of target dependent language

2021-02-03 Thread Joachim Protze via Phabricator via cfe-commits
protze.joachim added a comment.

In D94745#2539454 , @JonChesterfield 
wrote:

> I think there's a bug report about this. Sycl (iirc) introduced a change that 
> caught invalid things with types that were previously ignored. @jdoerfert is 
> on point I think.
>
> `-DLLVM_ENABLE_PROJECTS="clang;compiler-rt;libcxxabi;libcxx;libunwind;openmp" 
> `
> ^ That works, if the compiler in question can build things like an nvptx 
> devicertl, which essentially means if it's a (sometimes very) recent clang. A 
> generally easier path is
> `-DLLVM_ENABLE_RUNTIMES="openmp"`
> as that will build clang first, then use that clang to build openmp.
>
> Won't help in this particular instance - if I understand correctly, it's a 
> misfire from using glibc headers on the nvptx subsystem - though that 
> stdlib.h looks like it shipped as part of libc++.
>
> edit: I am too slow...

I tried @jdoerfert 's patches, but they are not even necessary to address my 
building issue. Just delaying the build of OpenMP by setting 
`-DLLVM_ENABLE_RUNTIMES="openmp"` helped.
From my perspective, we should error out if people try to build OpenMP as a 
project rather than runtime and print a error message about what to change.

In any case, a stand-alone build of OpenMP still fails with any of the older 
clang compilers. Should we disable building of libomptarget, if an old clang is 
used? CMake diagnostic could suggest to use in-tree build for libomptarget.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94745

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


[PATCH] D95901: [CUDA][HIP] Fix device variable linkage

2021-02-03 Thread Artem Belevich via Phabricator via cfe-commits
tra added a comment.

> For -fgpu-rdc, shadow variables should not be internalized, otherwise they 
> cannot be accessed by other TUs. 
> This is necessary because the shadow variable of external device variables 
> are always emitted as undefined symbols, which need to resolve to a global 
> symbols.

Does it mean that we always internalize shadows *now*, before this patch? That 
would indeed be wrong. Shadow's visibility should be the same as that of a 
variable without a `__device__`.

Next question is whether the behavior should be different for `-fgpu-rdc` vs 
non-RDC.  I think shadows should behave the same regardless of RDC mode and 
make things work closer to what users would expect from regular C++ code. We 
already have mechanisms to uniquify the variables, if necessary, so we don't 
need to use visibility to avoid cross-TU linking conflicts.




Comment at: clang/lib/AST/ASTContext.cpp:11437-11443
+  return ((!getLangOpts().GPURelocatableDeviceCode &&
+   ((D->hasAttr() &&
+ !D->getAttr()->isImplicit()) ||
+(D->hasAttr() &&
+ !D->getAttr()->isImplicit( ||
   D->hasAttr()) &&
  isa(D) && cast(D)->getStorageClass() == SC_Static;

I can't parse it. :-( Perhaps we can split it.


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

https://reviews.llvm.org/D95901

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


[PATCH] D94472: [clang][cli] Command line round-trip for HeaderSearch options

2021-02-03 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 321137.
jansvoboda11 added a comment.
Herald added a subscriber: mgorny.

Don't round-trip when the driver says so. Round-trip all the time when built to 
do so.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94472

Files:
  clang/CMakeLists.txt
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/tools/driver/cc1_main.cpp
  llvm/include/llvm/Option/ArgList.h
  llvm/lib/Option/ArgList.cpp

Index: llvm/lib/Option/ArgList.cpp
===
--- llvm/lib/Option/ArgList.cpp
+++ llvm/lib/Option/ArgList.cpp
@@ -90,11 +90,22 @@
 }
 
 std::vector ArgList::getAllArgValues(OptSpecifier Id) const {
+  recordQueriedOpts(Id);
   SmallVector Values;
   AddAllArgValues(Values, Id);
   return std::vector(Values.begin(), Values.end());
 }
 
+void ArgList::AddAllArgsExcept(ArgStringList &Output,
+   const DenseSet &ExcludeIds) const {
+  for (const Arg *Arg : *this) {
+if (!ExcludeIds.contains(Arg->getOption().getID())) {
+  Arg->claim();
+  Arg->render(*this, Output);
+}
+  }
+}
+
 void ArgList::AddAllArgsExcept(ArgStringList &Output,
ArrayRef Ids,
ArrayRef ExcludeIds) const {
Index: llvm/include/llvm/Option/ArgList.h
===
--- llvm/include/llvm/Option/ArgList.h
+++ llvm/include/llvm/Option/ArgList.h
@@ -137,6 +137,16 @@
   /// The first and last index of each different OptSpecifier ID.
   DenseMap OptRanges;
 
+  /// The OptSpecifiers that were queried from this argument list.
+  mutable DenseSet QueriedOpts;
+
+  /// Record the queried OptSpecifiers.
+  template 
+  void recordQueriedOpts(OptSpecifiers... Ids) const {
+SmallVector OptsSpecifiers({toOptSpecifier(Ids).getID()...});
+QueriedOpts.insert(OptsSpecifiers.begin(), OptsSpecifiers.end());
+  }
+
   /// Get the range of indexes in which options with the specified IDs might
   /// reside, or (0, 0) if there are no such options.
   OptRange getRange(std::initializer_list Ids) const;
@@ -203,6 +213,7 @@
   template
   iterator_range>
   filtered(OptSpecifiers ...Ids) const {
+recordQueriedOpts(Ids...);
 OptRange Range = getRange({toOptSpecifier(Ids)...});
 auto B = Args.begin() + Range.first;
 auto E = Args.begin() + Range.second;
@@ -214,6 +225,7 @@
   template
   iterator_range>
   filtered_reverse(OptSpecifiers ...Ids) const {
+recordQueriedOpts(Ids...);
 OptRange Range = getRange({toOptSpecifier(Ids)...});
 auto B = Args.rend() - Range.second;
 auto E = Args.rend() - Range.first;
@@ -308,6 +320,10 @@
   A->render(*this, Output);
   }
 
+  /// AddAllArgsExcept - Render all arguments not matching any of the excluded
+  /// ids.
+  void AddAllArgsExcept(ArgStringList &Output,
+const DenseSet &ExcludeIds) const;
   /// AddAllArgsExcept - Render all arguments matching any of the given ids
   /// and not matching any of the excluded ids.
   void AddAllArgsExcept(ArgStringList &Output, ArrayRef Ids,
@@ -342,6 +358,12 @@
   ///
   void ClaimAllArgs() const;
 
+  /// Return the OptSpecifiers queried from this argument list.
+  const DenseSet &getQueriedOpts() const { return QueriedOpts; }
+
+  /// Clear the set of queried OptSpecifiers.
+  void clearQueriedOpts() const { QueriedOpts.clear(); }
+
   /// @}
   /// @name Arg Synthesis
   /// @{
Index: clang/tools/driver/cc1_main.cpp
===
--- clang/tools/driver/cc1_main.cpp
+++ clang/tools/driver/cc1_main.cpp
@@ -203,6 +203,12 @@
   IntrusiveRefCntPtr DiagOpts = new DiagnosticOptions();
   TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
+
+  // Setup round-trip remarks for the DiagnosticsEngine used in CreateFromArgs.
+  if (find(Argv, StringRef("-Rround-trip-cc1-args")) != Argv.end())
+Diags.setSeverity(diag::remark_cc1_round_trip_generated,
+  diag::Severity::Remark, {});
+
   bool Success = CompilerInvocation::CreateFromArgs(Clang->getInvocation(),
 Argv, Diags, Argv0);
 
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -38,6 +38,7 @@
 #include "clang/Frontend/FrontendPluginRegistry.h"
 #include "clang/Frontend/MigratorOptions.h"
 #include "clang/Frontend/PreprocessorOutputOptions.h"
+#include "clang/Frontend/TextDiagnosticBuffer.h"
 #include "clang/Frontend/Utils.h"
 #include "clang/Lex/Heade

[PATCH] D95872: [clang][Arm] Fix handling of -Wa,-march=

2021-02-03 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers accepted this revision.
nickdesaulniers added a comment.
This revision is now accepted and ready to land.

Looks great. Thanks again David.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95872

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


[PATCH] D94745: [OpenMP][deviceRTLs] Build the deviceRTLs with OpenMP instead of target dependent language

2021-02-03 Thread Joachim Protze via Phabricator via cfe-commits
protze.joachim added a comment.

Sorry, I meant to disable building of the cuda device-runtime, or whatever is 
breaking.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94745

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


[PATCH] D95877: [analyzer] Fix static_cast on pointer-to-member handling

2021-02-03 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD updated this revision to Diff 321139.
RedDocMD added a comment.

Cleaner implementation of the popping logic, using STL/LLVM algorithms


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95877

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
  clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
  clang/test/Analysis/pointer-to-member.cpp

Index: clang/test/Analysis/pointer-to-member.cpp
===
--- clang/test/Analysis/pointer-to-member.cpp
+++ clang/test/Analysis/pointer-to-member.cpp
@@ -287,3 +287,25 @@
   clang_analyzer_eval(a.*ep == 5); // expected-warning{{TRUE}}
 }
 } // namespace testAnonymousMember
+
+namespace testStaticCasting {
+// From bug #48739
+struct Grandfather {
+  int field;
+};
+
+struct Father : public Grandfather {};
+struct Son : public Father {};
+
+void test() {
+  int Son::*sf = &Son::field;
+  Grandfather grandpa;
+  grandpa.field = 10;
+  int Grandfather::*gpf1 = static_cast(sf);
+  int Grandfather::*gpf2 = static_cast(static_cast(sf));
+  int Grandfather::*gpf3 = static_cast(static_cast(static_cast(sf)));
+  clang_analyzer_eval(grandpa.*gpf1 == 10); // expected-warning{{TRUE}}
+  clang_analyzer_eval(grandpa.*gpf2 == 10); // expected-warning{{TRUE}}
+  clang_analyzer_eval(grandpa.*gpf3 == 10); // expected-warning{{TRUE}}
+}
+} // namespace testStaticCasting
Index: clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
@@ -526,10 +526,11 @@
   case CK_ReinterpretMemberPointer: {
 SVal V = state->getSVal(Ex, LCtx);
 if (auto PTMSV = V.getAs()) {
-  SVal CastedPTMSV = svalBuilder.makePointerToMember(
-  getBasicVals().accumCXXBase(
+  SVal CastedPTMSV =
+  svalBuilder.makePointerToMember(getBasicVals().accumCXXBase(
   llvm::make_range(
-  CastE->path_begin(), CastE->path_end()), *PTMSV));
+  CastE->path_begin(), CastE->path_end()),
+  *PTMSV, CastE->getCastKind()));
   state = state->BindExpr(CastE, LCtx, CastedPTMSV);
   Bldr.generateNode(CastE, Pred, state);
   continue;
Index: clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
===
--- clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
+++ clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
@@ -21,8 +21,10 @@
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/ImmutableList.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallPtrSet.h"
 #include 
 #include 
+#include 
 #include 
 
 using namespace clang;
@@ -178,26 +180,63 @@
 
 const PointerToMemberData *BasicValueFactory::accumCXXBase(
 llvm::iterator_range PathRange,
-const nonloc::PointerToMember &PTM) {
+const nonloc::PointerToMember &PTM, const CastKind &kind) {
+  assert((kind == CK_DerivedToBaseMemberPointer ||
+  kind == CK_BaseToDerivedMemberPointer ||
+  kind == CK_ReinterpretMemberPointer) &&
+ "accumCXXBase called with wrong CastKind");
   nonloc::PointerToMember::PTMDataType PTMDT = PTM.getPTMData();
   const NamedDecl *ND = nullptr;
-  llvm::ImmutableList PathList;
+  llvm::ImmutableList BaseSpecList;
 
   if (PTMDT.isNull() || PTMDT.is()) {
 if (PTMDT.is())
   ND = PTMDT.get();
 
-PathList = CXXBaseListFactory.getEmptyList();
+BaseSpecList = CXXBaseListFactory.getEmptyList();
   } else { // const PointerToMemberData *
 const PointerToMemberData *PTMD = PTMDT.get();
 ND = PTMD->getDeclaratorDecl();
 
-PathList = PTMD->getCXXBaseList();
+BaseSpecList = PTMD->getCXXBaseList();
   }
 
-  for (const auto &I : llvm::reverse(PathRange))
-PathList = prependCXXBase(I, PathList);
-  return getPointerToMemberData(ND, PathList);
+  if (kind == CK_DerivedToBaseMemberPointer) {
+// Here we pop off matching CXXBaseSpecifiers from BaseSpecList.
+// Because, CK_DerivedToBaseMemberPointer comes from a static_cast and
+// serves to remove a matching implicit cast. Note that static_cast's that
+// are no-ops do not count since they produce an empty PathRange, a nice
+// thing about Clang AST.
+
+// First we need to make sure that there are no-repetitions in BaseSpecList
+llvm::SmallPtrSet BaseSpecSeen;
+for (const auto &BaseSpec : BaseSpecList) {
+  auto BaseType = BaseSpec->getType();
+  assert(BaseSpecSeen.find(BaseType) == BaseSpecSeen.end() &&
+ "CXXBaseSpecifier list of PointerToMemberData must not have "
+ "repeated elements");
+  BaseSpecSeen.insert(BaseType);
+ 

[PATCH] D95877: [analyzer] Fix static_cast on pointer-to-member handling

2021-02-03 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD marked 2 inline comments as done.
RedDocMD added a comment.

@vsavchenko , I have used the logic that you suggested and put in a better 
assertion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95877

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


  1   2   3   >