[PATCH] D122734: [CUDA][HIP] Fix mangling number for local struct

2022-04-22 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 424688.
yaxunl marked 5 inline comments as done.
yaxunl added a comment.

Revised by Artem's and Reid's comments.


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

https://reviews.llvm.org/D122734

Files:
  clang/include/clang/AST/ASTContext.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/MicrosoftCXXABI.cpp
  clang/lib/CodeGen/CGCUDANV.cpp
  clang/test/CodeGenCUDA/struct-mangling-number.cu

Index: clang/test/CodeGenCUDA/struct-mangling-number.cu
===
--- /dev/null
+++ clang/test/CodeGenCUDA/struct-mangling-number.cu
@@ -0,0 +1,68 @@
+// RUN: %clang_cc1 -emit-llvm -o - -aux-triple x86_64-pc-windows-msvc \
+// RUN:   -fms-extensions -triple amdgcn-amd-amdhsa \
+// RUN:   -target-cpu gfx1030 -fcuda-is-device -x hip %s \
+// RUN:   | FileCheck -check-prefix=DEV %s
+
+// RUN: %clang_cc1 -emit-llvm -o - -triple x86_64-pc-windows-msvc \
+// RUN:   -fms-extensions -aux-triple amdgcn-amd-amdhsa \
+// RUN:   -aux-target-cpu gfx1030 -x hip %s \
+// RUN:   | FileCheck -check-prefix=HOST %s
+
+// RUN: %clang_cc1 -emit-llvm -o - -triple x86_64-pc-windows-msvc \
+// RUN:   -fms-extensions -aux-triple amdgcn-amd-amdhsa \
+// RUN:   -aux-target-cpu gfx1030 -x hip %s \
+// RUN:   | FileCheck -check-prefix=HOST-NEG %s
+
+// RUN: %clang_cc1 -emit-llvm -o - -triple x86_64-pc-windows-msvc \
+// RUN:   -fms-extensions -x c++ %s \
+// RUN:   | FileCheck -check-prefix=CPP %s
+
+#if __HIP__
+#include "Inputs/cuda.h"
+#endif
+
+// Check local struct 'Op' uses Itanium mangling number instead of MSVC mangling
+// number in device side name mangling. It is the same in device and host
+// compilation.
+
+// DEV: define amdgpu_kernel void @_Z6kernelIZN4TestIiE3runEvE2OpEvv(
+
+// HOST-DAG: @{{.*}} = {{.*}}c"_Z6kernelIZN4TestIiE3runEvE2OpEvv\00"
+
+// HOST-NEG-NOT: @{{.*}} = {{.*}}c"_Z6kernelIZN4TestIiE3runEvE2Op_1Evv\00"
+#if __HIP__
+template
+__attribute__((global)) void kernel()
+{
+}
+#endif
+
+// Check local struct 'Op' uses MSVC mangling number in host function name mangling.
+// It is the same when compiled as HIP or C++ program.
+
+// HOST-DAG: call void @"??$fun@UOp@?2??run@?$Test@H@@QEAAXXZ@@@YAXXZ"()
+// CPP:  call void @"??$fun@UOp@?2??run@?$Test@H@@QEAAXXZ@@@YAXXZ"()
+template
+void fun()
+{
+}
+
+template 
+class Test {
+public:
+  void run()
+  {
+struct Op
+{
+};
+#if __HIP__
+kernel<<<1, 1>>>();
+#endif
+fun();
+  }
+};
+
+int main() {
+  Test A;
+  A.run();
+}
Index: clang/lib/CodeGen/CGCUDANV.cpp
===
--- clang/lib/CodeGen/CGCUDANV.cpp
+++ clang/lib/CodeGen/CGCUDANV.cpp
@@ -24,6 +24,7 @@
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/ReplaceConstant.h"
 #include "llvm/Support/Format.h"
+#include "llvm/Support/SaveAndRestore.h"
 
 using namespace clang;
 using namespace CodeGen;
@@ -260,6 +261,8 @@
 }
 
 std::string CGNVCUDARuntime::getDeviceSideName(const NamedDecl *ND) {
+  llvm::SaveAndRestore MangleAsDevice(
+  CGM.getContext().CUDAMangleDeviceNameInHostCompilation, true);
   GlobalDecl GD;
   // D could be either a kernel or a variable.
   if (auto *FD = dyn_cast(ND))
Index: clang/lib/AST/MicrosoftCXXABI.cpp
===
--- clang/lib/AST/MicrosoftCXXABI.cpp
+++ clang/lib/AST/MicrosoftCXXABI.cpp
@@ -208,6 +208,20 @@
   unsigned getDeviceManglingNumber(const CXXMethodDecl *CallOperator) override {
 return DeviceCtx->getManglingNumber(CallOperator);
   }
+
+  unsigned getManglingNumber(const TagDecl *TD,
+ unsigned MSLocalManglingNumber) override {
+unsigned DeviceN = DeviceCtx->getManglingNumber(TD, MSLocalManglingNumber);
+unsigned HostN =
+MicrosoftNumberingContext::getManglingNumber(TD, MSLocalManglingNumber);
+if (DeviceN > 0x || HostN > 0x) {
+  DiagnosticsEngine  = TD->getASTContext().getDiagnostics();
+  unsigned DiagID = Diags.getCustomDiagID(
+  DiagnosticsEngine::Error, "Mangling number exceeds limit (65535)");
+  Diags.Report(TD->getLocation(), DiagID);
+}
+return (DeviceN << 16) | HostN;
+  }
 };
 
 class MSSYCLNumberingContext : public MicrosoftNumberingContext {
Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -11754,7 +11754,14 @@
 
 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
   auto I = MangleNumbers.find(ND);
-  return I != MangleNumbers.end() ? I->second : 1;
+  unsigned Res = I != MangleNumbers.end() ? I->second : 1;
+  if (!LangOpts.CUDA || LangOpts.CUDAIsDevice)
+return Res;
+
+  // CUDA/HIP host compilation encodes host and device mangling numbers
+  // as lower and upper half of 32 bit integer.
+  Res = CUDAMangleDeviceNameInHostCompilation ? Res >> 16 : Res & 0x;
+  return Res > 

[PATCH] D122734: [CUDA][HIP] Fix mangling number for local struct

2022-04-22 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked 7 inline comments as done.
yaxunl added inline comments.



Comment at: clang/include/clang/AST/ASTContext.h:682
+/// Current name mangling is for device name in host compilation.
+bool MangleDeviceNameInHostCompilation = false;
+  } CUDANameMangleCtx;

rnk wrote:
> It doesn't feel right to store mutable state here in ASTContext. You are 
> effectively using this as a global variable to thread a boolean through to 
> `ASTContext::getManglingNumber`, which is called from the mangler. The 
> boolean indicates of host or device mangling numbers are desired for this 
> particular mangling. Is that more or less correct?
> 
> This makes me think that it was perhaps a mistake to store mangling numbers 
> in the AST Context in the first place. If we stored them in the mangling 
> context instead, I think we'd get the right behavior out of the box. Is that 
> correct? It it feasible to make that change?
> It doesn't feel right to store mutable state here in ASTContext. You are 
> effectively using this as a global variable to thread a boolean through to 
> `ASTContext::getManglingNumber`, which is called from the mangler. The 
> boolean indicates of host or device mangling numbers are desired for this 
> particular mangling. Is that more or less correct?
> 
> This makes me think that it was perhaps a mistake to store mangling numbers 
> in the AST Context in the first place. If we stored them in the mangling 
> context instead, I think we'd get the right behavior out of the box. Is that 
> correct? It it feasible to make that change?

It is possible but I feel it is too invasive. Mangling numbers need to be 
calculated during construction of AST since it is context dependent. Mangle 
contexts are created in ABI of codegen. To store mangling numbers in mangling 
contexts, we need to move mangling contexts from ABI to ASTContext. We also 
need to add device mangling context in ASTContext. Then for each use of get/set 
mangling number API, we need to add get/set device mangling number API. That 
would need lots of changes.

I would see the state added to ASTContext by my approach from the perspective 
of single source language. The program contains both device code and host code. 
Ideally the compiler should be able to compile the device code with device 
target and ABI and compile the host code with host target ABI and switch the 
target freely during codegen. When we try to get the device side mangled name 
in host compilation, what we trying to do is switch to device target 
momoentorily during the mangling. This needs a state in ASTContext indicating 
that we are doing mangling for device instead of host, therefore 
getManglingNumber should return device mangling number instead of host mangling 
number.



Comment at: clang/include/clang/AST/ASTContext.h:684
+  } CUDANameMangleCtx;
+  struct CUDANameMangleContextRAII {
+ASTContext 

rnk wrote:
> By the way, this looks like `SaveAndRestore`. Maybe you can use that in 
> the future.
Yes. SaveAndRestore serves the purpose. will use it.



Comment at: clang/lib/AST/ASTContext.cpp:11760
+
+  auto Cutoff = [](unsigned V) { return V > 1 ? V : 1; };
+  if (CUDANameMangleCtx.MangleDeviceNameInHostCompilation)

tra wrote:
> rnk wrote:
> > rnk wrote:
> > > tra wrote:
> > > > I think we should change the `MangleNumbers` instead to use uin64_t or, 
> > > > perhaps `unsigned[2]` or even `struct{ unsigned host; unsigned 
> > > > device;}`.
> > > > Reducing the max number of anything to just 64K will be prone to 
> > > > failing sooner or later. 
> > > IMO it would be simpler to set up a ternary instead of a lambda and two 
> > > returns:
> > >   Res = Cond ? (Res >> 16) : (Res & 0x);
> > >   return Res > 1 ? Res : 1;
> > I suspect we could live with a 64K mangling number limit, but that is low 
> > enough that we need to put in a check for overflow somewhere.
> If we'd produce a reasonable diagnostic for that, it might work. 
> 
> 
will do



Comment at: clang/lib/AST/ASTContext.cpp:11760-11763
+  auto Cutoff = [](unsigned V) { return V > 1 ? V : 1; };
+  if (CUDANameMangleCtx.MangleDeviceNameInHostCompilation)
+return Cutoff(Res >> 16);
+  return Cutoff(Res & 0x);

yaxunl wrote:
> tra wrote:
> > rnk wrote:
> > > rnk wrote:
> > > > tra wrote:
> > > > > I think we should change the `MangleNumbers` instead to use uin64_t 
> > > > > or, perhaps `unsigned[2]` or even `struct{ unsigned host; unsigned 
> > > > > device;}`.
> > > > > Reducing the max number of anything to just 64K will be prone to 
> > > > > failing sooner or later. 
> > > > IMO it would be simpler to set up a ternary instead of a lambda and two 
> > > > returns:
> > > >   Res = Cond ? (Res >> 16) : (Res & 0x);
> > > >   return Res > 1 ? Res : 1;
> > > I suspect we could live with a 64K mangling number limit, but that is low 
> > > enough that we need 

[PATCH] D124312: [Driver] Call hasFlag instead of hasArg

2022-04-22 Thread Akira Hatanaka via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3b578ae9088c: [Driver] Call hasFlag instead of hasArg 
(authored by ahatanak).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124312

Files:
  clang/lib/Driver/ToolChains/MSVC.cpp
  clang/test/Driver/msvc-static-rtti.cpp


Index: clang/test/Driver/msvc-static-rtti.cpp
===
--- clang/test/Driver/msvc-static-rtti.cpp
+++ clang/test/Driver/msvc-static-rtti.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang -target x86_64-pc-windows-msvc -fno-rtti -### %s 2>&1 | 
FileCheck %s -check-prefix STATIC-RTTI-DEF
-// RUN: %clang -target x86_64-pc-windows-msvc -frtti -### %s 2>&1 | FileCheck 
%s -check-prefix STATIC-RTTI-DEF-NOT
+// RUN: %clang -target x86_64-pc-windows-msvc -fno-rtti -### %s 2>&1 | 
FileCheck %s -check-prefix NO-RTTI
+// RUN: %clang -target x86_64-pc-windows-msvc -frtti -### %s 2>&1 | FileCheck 
%s -check-prefix RTTI
 
-// STATIC-RTTI-DEF: -D_HAS_STATIC_RTTI=0
-// STATIC-RTTI-DEF-NOT: -D_HAS_STATIC_RTTI=0
+// RTTI-NOT: -D_HAS_STATIC_RTTI=0
+// NO-RTTI: -D_HAS_STATIC_RTTI=0
Index: clang/lib/Driver/ToolChains/MSVC.cpp
===
--- clang/lib/Driver/ToolChains/MSVC.cpp
+++ clang/lib/Driver/ToolChains/MSVC.cpp
@@ -963,7 +963,7 @@
 Action::OffloadKind DeviceOffloadKind) const {
   // MSVC STL kindly allows removing all usages of typeid by defining
   // _HAS_STATIC_RTTI to 0. Do so, when compiling with -fno-rtti
-  if (DriverArgs.hasArg(options::OPT_fno_rtti, options::OPT_frtti,
-/*Default=*/false))
+  if (DriverArgs.hasFlag(options::OPT_fno_rtti, options::OPT_frtti,
+ /*Default=*/false))
 CC1Args.push_back("-D_HAS_STATIC_RTTI=0");
 }


Index: clang/test/Driver/msvc-static-rtti.cpp
===
--- clang/test/Driver/msvc-static-rtti.cpp
+++ clang/test/Driver/msvc-static-rtti.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang -target x86_64-pc-windows-msvc -fno-rtti -### %s 2>&1 | FileCheck %s -check-prefix STATIC-RTTI-DEF
-// RUN: %clang -target x86_64-pc-windows-msvc -frtti -### %s 2>&1 | FileCheck %s -check-prefix STATIC-RTTI-DEF-NOT
+// RUN: %clang -target x86_64-pc-windows-msvc -fno-rtti -### %s 2>&1 | FileCheck %s -check-prefix NO-RTTI
+// RUN: %clang -target x86_64-pc-windows-msvc -frtti -### %s 2>&1 | FileCheck %s -check-prefix RTTI
 
-// STATIC-RTTI-DEF: -D_HAS_STATIC_RTTI=0
-// STATIC-RTTI-DEF-NOT: -D_HAS_STATIC_RTTI=0
+// RTTI-NOT: -D_HAS_STATIC_RTTI=0
+// NO-RTTI: -D_HAS_STATIC_RTTI=0
Index: clang/lib/Driver/ToolChains/MSVC.cpp
===
--- clang/lib/Driver/ToolChains/MSVC.cpp
+++ clang/lib/Driver/ToolChains/MSVC.cpp
@@ -963,7 +963,7 @@
 Action::OffloadKind DeviceOffloadKind) const {
   // MSVC STL kindly allows removing all usages of typeid by defining
   // _HAS_STATIC_RTTI to 0. Do so, when compiling with -fno-rtti
-  if (DriverArgs.hasArg(options::OPT_fno_rtti, options::OPT_frtti,
-/*Default=*/false))
+  if (DriverArgs.hasFlag(options::OPT_fno_rtti, options::OPT_frtti,
+ /*Default=*/false))
 CC1Args.push_back("-D_HAS_STATIC_RTTI=0");
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 3b578ae - [Driver] Call hasFlag instead of hasArg

2022-04-22 Thread Akira Hatanaka via cfe-commits

Author: Akira Hatanaka
Date: 2022-04-22T20:14:50-07:00
New Revision: 3b578ae9088caf08932dc7d18e87d2a17fb4f7a8

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

LOG: [Driver] Call hasFlag instead of hasArg

`_HAS_STATIC_RTTI` should be set to 0 only by `-fno-rtti` according to the
summary of https://reviews.llvm.org/D103771.

rdar://92039243

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/MSVC.cpp
clang/test/Driver/msvc-static-rtti.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/MSVC.cpp 
b/clang/lib/Driver/ToolChains/MSVC.cpp
index 3fc02eefe11b0..a470d44a50148 100644
--- a/clang/lib/Driver/ToolChains/MSVC.cpp
+++ b/clang/lib/Driver/ToolChains/MSVC.cpp
@@ -963,7 +963,7 @@ void MSVCToolChain::addClangTargetOptions(
 Action::OffloadKind DeviceOffloadKind) const {
   // MSVC STL kindly allows removing all usages of typeid by defining
   // _HAS_STATIC_RTTI to 0. Do so, when compiling with -fno-rtti
-  if (DriverArgs.hasArg(options::OPT_fno_rtti, options::OPT_frtti,
-/*Default=*/false))
+  if (DriverArgs.hasFlag(options::OPT_fno_rtti, options::OPT_frtti,
+ /*Default=*/false))
 CC1Args.push_back("-D_HAS_STATIC_RTTI=0");
 }

diff  --git a/clang/test/Driver/msvc-static-rtti.cpp 
b/clang/test/Driver/msvc-static-rtti.cpp
index b352f07bc6c10..680c5f8518b2d 100644
--- a/clang/test/Driver/msvc-static-rtti.cpp
+++ b/clang/test/Driver/msvc-static-rtti.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang -target x86_64-pc-windows-msvc -fno-rtti -### %s 2>&1 | 
FileCheck %s -check-prefix STATIC-RTTI-DEF
-// RUN: %clang -target x86_64-pc-windows-msvc -frtti -### %s 2>&1 | FileCheck 
%s -check-prefix STATIC-RTTI-DEF-NOT
+// RUN: %clang -target x86_64-pc-windows-msvc -fno-rtti -### %s 2>&1 | 
FileCheck %s -check-prefix NO-RTTI
+// RUN: %clang -target x86_64-pc-windows-msvc -frtti -### %s 2>&1 | FileCheck 
%s -check-prefix RTTI
 
-// STATIC-RTTI-DEF: -D_HAS_STATIC_RTTI=0
-// STATIC-RTTI-DEF-NOT: -D_HAS_STATIC_RTTI=0
+// RTTI-NOT: -D_HAS_STATIC_RTTI=0
+// NO-RTTI: -D_HAS_STATIC_RTTI=0



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


[clang] 72e00c4 - [asan] Don't enable detect_stack_use_after_return on Windows

2022-04-22 Thread Vitaly Buka via cfe-commits

Author: Vitaly Buka
Date: 2022-04-22T19:10:30-07:00
New Revision: 72e00c45a4e7b1651c0fdfe4bfc12ff5e2a201d3

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

LOG: [asan] Don't enable detect_stack_use_after_return on Windows

It's not clear how ready it's there.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
compiler-rt/lib/asan/asan_flags.inc

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 066a0e1977324..3f1c86cdc3aca 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -174,7 +174,7 @@ Non-comprehensive list of changes in this release
   - Remove anonymous tag locations.
   - Beautify dump format, add indent for nested struct and struct members.
 - Previously disabled sanitizer options now enabled by default:
-  - ASAN_OPTIONS=detect_stack_use_after_return=1.
+  - ASAN_OPTIONS=detect_stack_use_after_return=1 (except Windows).
   - MSAN_OPTIONS=poison_in_dtor=1.
 
 New Compiler Flags

diff  --git a/compiler-rt/lib/asan/asan_flags.inc 
b/compiler-rt/lib/asan/asan_flags.inc
index 31d4b3a6f3cc5..04023234bc945 100644
--- a/compiler-rt/lib/asan/asan_flags.inc
+++ b/compiler-rt/lib/asan/asan_flags.inc
@@ -49,7 +49,7 @@ ASAN_FLAG(
 "to find more errors.")
 ASAN_FLAG(bool, replace_intrin, true,
   "If set, uses custom wrappers for memset/memcpy/memmove intrinsics.")
-ASAN_FLAG(bool, detect_stack_use_after_return, true,
+ASAN_FLAG(bool, detect_stack_use_after_return, !SANITIZER_WINDOWS,
   "Enables stack-use-after-return checking at run-time.")
 ASAN_FLAG(int, min_uar_stack_size_log, 16, // We can't do smaller anyway.
   "Minimum fake stack size log.")



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


[PATCH] D124316: [clang-tidy] Modernize-macro-to-enum should skip macros used in other macros

2022-04-22 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood created this revision.
LegalizeAdulthood added reviewers: aaron.ballman, alexfh.
LegalizeAdulthood added a project: clang-tools-extra.
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a project: All.
LegalizeAdulthood requested review of this revision.

If a macro is used in the expansion of another macro, that can cause
a compile error if the macro is replaced with an enum.  Token-pasting is
an example where converting a macro defined as an integral constant can
cause code to no longer compile.

This change causes such macros to be skipped from the conversion
process in order to prevent fixits from creating code that no longer
compiles.

A subsequent enhancement will examine macro usage in more detail to
allow more cases to be handled without breaking code.

Fixes #54948 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124316

Files:
  clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
@@ -281,27 +281,14 @@
 #define EPS2 1e5
 #define EPS3 1.
 
-#define DO_RED draw(RED)
-#define DO_GREEN draw(GREEN)
-#define DO_BLUE draw(BLUE)
-
-#define FN_RED(x) draw(RED | x)
-#define FN_GREEN(x) draw(GREEN | x)
-#define FN_BLUE(x) draw(BLUE | x)
-
 extern void draw(unsigned int Color);
 
 void f()
 {
+  // Usage of macros converted to enums should still compile.
   draw(RED);
-  draw(GREEN);
-  draw(BLUE);
-  DO_RED;
-  DO_GREEN;
-  DO_BLUE;
-  FN_RED(0);
-  FN_GREEN(0);
-  FN_BLUE(0);
+  draw(GREEN | RED);
+  draw(BLUE + RED);
 }
 
 // Ignore macros defined inside a top-level function definition.
@@ -389,3 +376,17 @@
 constexpr int
 #define INSIDE17 17
 value = INSIDE17;
+
+// Ignore macros used in the expansion of other macros
+#define INSIDE18 18
+#define INSIDE19 19
+
+#define CONCAT(n_, s_) n_##s_
+#define FN_NAME(n_, s_) CONCAT(n_, s_)
+
+extern void FN_NAME(g, INSIDE18)();
+
+void gg()
+{
+g18();
+}
Index: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
@@ -226,7 +226,8 @@
   void conditionStart(const SourceLocation );
   void checkCondition(SourceRange ConditionRange);
   void checkName(const Token );
-  void rememberExpressionName(const Token );
+  void rememberExpressionName(const Token );
+  void rememberExpressionTokens(const ArrayRef );
   void invalidateExpressionNames();
   void issueDiagnostics();
   void warnMacroEnum(const EnumMacro ) const;
@@ -302,14 +303,21 @@
   });
 }
 
-void MacroToEnumCallbacks::rememberExpressionName(const Token ) {
-  std::string Id = getTokenName(MacroNameTok).str();
+void MacroToEnumCallbacks::rememberExpressionName(const Token ) {
+  std::string Id = getTokenName(Tok).str();
   auto Pos = llvm::lower_bound(ExpressionNames, Id);
   if (Pos == ExpressionNames.end() || *Pos != Id) {
 ExpressionNames.insert(Pos, Id);
   }
 }
 
+void MacroToEnumCallbacks::rememberExpressionTokens(
+const ArrayRef ) {
+  for (Token Tok : MacroTokens)
+if (Tok.isAnyIdentifier())
+  rememberExpressionName(Tok);
+}
+
 void MacroToEnumCallbacks::FileChanged(SourceLocation Loc,
FileChangeReason Reason,
SrcMgr::CharacteristicKind FileType,
@@ -326,6 +334,8 @@
   CurrentFile = ();
 }
 
+// Any defined but rejected macro is scanned for identifiers that
+// are to be excluded as enums.
 void MacroToEnumCallbacks::MacroDefined(const Token ,
 const MacroDirective *MD) {
   // Include guards are never candidates for becoming an enum.
@@ -342,8 +352,12 @@
 
   const MacroInfo *Info = MD->getMacroInfo();
   ArrayRef MacroTokens = Info->tokens();
-  if (Info->isFunctionLike() || Info->isBuiltinMacro() || MacroTokens.empty())
+  if (Info->isBuiltinMacro() || MacroTokens.empty())
+return;
+  if (Info->isFunctionLike()) {
+rememberExpressionTokens(MacroTokens);
 return;
+  }
 
   // Return Lit when +Lit, -Lit or ~Lit; otherwise return Unknown.
   Token Unknown;
@@ -378,17 +392,22 @@
 else if (Size == 2)
   // It can be +Lit, -Lit or ~Lit.
   Tok = GetUnopArg(MacroTokens[Begin], MacroTokens[End]);
-else
+else {
   // Zero or too many tokens after we stripped matching parens.
+  rememberExpressionTokens(MacroTokens);
   return;
+}
   } else if (MacroTokens.size() == 2) {
 // It can be +Lit, -Lit, or ~Lit.
 Tok = GetUnopArg(MacroTokens.front(), 

[clang] a7f9f2f - [fixup] Handle enum constant `Lang_OBJC` introduced in 4604db94.

2022-04-22 Thread Volodymyr Sapsai via cfe-commits

Author: Volodymyr Sapsai
Date: 2022-04-22T17:59:17-07:00
New Revision: a7f9f2fea506fa213e4ce9c6230a816cd5bcfa38

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

LOG: [fixup] Handle enum constant `Lang_OBJC` introduced in 4604db94.

Added: 


Modified: 
clang/lib/Testing/CommandLineArgs.cpp

Removed: 




diff  --git a/clang/lib/Testing/CommandLineArgs.cpp 
b/clang/lib/Testing/CommandLineArgs.cpp
index c04702f689028..bf517e2dd312e 100644
--- a/clang/lib/Testing/CommandLineArgs.cpp
+++ b/clang/lib/Testing/CommandLineArgs.cpp
@@ -72,6 +72,9 @@ std::vector getCC1ArgsForTesting(TestLanguage 
Lang) {
   case Lang_CXX20:
 Args = {"-std=c++20"};
 break;
+  case Lang_OBJC:
+Args = {"-xobjective-c"};
+break;
   case Lang_OBJCXX:
 Args = {"-xobjective-c++"};
 break;



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


[PATCH] D116280: [clang] adds unary type trait checks as compiler built-ins

2022-04-22 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb updated this revision to Diff 424673.
cjdb added a comment.

fixes formatting


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116280

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/TokenKinds.def
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/SemaCXX/type-traits.cpp

Index: clang/test/SemaCXX/type-traits.cpp
===
--- clang/test/SemaCXX/type-traits.cpp
+++ clang/test/SemaCXX/type-traits.cpp
@@ -345,11 +345,19 @@
 }
 
 typedef Enum EnumType;
+typedef EnumClass EnumClassType;
 
 void is_enum()
 {
   { int arr[T(__is_enum(Enum))]; }
   { int arr[T(__is_enum(EnumType))]; }
+  { int arr[T(__is_enum(SignedEnum))]; }
+  { int arr[T(__is_enum(UnsignedEnum))]; }
+
+  { int arr[T(__is_enum(EnumClass))]; }
+  { int arr[T(__is_enum(EnumClassType))]; }
+  { int arr[T(__is_enum(SignedEnumClass))]; }
+  { int arr[T(__is_enum(UnsignedEnumClass))]; }
 
   { int arr[F(__is_enum(int))]; }
   { int arr[F(__is_enum(Union))]; }
@@ -363,6 +371,29 @@
   { int arr[F(__is_enum(HasAnonymousUnion))]; }
 }
 
+void is_scoped_enum() {
+  { int arr[F(__is_scoped_enum(Enum))]; }
+  { int arr[F(__is_scoped_enum(EnumType))]; }
+  { int arr[F(__is_scoped_enum(SignedEnum))]; }
+  { int arr[F(__is_scoped_enum(UnsignedEnum))]; }
+
+  { int arr[T(__is_scoped_enum(EnumClass))]; }
+  { int arr[T(__is_scoped_enum(EnumClassType))]; }
+  { int arr[T(__is_scoped_enum(SignedEnumClass))]; }
+  { int arr[T(__is_scoped_enum(UnsignedEnumClass))]; }
+
+  { int arr[F(__is_scoped_enum(int))]; }
+  { int arr[F(__is_scoped_enum(Union))]; }
+  { int arr[F(__is_scoped_enum(Int))]; }
+  { int arr[F(__is_scoped_enum(IntAr))]; }
+  { int arr[F(__is_scoped_enum(UnionAr))]; }
+  { int arr[F(__is_scoped_enum(Derives))]; }
+  { int arr[F(__is_scoped_enum(ClassType))]; }
+  { int arr[F(__is_scoped_enum(cvoid))]; }
+  { int arr[F(__is_scoped_enum(IntArNB))]; }
+  { int arr[F(__is_scoped_enum(HasAnonymousUnion))]; }
+}
+
 struct FinalClass final {
 };
 
@@ -702,6 +733,106 @@
   int t31[F(__is_array(cvoid*))];
 }
 
+void is_bounded_array(int n) {
+  int t01[T(__is_bounded_array(IntAr))];
+  int t02[F(__is_bounded_array(IntArNB))];
+  int t03[T(__is_bounded_array(UnionAr))];
+
+  int t10[F(__is_bounded_array(void))];
+  int t11[F(__is_bounded_array(cvoid))];
+  int t12[F(__is_bounded_array(float))];
+  int t13[F(__is_bounded_array(double))];
+  int t14[F(__is_bounded_array(long double))];
+  int t15[F(__is_bounded_array(bool))];
+  int t16[F(__is_bounded_array(char))];
+  int t17[F(__is_bounded_array(signed char))];
+  int t18[F(__is_bounded_array(unsigned char))];
+  int t19[F(__is_bounded_array(wchar_t))];
+  int t20[F(__is_bounded_array(short))];
+  int t21[F(__is_bounded_array(unsigned short))];
+  int t22[F(__is_bounded_array(int))];
+  int t23[F(__is_bounded_array(unsigned int))];
+  int t24[F(__is_bounded_array(long))];
+  int t25[F(__is_bounded_array(unsigned long))];
+  int t26[F(__is_bounded_array(Union))];
+  int t27[F(__is_bounded_array(Derives))];
+  int t28[F(__is_bounded_array(ClassType))];
+  int t29[F(__is_bounded_array(Enum))];
+  int t30[F(__is_bounded_array(void *))];
+  int t31[F(__is_bounded_array(cvoid *))];
+
+  int t32[n];
+  (void)__is_bounded_array(decltype(t32)); // expected-error{{variable length arrays are not supported for '__is_bounded_array'}}
+}
+
+void is_unbounded_array(int n) {
+  int t01[F(__is_unbounded_array(IntAr))];
+  int t02[T(__is_unbounded_array(IntArNB))];
+  int t03[F(__is_unbounded_array(UnionAr))];
+
+  int t10[F(__is_unbounded_array(void))];
+  int t11[F(__is_unbounded_array(cvoid))];
+  int t12[F(__is_unbounded_array(float))];
+  int t13[F(__is_unbounded_array(double))];
+  int t14[F(__is_unbounded_array(long double))];
+  int t15[F(__is_unbounded_array(bool))];
+  int t16[F(__is_unbounded_array(char))];
+  int t17[F(__is_unbounded_array(signed char))];
+  int t18[F(__is_unbounded_array(unsigned char))];
+  int t19[F(__is_unbounded_array(wchar_t))];
+  int t20[F(__is_unbounded_array(short))];
+  int t21[F(__is_unbounded_array(unsigned short))];
+  int t22[F(__is_unbounded_array(int))];
+  int t23[F(__is_unbounded_array(unsigned int))];
+  int t24[F(__is_unbounded_array(long))];
+  int t25[F(__is_unbounded_array(unsigned long))];
+  int t26[F(__is_unbounded_array(Union))];
+  int t27[F(__is_unbounded_array(Derives))];
+  int t28[F(__is_unbounded_array(ClassType))];
+  int t29[F(__is_unbounded_array(Enum))];
+  int t30[F(__is_unbounded_array(void *))];
+  int t31[F(__is_unbounded_array(cvoid *))];
+
+  int t32[n];
+  (void)__is_unbounded_array(decltype(t32)); // expected-error{{variable length arrays are not supported for '__is_unbounded_array'}}
+}
+
+void is_referenceable() {
+  { int 

[PATCH] D124312: [Driver] Call hasFlag instead of hasArg

2022-04-22 Thread Markus Böck via Phabricator via cfe-commits
zero9178 accepted this revision.
zero9178 added a comment.
This revision is now accepted and ready to land.

Ouch! Two bugs, and the one in the testsuite covered up the former one. Thank 
you for noticing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124312

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


[PATCH] D116280: [clang] adds unary type trait checks as compiler built-ins

2022-04-22 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb updated this revision to Diff 424672.
cjdb marked 5 inline comments as done.
cjdb edited the summary of this revision.
cjdb added a comment.

- handles VLAs
- adds `__is_referenceable` which is used by portions of the standard library


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116280

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/TokenKinds.def
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/SemaCXX/type-traits.cpp

Index: clang/test/SemaCXX/type-traits.cpp
===
--- clang/test/SemaCXX/type-traits.cpp
+++ clang/test/SemaCXX/type-traits.cpp
@@ -345,11 +345,19 @@
 }
 
 typedef Enum EnumType;
+typedef EnumClass EnumClassType;
 
 void is_enum()
 {
   { int arr[T(__is_enum(Enum))]; }
   { int arr[T(__is_enum(EnumType))]; }
+  { int arr[T(__is_enum(SignedEnum))]; }
+  { int arr[T(__is_enum(UnsignedEnum))]; }
+
+  { int arr[T(__is_enum(EnumClass))]; }
+  { int arr[T(__is_enum(EnumClassType))]; }
+  { int arr[T(__is_enum(SignedEnumClass))]; }
+  { int arr[T(__is_enum(UnsignedEnumClass))]; }
 
   { int arr[F(__is_enum(int))]; }
   { int arr[F(__is_enum(Union))]; }
@@ -363,6 +371,29 @@
   { int arr[F(__is_enum(HasAnonymousUnion))]; }
 }
 
+void is_scoped_enum() {
+  { int arr[F(__is_scoped_enum(Enum))]; }
+  { int arr[F(__is_scoped_enum(EnumType))]; }
+  { int arr[F(__is_scoped_enum(SignedEnum))]; }
+  { int arr[F(__is_scoped_enum(UnsignedEnum))]; }
+
+  { int arr[T(__is_scoped_enum(EnumClass))]; }
+  { int arr[T(__is_scoped_enum(EnumClassType))]; }
+  { int arr[T(__is_scoped_enum(SignedEnumClass))]; }
+  { int arr[T(__is_scoped_enum(UnsignedEnumClass))]; }
+
+  { int arr[F(__is_scoped_enum(int))]; }
+  { int arr[F(__is_scoped_enum(Union))]; }
+  { int arr[F(__is_scoped_enum(Int))]; }
+  { int arr[F(__is_scoped_enum(IntAr))]; }
+  { int arr[F(__is_scoped_enum(UnionAr))]; }
+  { int arr[F(__is_scoped_enum(Derives))]; }
+  { int arr[F(__is_scoped_enum(ClassType))]; }
+  { int arr[F(__is_scoped_enum(cvoid))]; }
+  { int arr[F(__is_scoped_enum(IntArNB))]; }
+  { int arr[F(__is_scoped_enum(HasAnonymousUnion))]; }
+}
+
 struct FinalClass final {
 };
 
@@ -702,6 +733,106 @@
   int t31[F(__is_array(cvoid*))];
 }
 
+void is_bounded_array(int n) {
+  int t01[T(__is_bounded_array(IntAr))];
+  int t02[F(__is_bounded_array(IntArNB))];
+  int t03[T(__is_bounded_array(UnionAr))];
+
+  int t10[F(__is_bounded_array(void))];
+  int t11[F(__is_bounded_array(cvoid))];
+  int t12[F(__is_bounded_array(float))];
+  int t13[F(__is_bounded_array(double))];
+  int t14[F(__is_bounded_array(long double))];
+  int t15[F(__is_bounded_array(bool))];
+  int t16[F(__is_bounded_array(char))];
+  int t17[F(__is_bounded_array(signed char))];
+  int t18[F(__is_bounded_array(unsigned char))];
+  int t19[F(__is_bounded_array(wchar_t))];
+  int t20[F(__is_bounded_array(short))];
+  int t21[F(__is_bounded_array(unsigned short))];
+  int t22[F(__is_bounded_array(int))];
+  int t23[F(__is_bounded_array(unsigned int))];
+  int t24[F(__is_bounded_array(long))];
+  int t25[F(__is_bounded_array(unsigned long))];
+  int t26[F(__is_bounded_array(Union))];
+  int t27[F(__is_bounded_array(Derives))];
+  int t28[F(__is_bounded_array(ClassType))];
+  int t29[F(__is_bounded_array(Enum))];
+  int t30[F(__is_bounded_array(void *))];
+  int t31[F(__is_bounded_array(cvoid *))];
+
+  int t32[n];
+  (void)__is_bounded_array(decltype(t32)); // expected-error{{variable length arrays are not supported for '__is_bounded_array'}}
+}
+
+void is_unbounded_array(int n) {
+  int t01[F(__is_unbounded_array(IntAr))];
+  int t02[T(__is_unbounded_array(IntArNB))];
+  int t03[F(__is_unbounded_array(UnionAr))];
+
+  int t10[F(__is_unbounded_array(void))];
+  int t11[F(__is_unbounded_array(cvoid))];
+  int t12[F(__is_unbounded_array(float))];
+  int t13[F(__is_unbounded_array(double))];
+  int t14[F(__is_unbounded_array(long double))];
+  int t15[F(__is_unbounded_array(bool))];
+  int t16[F(__is_unbounded_array(char))];
+  int t17[F(__is_unbounded_array(signed char))];
+  int t18[F(__is_unbounded_array(unsigned char))];
+  int t19[F(__is_unbounded_array(wchar_t))];
+  int t20[F(__is_unbounded_array(short))];
+  int t21[F(__is_unbounded_array(unsigned short))];
+  int t22[F(__is_unbounded_array(int))];
+  int t23[F(__is_unbounded_array(unsigned int))];
+  int t24[F(__is_unbounded_array(long))];
+  int t25[F(__is_unbounded_array(unsigned long))];
+  int t26[F(__is_unbounded_array(Union))];
+  int t27[F(__is_unbounded_array(Derives))];
+  int t28[F(__is_unbounded_array(ClassType))];
+  int t29[F(__is_unbounded_array(Enum))];
+  int t30[F(__is_unbounded_array(void *))];
+  int t31[F(__is_unbounded_array(cvoid *))];
+
+  int t32[n];
+  

[PATCH] D124288: [Index] Remove reference to `UnresolvedUsingIfExists`

2022-04-22 Thread Ben Barham via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG089b6efefc3d: [Index] Remove reference to 
`UnresolvedUsingIfExists` (authored by bnbarham).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124288

Files:
  clang/lib/Index/IndexDecl.cpp
  clang/test/Index/using_if_exists.cpp


Index: clang/test/Index/using_if_exists.cpp
===
--- /dev/null
+++ clang/test/Index/using_if_exists.cpp
@@ -0,0 +1,9 @@
+// RUN: c-index-test core -print-source-symbols -- %s -target 
x86_64-unknown-unknown 2>&1 | FileCheck %s
+
+namespace ns {
+//  void foo();
+}
+
+using ns::foo __attribute__((using_if_exists));
+// CHECK: [[@LINE-1]]:11 | using/C++ | foo | c:@UD@foo |  | Decl | 
rel: 0
+// CHECK-NOT: 
Index: clang/lib/Index/IndexDecl.cpp
===
--- clang/lib/Index/IndexDecl.cpp
+++ clang/lib/Index/IndexDecl.cpp
@@ -605,9 +605,16 @@
 const NamedDecl *Parent = dyn_cast(DC);
 IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), Parent,
  D->getLexicalDeclContext());
-for (const auto *I : D->shadows())
+for (const auto *I : D->shadows()) {
+  // Skip unresolved using decls - we already have a decl for the using
+  // itself, so there's not much point adding another decl or reference to
+  // refer to the same location.
+  if (isa(I->getUnderlyingDecl()))
+continue;
+
   IndexCtx.handleReference(I->getUnderlyingDecl(), D->getLocation(), 
Parent,
D->getLexicalDeclContext(), SymbolRoleSet());
+}
 return true;
   }
 


Index: clang/test/Index/using_if_exists.cpp
===
--- /dev/null
+++ clang/test/Index/using_if_exists.cpp
@@ -0,0 +1,9 @@
+// RUN: c-index-test core -print-source-symbols -- %s -target x86_64-unknown-unknown 2>&1 | FileCheck %s
+
+namespace ns {
+//  void foo();
+}
+
+using ns::foo __attribute__((using_if_exists));
+// CHECK: [[@LINE-1]]:11 | using/C++ | foo | c:@UD@foo |  | Decl | rel: 0
+// CHECK-NOT: 
Index: clang/lib/Index/IndexDecl.cpp
===
--- clang/lib/Index/IndexDecl.cpp
+++ clang/lib/Index/IndexDecl.cpp
@@ -605,9 +605,16 @@
 const NamedDecl *Parent = dyn_cast(DC);
 IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), Parent,
  D->getLexicalDeclContext());
-for (const auto *I : D->shadows())
+for (const auto *I : D->shadows()) {
+  // Skip unresolved using decls - we already have a decl for the using
+  // itself, so there's not much point adding another decl or reference to
+  // refer to the same location.
+  if (isa(I->getUnderlyingDecl()))
+continue;
+
   IndexCtx.handleReference(I->getUnderlyingDecl(), D->getLocation(), Parent,
D->getLexicalDeclContext(), SymbolRoleSet());
+}
 return true;
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 089b6ef - [Index] Remove reference to `UnresolvedUsingIfExists`

2022-04-22 Thread Ben Barham via cfe-commits

Author: Ben Barham
Date: 2022-04-22T17:19:33-07:00
New Revision: 089b6efefc3dbfc88e8fa92673eeb63ee78e4adf

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

LOG: [Index] Remove reference to `UnresolvedUsingIfExists`

Assuming `ns::foo` doesn't exist, given:
```
using ns::foo __attribute__((using_if_exists));
```

The AST will look something like:
UsingDecl
  UsingShadowDecl
UnresolvedUsingIfExistsDecl

Thus we end up adding a reference to `UnresolvedUsingIfExistsDecl` when
processing `UsingDecl`, but never add the decl itself. In this case the
decl is really the `UsingDecl` anyway though (which we do output), so it
makes more sense to just remove the extra reference.

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

Added: 
clang/test/Index/using_if_exists.cpp

Modified: 
clang/lib/Index/IndexDecl.cpp

Removed: 




diff  --git a/clang/lib/Index/IndexDecl.cpp b/clang/lib/Index/IndexDecl.cpp
index 3139aedaf01d4..635174500cee7 100644
--- a/clang/lib/Index/IndexDecl.cpp
+++ b/clang/lib/Index/IndexDecl.cpp
@@ -605,9 +605,16 @@ class IndexingDeclVisitor : public 
ConstDeclVisitor {
 const NamedDecl *Parent = dyn_cast(DC);
 IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), Parent,
  D->getLexicalDeclContext());
-for (const auto *I : D->shadows())
+for (const auto *I : D->shadows()) {
+  // Skip unresolved using decls - we already have a decl for the using
+  // itself, so there's not much point adding another decl or reference to
+  // refer to the same location.
+  if (isa(I->getUnderlyingDecl()))
+continue;
+
   IndexCtx.handleReference(I->getUnderlyingDecl(), D->getLocation(), 
Parent,
D->getLexicalDeclContext(), SymbolRoleSet());
+}
 return true;
   }
 

diff  --git a/clang/test/Index/using_if_exists.cpp 
b/clang/test/Index/using_if_exists.cpp
new file mode 100644
index 0..ed13dad9b1f74
--- /dev/null
+++ b/clang/test/Index/using_if_exists.cpp
@@ -0,0 +1,9 @@
+// RUN: c-index-test core -print-source-symbols -- %s -target 
x86_64-unknown-unknown 2>&1 | FileCheck %s
+
+namespace ns {
+//  void foo();
+}
+
+using ns::foo __attribute__((using_if_exists));
+// CHECK: [[@LINE-1]]:11 | using/C++ | foo | c:@UD@foo |  | Decl | 
rel: 0
+// CHECK-NOT: 



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


[PATCH] D124312: [Driver] Call hasFlag instead of hasArg

2022-04-22 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak created this revision.
ahatanak added a reviewer: zero9178.
ahatanak added a project: clang.
Herald added a project: All.
ahatanak requested review of this revision.
Herald added a subscriber: MaskRay.

`_HAS_STATIC_RTTI` should be set to 0 only by `-fno-rtti` according to the 
summary of https://reviews.llvm.org/D103771.

rdar://92039243


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124312

Files:
  clang/lib/Driver/ToolChains/MSVC.cpp
  clang/test/Driver/msvc-static-rtti.cpp


Index: clang/test/Driver/msvc-static-rtti.cpp
===
--- clang/test/Driver/msvc-static-rtti.cpp
+++ clang/test/Driver/msvc-static-rtti.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang -target x86_64-pc-windows-msvc -fno-rtti -### %s 2>&1 | 
FileCheck %s -check-prefix STATIC-RTTI-DEF
-// RUN: %clang -target x86_64-pc-windows-msvc -frtti -### %s 2>&1 | FileCheck 
%s -check-prefix STATIC-RTTI-DEF-NOT
+// RUN: %clang -target x86_64-pc-windows-msvc -fno-rtti -### %s 2>&1 | 
FileCheck %s -check-prefix NO-RTTI
+// RUN: %clang -target x86_64-pc-windows-msvc -frtti -### %s 2>&1 | FileCheck 
%s -check-prefix RTTI
 
-// STATIC-RTTI-DEF: -D_HAS_STATIC_RTTI=0
-// STATIC-RTTI-DEF-NOT: -D_HAS_STATIC_RTTI=0
+// RTTI-NOT: -D_HAS_STATIC_RTTI=0
+// NO-RTTI: -D_HAS_STATIC_RTTI=0
Index: clang/lib/Driver/ToolChains/MSVC.cpp
===
--- clang/lib/Driver/ToolChains/MSVC.cpp
+++ clang/lib/Driver/ToolChains/MSVC.cpp
@@ -963,7 +963,7 @@
 Action::OffloadKind DeviceOffloadKind) const {
   // MSVC STL kindly allows removing all usages of typeid by defining
   // _HAS_STATIC_RTTI to 0. Do so, when compiling with -fno-rtti
-  if (DriverArgs.hasArg(options::OPT_fno_rtti, options::OPT_frtti,
-/*Default=*/false))
+  if (DriverArgs.hasFlag(options::OPT_fno_rtti, options::OPT_frtti,
+ /*Default=*/false))
 CC1Args.push_back("-D_HAS_STATIC_RTTI=0");
 }


Index: clang/test/Driver/msvc-static-rtti.cpp
===
--- clang/test/Driver/msvc-static-rtti.cpp
+++ clang/test/Driver/msvc-static-rtti.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang -target x86_64-pc-windows-msvc -fno-rtti -### %s 2>&1 | FileCheck %s -check-prefix STATIC-RTTI-DEF
-// RUN: %clang -target x86_64-pc-windows-msvc -frtti -### %s 2>&1 | FileCheck %s -check-prefix STATIC-RTTI-DEF-NOT
+// RUN: %clang -target x86_64-pc-windows-msvc -fno-rtti -### %s 2>&1 | FileCheck %s -check-prefix NO-RTTI
+// RUN: %clang -target x86_64-pc-windows-msvc -frtti -### %s 2>&1 | FileCheck %s -check-prefix RTTI
 
-// STATIC-RTTI-DEF: -D_HAS_STATIC_RTTI=0
-// STATIC-RTTI-DEF-NOT: -D_HAS_STATIC_RTTI=0
+// RTTI-NOT: -D_HAS_STATIC_RTTI=0
+// NO-RTTI: -D_HAS_STATIC_RTTI=0
Index: clang/lib/Driver/ToolChains/MSVC.cpp
===
--- clang/lib/Driver/ToolChains/MSVC.cpp
+++ clang/lib/Driver/ToolChains/MSVC.cpp
@@ -963,7 +963,7 @@
 Action::OffloadKind DeviceOffloadKind) const {
   // MSVC STL kindly allows removing all usages of typeid by defining
   // _HAS_STATIC_RTTI to 0. Do so, when compiling with -fno-rtti
-  if (DriverArgs.hasArg(options::OPT_fno_rtti, options::OPT_frtti,
-/*Default=*/false))
+  if (DriverArgs.hasFlag(options::OPT_fno_rtti, options::OPT_frtti,
+ /*Default=*/false))
 CC1Args.push_back("-D_HAS_STATIC_RTTI=0");
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121176: [ASTStructuralEquivalence] Add support for comparing ObjCCategoryDecl.

2022-04-22 Thread Volodymyr Sapsai via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4604db9493ff: [ASTStructuralEquivalence] Add support for 
comparing ObjCCategoryDecl. (authored by vsapsai).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121176

Files:
  clang/include/clang/Testing/CommandLineArgs.h
  clang/lib/AST/ASTStructuralEquivalence.cpp
  clang/lib/Testing/CommandLineArgs.cpp
  clang/unittests/AST/MatchVerifier.h
  clang/unittests/AST/StructuralEquivalenceTest.cpp

Index: clang/unittests/AST/StructuralEquivalenceTest.cpp
===
--- clang/unittests/AST/StructuralEquivalenceTest.cpp
+++ clang/unittests/AST/StructuralEquivalenceTest.cpp
@@ -1120,6 +1120,187 @@
   EXPECT_FALSE(testStructuralMatch(t));
 }
 
+struct StructuralEquivalenceObjCCategoryTest : StructuralEquivalenceTest {};
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, MatchinCategoryNames) {
+  auto t = makeDecls("@interface A @end @interface A(X) @end",
+   "@interface A @end @interface A(X) @end",
+   Lang_OBJC, objcCategoryDecl());
+  EXPECT_TRUE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, CategoriesForDifferentClasses) {
+  auto t = makeDecls("@interface A @end @interface A(X) @end",
+   "@interface B @end @interface B(X) @end",
+   Lang_OBJC, objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, CategoriesWithDifferentNames) {
+  auto t = makeDecls("@interface A @end @interface A(X) @end",
+   "@interface A @end @interface A(Y) @end",
+   Lang_OBJC, objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, CategoryAndExtension) {
+  auto t = makeDecls("@interface A @end @interface A(X) @end",
+   "@interface A @end @interface A() @end",
+   Lang_OBJC, objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, MatchingProtocols) {
+  auto t = makeDecls(
+  "@protocol P @end @interface A @end @interface A(X) @end",
+  "@protocol P @end @interface A @end @interface A(X) @end", Lang_OBJC,
+  objcCategoryDecl());
+  EXPECT_TRUE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, DifferentProtocols) {
+  auto t = makeDecls(
+  "@protocol P @end @interface A @end @interface A(X) @end",
+  "@protocol Q @end @interface A @end @interface A(X) @end", Lang_OBJC,
+  objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, DifferentProtocolsOrder) {
+  auto t = makeDecls(
+  "@protocol P @end @protocol Q @end @interface A @end @interface A(X) @end",
+  "@protocol P @end @protocol Q @end @interface A @end @interface A(X) @end",
+  Lang_OBJC, objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, MatchingIvars) {
+  auto t = makeDecls(
+  "@interface A @end @interface A() { int x; } @end",
+  "@interface A @end @interface A() { int x; } @end", Lang_OBJC,
+  objcCategoryDecl());
+  EXPECT_TRUE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, DifferentIvarName) {
+  auto t = makeDecls(
+  "@interface A @end @interface A() { int x; } @end",
+  "@interface A @end @interface A() { int y; } @end", Lang_OBJC,
+  objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, DifferentIvarType) {
+  auto t = makeDecls(
+  "@interface A @end @interface A() { int x; } @end",
+  "@interface A @end @interface A() { float x; } @end", Lang_OBJC,
+  objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, DifferentIvarBitfieldWidth) {
+  auto t = makeDecls(
+  "@interface A @end @interface A() { int x: 1; } @end",
+  "@interface A @end @interface A() { int x: 2; } @end", Lang_OBJC,
+  objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, DifferentIvarVisibility) {
+  auto t = makeDecls(
+  "@interface A @end @interface A() { @public int x; } @end",
+  "@interface A @end @interface A() { @protected int x; } @end", Lang_OBJC,
+  objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, DifferentIvarNumber) {
+  auto t = makeDecls(
+  "@interface A @end @interface A() { int x; } @end",
+  "@interface A @end @interface A() {} @end", Lang_OBJC,
+ 

[clang] 4604db9 - [ASTStructuralEquivalence] Add support for comparing ObjCCategoryDecl.

2022-04-22 Thread Volodymyr Sapsai via cfe-commits

Author: Volodymyr Sapsai
Date: 2022-04-22T16:51:19-07:00
New Revision: 4604db9493ffb22e1f411d907f163bf021193d84

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

LOG: [ASTStructuralEquivalence] Add support for comparing ObjCCategoryDecl.

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

Added: 


Modified: 
clang/include/clang/Testing/CommandLineArgs.h
clang/lib/AST/ASTStructuralEquivalence.cpp
clang/lib/Testing/CommandLineArgs.cpp
clang/unittests/AST/MatchVerifier.h
clang/unittests/AST/StructuralEquivalenceTest.cpp

Removed: 




diff  --git a/clang/include/clang/Testing/CommandLineArgs.h 
b/clang/include/clang/Testing/CommandLineArgs.h
index fe2103a3dce21..e668781ee2ce1 100644
--- a/clang/include/clang/Testing/CommandLineArgs.h
+++ b/clang/include/clang/Testing/CommandLineArgs.h
@@ -29,6 +29,7 @@ enum TestLanguage {
   Lang_CXX17,
   Lang_CXX20,
   Lang_OpenCL,
+  Lang_OBJC,
   Lang_OBJCXX
 };
 

diff  --git a/clang/lib/AST/ASTStructuralEquivalence.cpp 
b/clang/lib/AST/ASTStructuralEquivalence.cpp
index 05f3470a179d2..b15036a11ad92 100644
--- a/clang/lib/AST/ASTStructuralEquivalence.cpp
+++ b/clang/lib/AST/ASTStructuralEquivalence.cpp
@@ -1242,10 +1242,10 @@ static bool 
IsStructurallyEquivalent(StructuralEquivalenceContext ,
   return true;
 }
 
-/// Determine structural equivalence of two fields.
 static bool IsStructurallyEquivalent(StructuralEquivalenceContext ,
- FieldDecl *Field1, FieldDecl *Field2) {
-  const auto *Owner2 = cast(Field2->getDeclContext());
+ FieldDecl *Field1, FieldDecl *Field2,
+ QualType Owner2Type) {
+  const auto *Owner2 = cast(Field2->getDeclContext());
 
   // For anonymous structs/unions, match up the anonymous struct/union type
   // declarations directly, so that we don't go off searching for anonymous
@@ -1265,7 +1265,7 @@ static bool 
IsStructurallyEquivalent(StructuralEquivalenceContext ,
   Context.Diag2(
   Owner2->getLocation(),
   Context.getApplicableDiagnostic(diag::err_odr_tag_type_inconsistent))
-  << Context.ToCtx.getTypeDeclType(Owner2);
+  << Owner2Type;
   Context.Diag2(Field2->getLocation(), diag::note_odr_field_name)
   << Field2->getDeclName();
   Context.Diag1(Field1->getLocation(), diag::note_odr_field_name)
@@ -1280,7 +1280,7 @@ static bool 
IsStructurallyEquivalent(StructuralEquivalenceContext ,
   Context.Diag2(
   Owner2->getLocation(),
   Context.getApplicableDiagnostic(diag::err_odr_tag_type_inconsistent))
-  << Context.ToCtx.getTypeDeclType(Owner2);
+  << Owner2Type;
   Context.Diag2(Field2->getLocation(), diag::note_odr_field)
   << Field2->getDeclName() << Field2->getType();
   Context.Diag1(Field1->getLocation(), diag::note_odr_field)
@@ -1296,6 +1296,14 @@ static bool 
IsStructurallyEquivalent(StructuralEquivalenceContext ,
   return true;
 }
 
+/// Determine structural equivalence of two fields.
+static bool IsStructurallyEquivalent(StructuralEquivalenceContext ,
+ FieldDecl *Field1, FieldDecl *Field2) {
+  const auto *Owner2 = cast(Field2->getDeclContext());
+  return IsStructurallyEquivalent(Context, Field1, Field2,
+  Context.ToCtx.getTypeDeclType(Owner2));
+}
+
 /// Determine structural equivalence of two methods.
 static bool IsStructurallyEquivalent(StructuralEquivalenceContext ,
  CXXMethodDecl *Method1,
@@ -1610,6 +1618,7 @@ static bool 
IsStructurallyEquivalent(StructuralEquivalenceContext ,
   }
 
   // Check the fields for consistency.
+  QualType D2Type = Context.ToCtx.getTypeDeclType(D2);
   RecordDecl::field_iterator Field2 = D2->field_begin(),
  Field2End = D2->field_end();
   for (RecordDecl::field_iterator Field1 = D1->field_begin(),
@@ -1628,7 +1637,7 @@ static bool 
IsStructurallyEquivalent(StructuralEquivalenceContext ,
   return false;
 }
 
-if (!IsStructurallyEquivalent(Context, *Field1, *Field2))
+if (!IsStructurallyEquivalent(Context, *Field1, *Field2, D2Type))
   return false;
   }
 
@@ -1934,6 +1943,126 @@ static bool 
IsStructurallyEquivalent(StructuralEquivalenceContext ,
   return true;
 }
 
+static bool IsStructurallyEquivalent(StructuralEquivalenceContext ,
+ ObjCIvarDecl *D1, ObjCIvarDecl *D2,
+ QualType Owner2Type) {
+  if (D1->getAccessControl() != D2->getAccessControl())
+return false;
+
+  return IsStructurallyEquivalent(Context, cast(D1),
+  cast(D2), Owner2Type);
+}
+
+static bool 

[PATCH] D124066: [clang-tidy] Ignore macros defined within declarations in modernize-macro-to-enum

2022-04-22 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood updated this revision to Diff 424663.
LegalizeAdulthood added a comment.

Update from review comments


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

https://reviews.llvm.org/D124066

Files:
  clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
  clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.h
  clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy -std=c++14-or-later %s modernize-macro-to-enum %t -- -- -I%S/Inputs/modernize-macro-to-enum
+// RUN: %check_clang_tidy -std=c++14-or-later %s modernize-macro-to-enum %t -- -- -I%S/Inputs/modernize-macro-to-enum -fno-delayed-template-parsing
 // C++14 or later required for binary literals.
 
 #if 1
@@ -303,3 +303,89 @@
   FN_GREEN(0);
   FN_BLUE(0);
 }
+
+// Ignore macros defined inside a top-level function definition.
+void g(int x)
+{
+  if (x != 0) {
+#define INSIDE1 1
+#define INSIDE2 2
+if (INSIDE1 > 1) {
+  f();
+}
+  } else {
+if (INSIDE2 == 1) {
+  f();
+}
+  }
+}
+
+// Ignore macros defined inside a top-level function declaration.
+extern void g2(
+#define INSIDE3 3
+#define INSIDE4 4
+);
+
+// Ignore macros defined inside a record (structure) declaration.
+struct S {
+#define INSIDE5 5
+#define INSIDE6 6
+  char storage[INSIDE5];
+};
+class C {
+#define INSIDE7 7
+#define INSIDE8 8
+};
+
+// Ignore macros defined inside a template function definition.
+template 
+#define INSIDE9 9
+bool fn()
+{
+  #define INSIDE10 10
+  return INSIDE9 > 1 || INSIDE10 < N;
+}
+
+// Ignore macros defined inside a variable declaration.
+extern int
+#define INSIDE11 11
+v;
+
+// Ignore macros defined inside a template class definition.
+template 
+class C2 {
+public:
+#define INSIDE12 12
+char storage[N];
+  bool f() {
+return N > INSIDE12;
+  }
+  bool g();
+};
+
+// Ignore macros defined inside a template member function definition.
+template 
+#define INSIDE13 13
+bool C2::g() {
+#define INSIDE14 14
+  return N < INSIDE12 || N > INSIDE13 || INSIDE14 > N;
+};
+
+// Ignore macros defined inside a template type alias.
+template 
+class C3 {
+  T data;
+};
+template 
+#define INSIDE15 15
+using Data = C3;
+
+// Ignore macros defined inside a type alias.
+using Data2 =
+#define INSIDE16 16
+char[INSIDE16];
+
+// Ignore macros defined inside a (constexpr) variable definition.
+constexpr int
+#define INSIDE17 17
+value = INSIDE17;
Index: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.h
+++ clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.h
@@ -15,6 +15,8 @@
 namespace tidy {
 namespace modernize {
 
+class MacroToEnumCallbacks;
+
 /// Replaces groups of related macros with an unscoped anonymous enum.
 ///
 /// For the user-facing documentation see:
@@ -25,6 +27,11 @@
   : ClangTidyCheck(Name, Context) {}
   void registerPPCallbacks(const SourceManager , Preprocessor *PP,
Preprocessor *ModuleExpanderPP) override;
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult ) override;
+
+private:
+  MacroToEnumCallbacks *PPCallback{};
 };
 
 } // namespace modernize
Index: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
@@ -121,6 +121,8 @@
   SourceLocation LastMacroLocation;
 };
 
+} // namespace
+
 class MacroToEnumCallbacks : public PPCallbacks {
 public:
   MacroToEnumCallbacks(MacroToEnumCheck *Check, const LangOptions ,
@@ -197,6 +199,8 @@
   // After we've seen everything, issue warnings and fix-its.
   void EndOfMainFile() override;
 
+  void invalidateRange(SourceRange Range);
+
 private:
   void newEnum() {
 if (Enums.empty() || !Enums.back().empty())
@@ -224,6 +228,7 @@
   void checkName(const Token );
   void rememberExpressionName(const Token );
   void invalidateExpressionNames();
+  void issueDiagnostics();
   void warnMacroEnum(const EnumMacro ) const;
   void fixEnumMacro(const MacroList ) const;
 
@@ -472,8 +477,20 @@
 }
 
 void MacroToEnumCallbacks::EndOfMainFile() {
-  invalidateExpressionNames();
+invalidateExpressionNames();
+issueDiagnostics();
+}
 
+void MacroToEnumCallbacks::invalidateRange(SourceRange Range) {
+  llvm::erase_if(Enums, [Range](const MacroList ) {
+return llvm::any_of(MacroList, [Range](const EnumMacro ) {
+  return 

[PATCH] D124066: [clang-tidy] Ignore macros defined within declarations in modernize-macro-to-enum

2022-04-22 Thread Richard 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 rGb985b6e3c15a: [clang-tidy] Ignore macros defined within 
declarations (authored by LegalizeAdulthood).

Changed prior to commit:
  https://reviews.llvm.org/D124066?vs=423818=424661#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124066

Files:
  clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
  clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.h
  clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy -std=c++14-or-later %s modernize-macro-to-enum %t -- -- -I%S/Inputs/modernize-macro-to-enum
+// RUN: %check_clang_tidy -std=c++14-or-later %s modernize-macro-to-enum %t -- -- -I%S/Inputs/modernize-macro-to-enum -fno-delayed-template-parsing
 // C++14 or later required for binary literals.
 
 #if 1
@@ -303,3 +303,89 @@
   FN_GREEN(0);
   FN_BLUE(0);
 }
+
+// Ignore macros defined inside a top-level function definition.
+void g(int x)
+{
+  if (x != 0) {
+#define INSIDE1 1
+#define INSIDE2 2
+if (INSIDE1 > 1) {
+  f();
+}
+  } else {
+if (INSIDE2 == 1) {
+  f();
+}
+  }
+}
+
+// Ignore macros defined inside a top-level function declaration.
+extern void g2(
+#define INSIDE3 3
+#define INSIDE4 4
+);
+
+// Ignore macros defined inside a record (structure) declaration.
+struct S {
+#define INSIDE5 5
+#define INSIDE6 6
+  char storage[INSIDE5];
+};
+class C {
+#define INSIDE7 7
+#define INSIDE8 8
+};
+
+// Ignore macros defined inside a template function definition.
+template 
+#define INSIDE9 9
+bool fn()
+{
+  #define INSIDE10 10
+  return INSIDE9 > 1 || INSIDE10 < N;
+}
+
+// Ignore macros defined inside a variable declaration.
+extern int
+#define INSIDE11 11
+v;
+
+// Ignore macros defined inside a template class definition.
+template 
+class C2 {
+public:
+#define INSIDE12 12
+char storage[N];
+  bool f() {
+return N > INSIDE12;
+  }
+  bool g();
+};
+
+// Ignore macros defined inside a template member function definition.
+template 
+#define INSIDE13 13
+bool C2::g() {
+#define INSIDE14 14
+  return N < INSIDE12 || N > INSIDE13 || INSIDE14 > N;
+};
+
+// Ignore macros defined inside a template type alias.
+template 
+class C3 {
+  T data;
+};
+template 
+#define INSIDE15 15
+using Data = C3;
+
+// Ignore macros defined inside a type alias.
+using Data2 =
+#define INSIDE16 16
+char[INSIDE16];
+
+// Ignore macros defined inside a (constexpr) variable definition.
+constexpr int
+#define INSIDE17 17
+value = INSIDE17;
Index: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.h
+++ clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.h
@@ -15,6 +15,8 @@
 namespace tidy {
 namespace modernize {
 
+class MacroToEnumCallbacks;
+
 /// Replaces groups of related macros with an unscoped anonymous enum.
 ///
 /// For the user-facing documentation see:
@@ -25,6 +27,11 @@
   : ClangTidyCheck(Name, Context) {}
   void registerPPCallbacks(const SourceManager , Preprocessor *PP,
Preprocessor *ModuleExpanderPP) override;
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult ) override;
+
+private:
+  MacroToEnumCallbacks *PPCallback{};
 };
 
 } // namespace modernize
Index: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
@@ -121,6 +121,8 @@
   SourceLocation LastMacroLocation;
 };
 
+} // namespace
+
 class MacroToEnumCallbacks : public PPCallbacks {
 public:
   MacroToEnumCallbacks(MacroToEnumCheck *Check, const LangOptions ,
@@ -197,6 +199,8 @@
   // After we've seen everything, issue warnings and fix-its.
   void EndOfMainFile() override;
 
+  void invalidateRange(SourceRange Range);
+
 private:
   void newEnum() {
 if (Enums.empty() || !Enums.back().empty())
@@ -224,6 +228,7 @@
   void checkName(const Token );
   void rememberExpressionName(const Token );
   void invalidateExpressionNames();
+  void issueDiagnostics();
   void warnMacroEnum(const EnumMacro ) const;
   void fixEnumMacro(const MacroList ) const;
 
@@ -472,8 +477,20 @@
 }
 
 void MacroToEnumCallbacks::EndOfMainFile() {
-  invalidateExpressionNames();
+

[PATCH] D124258: [C89/C2x] Change the behavior of implicit int diagnostics

2022-04-22 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:168-169
+  ``-Wno-error=implicit-int``, or disabled entirely with ``-Wno-implicit-int``.
+  As of C2x, support for implicit int has been removed, and the warning options
+  will have no effect. Specifying ``-Wimplicit-int`` in C89 mode will now issue
+  warnings instead of being a noop.

aaron.ballman wrote:
> rsmith wrote:
> > Is there some fundamental reason why implicit int is harder to support in 
> > C2x (as there was for implicit function declarations, because unprototyped 
> > functions are gone), or are we merely taking the opportunity to do this 
> > because C2x is new? I find the former more easily defensible than the 
> > latter, but I suppose the fact that we removed implicit function 
> > declarations means that C2x is the first really properly breaking change 
> > that C has had, so maybe now is the time regardless.
> Purely the latter -- C2x didn't make anything harder here. However, I'd like 
> to position C23 as "not your grandfather's C" in Clang by strengthening 
> diagnostics, especially ones related to safety or security vulnerabilities. 
> Basically, I think it's time to cut ties with as many dangerous things that 
> have been excised from C as possible. I think implicit int fits that goal in 
> the same way that implicit function decls do (namely, the implicit choice can 
> be wrong and you get surprising silent breakage at runtime if you're lucky).
> 
> (FWIW, I'm also hoping to get these sort of changes lumped into Clang 15 so 
> that the pain of upgrading is more localized to just one release rather than 
> strung out over several.)
OK. I wonder our stricter interpretation of the rules in C23 onwards is 
something we should be calling out in our documentation as policy?


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

https://reviews.llvm.org/D124258

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


[clang-tools-extra] b985b6e - [clang-tidy] Ignore macros defined within declarations

2022-04-22 Thread via cfe-commits

Author: Richard
Date: 2022-04-22T17:46:54-06:00
New Revision: b985b6e3c15a863112e1676d6211c80c7683f3eb

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

LOG: [clang-tidy] Ignore macros defined within declarations

Modernize-macro-to-enum shouldn't try to convert macros to enums
when they are defined inside a declaration or definition, only
when the macros are defined at the top level.  Since preprocessing
is disconnected from AST traversal, match nodes in the AST and then
invalidate source ranges spanning AST nodes before issuing diagnostics.

ClangTidyCheck::onEndOfTranslationUnit is called before
PPCallbacks::EndOfMainFile, so defer final diagnostics to the
PPCallbacks implementation.

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

Fixes #54883

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.h
clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
index 90d3fe0b99822..e916668f7cbb9 100644
--- a/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
@@ -121,6 +121,8 @@ struct FileState {
   SourceLocation LastMacroLocation;
 };
 
+} // namespace
+
 class MacroToEnumCallbacks : public PPCallbacks {
 public:
   MacroToEnumCallbacks(MacroToEnumCheck *Check, const LangOptions ,
@@ -197,6 +199,8 @@ class MacroToEnumCallbacks : public PPCallbacks {
   // After we've seen everything, issue warnings and fix-its.
   void EndOfMainFile() override;
 
+  void invalidateRange(SourceRange Range);
+
 private:
   void newEnum() {
 if (Enums.empty() || !Enums.back().empty())
@@ -224,6 +228,7 @@ class MacroToEnumCallbacks : public PPCallbacks {
   void checkName(const Token );
   void rememberExpressionName(const Token );
   void invalidateExpressionNames();
+  void issueDiagnostics();
   void warnMacroEnum(const EnumMacro ) const;
   void fixEnumMacro(const MacroList ) const;
 
@@ -472,8 +477,20 @@ void MacroToEnumCallbacks::invalidateExpressionNames() {
 }
 
 void MacroToEnumCallbacks::EndOfMainFile() {
-  invalidateExpressionNames();
+invalidateExpressionNames();
+issueDiagnostics();
+}
 
+void MacroToEnumCallbacks::invalidateRange(SourceRange Range) {
+  llvm::erase_if(Enums, [Range](const MacroList ) {
+return llvm::any_of(MacroList, [Range](const EnumMacro ) {
+  return Macro.Directive->getLocation() >= Range.getBegin() &&
+ Macro.Directive->getLocation() <= Range.getEnd();
+});
+  });
+}
+
+void MacroToEnumCallbacks::issueDiagnostics() {
   for (const MacroList  : Enums) {
 if (MacroList.empty())
   continue;
@@ -530,13 +547,43 @@ void MacroToEnumCallbacks::fixEnumMacro(const MacroList 
) const {
   Diagnostic << FixItHint::CreateInsertion(End, "};\n");
 }
 
-} // namespace
-
 void MacroToEnumCheck::registerPPCallbacks(const SourceManager ,
Preprocessor *PP,
Preprocessor *ModuleExpanderPP) {
-  PP->addPPCallbacks(
-  std::make_unique(this, getLangOpts(), SM));
+  auto Callback = std::make_unique(this, getLangOpts(), 
SM);
+  PPCallback = Callback.get();
+  PP->addPPCallbacks(std::move(Callback));
+}
+
+void MacroToEnumCheck::registerMatchers(ast_matchers::MatchFinder *Finder) {
+  using namespace ast_matchers;
+  auto TopLevelDecl = hasParent(translationUnitDecl());
+  Finder->addMatcher(decl(TopLevelDecl).bind("top"), this);
+}
+
+static bool isValid(SourceRange Range) {
+  return Range.getBegin().isValid() && Range.getEnd().isValid();
+}
+
+static bool empty(SourceRange Range) {
+  return Range.getBegin() == Range.getEnd();
+}
+
+void MacroToEnumCheck::check(
+const ast_matchers::MatchFinder::MatchResult ) {
+  auto *TLDecl = Result.Nodes.getNodeAs("top");
+  if (TLDecl == nullptr)
+  return;
+
+  SourceRange Range = TLDecl->getSourceRange();
+  if (auto *TemplateFn = Result.Nodes.getNodeAs("top")) {
+if (TemplateFn->isThisDeclarationADefinition() && TemplateFn->hasBody())
+  Range = SourceRange{TemplateFn->getBeginLoc(),
+  TemplateFn->getUnderlyingDecl()->getBodyRBrace()};
+  }
+
+  if (isValid(Range) && !empty(Range))
+PPCallback->invalidateRange(Range);
 }
 
 } // namespace modernize

diff  --git a/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.h 
b/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.h
index 667ff49d671a1..09fdd5448ad4b 100644
--- a/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.h
+++ 

[PATCH] D124131: Thread safety analysis: Store capability kind in CapabilityExpr

2022-04-22 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert added inline comments.



Comment at: clang/include/clang/Analysis/Analyses/ThreadSafetyCommon.h:277
+  /// The kind of capability as specified by @ref CapabilityAttr::getName.
+  StringRef CapKind;
+

aaron.ballman wrote:
> Hr, I think this may actually be safe, but it does give me pause to store 
> a `StringRef` as anything other than a local (or param/return type): 
> https://llvm.org/docs/ProgrammersManual.html#the-stringref-class
> 
> Can you double-check my thinking? This is fine because it's pulling the 
> `StringRef` from the `CapabilityAttr`, and that stores its name internally 
> and isn't released until the AST is destroyed.
Exactly, aside from two places where I'm storing a string literal ("mutex" and 
"wildcard"), the common case is taking the `StringRef` (as returned by 
`CapabilityAttr::getName`) from the attribute. So that would be 
lifetime-coupled to the AST and should be safe for our analysis.

Of course `StringRef` is implicitly constructible from other types, and we 
wouldn't want that. Especially `std::string` would be an issue. Perhaps we 
should prevent implicit conversions, and thus force the caller to pass a 
`StringRef` glvalue, by overloading with a deleted template?
```
template
CapabilityExpr(const til::SExpr *, T, bool) = delete;
```
Or maybe you've got a better idea.

As for a justification: we're building lots of `CapabilityExpr`s, essentially 
every time we see a capability expression in the code (in attributes or as 
capability type method call arguments). Given that the kind is only used for 
actual warnings I wouldn't want us to spend of lot of time or memory on storing 
it.

We could also store the original `Expr*` and extract on demand, but that seemed 
to me antithetical to translating into the TIL. Of course it would be slightly 
faster, but the current code (before this change) also extracts capability 
names eagerly without waiting for the need to arise.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124131

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


[PATCH] D124221: Add new builtin __builtin_reflect_struct.

2022-04-22 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

In D124221#3468706 , @aaron.ballman 
wrote:

> Thank you for looking into this! I've also thought that the 
> `__builtin_dump_struct` implementation hasn't been quite as robust as it 
> could be. However, the primary use case for that builtin has been for kernel 
> folks to debug when they have no access to an actual debugger -- it being a 
> super limited interface is actually a feature rather than a bug, in some ways.

I'm more concerned about the design of `__builtin_dump_struct` than the 
implementation -- we can always fix the implementation. Right now the design is 
hostile to any use other than the very simplest one where the function you give 
it is essentially `printf`. You can't even dump to a log file or to a string 
without having to fight the design of the builtin. And if you want anything 
other than the exact recursion and formatting choices that we've arbitrarily 
made, you're out of luck. And of course, if you're in C++, you'll want to be 
able to print out `std::string` and `std::optional` and similar types too, 
which are not supported by the current design at all. Perhaps this is precisely 
what a specific set of kernel folks want for a specific use case, but if the 
only purpose is to address that one use case, then I don't really see how we 
can justify keeping this builtin in-tree. So I think we should either expand 
the scope beyond the specific kernel folks or we should remove it.

> I think what you're designing here is straight-up reflection, which is a 
> different use case. If we're going to get something that's basically only 
> usable in C++, I'm not certain there's much value in adding builtins for 
> reflection until WG21 decides what reflection looks like, and then we can 
> design around that. (Personally, I think designing usable reflection 
> interfaces for C would be considerably harder but would provide considerably 
> more benefit to users given the lack of reflection capabilities. There's 
> almost no chance WG14 and WG21 would come up with the same interfaces for 
> reflection, so I think we've got some opportunity for exploration here.)

What I set out to build is something that lets you implement struct dumping 
without all the shortcomings I see in `__builtin_dump_struct`. I think it's 
inevitable that that ends up being substantially a struct reflection system, 
and indeed `__builtin_dump_struct` is a reflection system, too, just a really 
awkward one -- people have already started parsing its format strings to 
extract struct field names, for example. (The usage I've seen actually *is* 
struct dumping, but that usage can't use `__builtin_dump_struct` directly 
because of its limitations, so `__builtin_dump_struct` is just used to extract 
the field names, and the field values and types are extracted via structured 
bindings instead.)

I do agree that we shouldn't be providing a full reflection mechanism here, 
given both that one is coming anyway, and that whatever we design, people will 
inevitably ask for more, and we don't want to be maintaining our own reflection 
technology.

So, I think we should either roll back `__builtin_dump_struct` or fix forward. 
This patch attempted to do the latter, but maybe it's gone too far in the 
direction of reflection. I think we can address most of my concerns with 
`__builtin_dump_struct` without a new builtin, by incorporating things from 
this implementation as follows:

- Desugar it in Sema rather than in CodeGen -- this is necessary to enable 
following things as well as for constant evaluation
- Take any callable as the printing function and pass it the fields with their 
correct types, so that a C++ implementation can dispatch based on the type and 
print the values of types that we don't hard-code (eg, we'd generate calls like 
`user_dump_function("%s = %p", "field_name", >field_name);`, and a smart C++ 
formatting function can preserve the field type and do something suitable when 
formatting a corresponding `%p`).
- Take additional arguments to be passed onto the provided function, so that C 
users can easily format to a different file or to a  string or whatever else

The main concern that I think we can't address this way is that 
`__builtin_dump_struct` decides for itself how to format the struct. But if we 
keep that property, that might actually help to keep us in the bounds of a 
builtin that's good for dumping but nothing else?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

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


[PATCH] D124057: [asan] Enable detect_stack_use_after_return=1 by default

2022-04-22 Thread Vitaly Buka 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 rG4b4437c084e2: [asan] Enable detect_stack_use_after_return=1 
by default (authored by vitalybuka).

Changed prior to commit:
  https://reviews.llvm.org/D124057?vs=424291=424635#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124057

Files:
  clang/docs/AddressSanitizer.rst
  clang/docs/ReleaseNotes.rst
  compiler-rt/lib/asan/asan_flags.inc
  compiler-rt/lib/asan/tests/asan_interface_test.cpp
  compiler-rt/test/asan/TestCases/Posix/gc-test.cpp
  compiler-rt/test/asan/TestCases/Posix/stack-use-after-return.cpp
  compiler-rt/test/asan/TestCases/Posix/unpoison-alternate-stack.cpp
  compiler-rt/test/asan/TestCases/Windows/stack_use_after_return.cpp
  compiler-rt/test/asan/TestCases/alloca_loop_unpoisoning.cpp
  compiler-rt/test/asan/TestCases/contiguous_container.cpp
  compiler-rt/test/asan/TestCases/handle_noreturn_bug.cpp
  compiler-rt/test/asan/TestCases/heavy_uar_test.cpp
  compiler-rt/test/asan/TestCases/intercept-rethrow-exception.cpp
  compiler-rt/test/asan/TestCases/invalid-pointer-pairs-subtract-success.cpp
  llvm/include/llvm/Transforms/Instrumentation/AddressSanitizerOptions.h

Index: llvm/include/llvm/Transforms/Instrumentation/AddressSanitizerOptions.h
===
--- llvm/include/llvm/Transforms/Instrumentation/AddressSanitizerOptions.h
+++ llvm/include/llvm/Transforms/Instrumentation/AddressSanitizerOptions.h
@@ -22,8 +22,8 @@
 /// Mode of ASan detect stack use after return
 enum class AsanDetectStackUseAfterReturnMode {
   Never,   ///< Never detect stack use after return.
-  Runtime, ///< Detect stack use after return if runtime flag is enabled
-   ///< (ASAN_OPTIONS=detect_stack_use_after_return=1)
+  Runtime, ///< Detect stack use after return if not disabled runtime with
+   ///< (ASAN_OPTIONS=detect_stack_use_after_return=0).
   Always,  ///< Always detect stack use after return.
   Invalid, ///< Not a valid detect mode.
 };
Index: compiler-rt/test/asan/TestCases/invalid-pointer-pairs-subtract-success.cpp
===
--- compiler-rt/test/asan/TestCases/invalid-pointer-pairs-subtract-success.cpp
+++ compiler-rt/test/asan/TestCases/invalid-pointer-pairs-subtract-success.cpp
@@ -1,7 +1,7 @@
 // RUN: %clangxx_asan -O0 %s -o %t -mllvm -asan-detect-invalid-pointer-pair
 
 // RUN: %env_asan_opts=detect_invalid_pointer_pairs=2 %run %t
-// RUN: %env_asan_opts=detect_invalid_pointer_pairs=2,detect_stack_use_after_return=1 %run %t
+// RUN: %env_asan_opts=detect_invalid_pointer_pairs=2,detect_stack_use_after_return=0 %run %t
 
 #include 
 #include 
Index: compiler-rt/test/asan/TestCases/intercept-rethrow-exception.cpp
===
--- compiler-rt/test/asan/TestCases/intercept-rethrow-exception.cpp
+++ compiler-rt/test/asan/TestCases/intercept-rethrow-exception.cpp
@@ -4,7 +4,7 @@
 // REQUIRES: shared_cxxabi
 
 // RUN: %clangxx_asan -fexceptions -O0 %s -o %t
-// RUN: %run %t
+// RUN: %env_asan_opts=detect_stack_use_after_return=0 %run %t
 
 // The current implementation of this functionality requires special
 // combination of libraries that are not used by default on NetBSD
Index: compiler-rt/test/asan/TestCases/heavy_uar_test.cpp
===
--- compiler-rt/test/asan/TestCases/heavy_uar_test.cpp
+++ compiler-rt/test/asan/TestCases/heavy_uar_test.cpp
@@ -1,5 +1,7 @@
-// RUN: %clangxx_asan -O0 %s -o %t && %env_asan_opts=detect_stack_use_after_return=1 not %run %t 2>&1 | FileCheck %s
-// RUN: %clangxx_asan -O2 %s -o %t && %env_asan_opts=detect_stack_use_after_return=1 not %run %t 2>&1 | FileCheck %s
+// RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s
+// RUN: %env_asan_opts=detect_stack_use_after_return=1 not %run %t 2>&1 | FileCheck %s
+// RUN: %clangxx_asan -O2 %s -o %t && not %run %t 2>&1 | FileCheck %s
+// RUN: %env_asan_opts=detect_stack_use_after_return=1 not %run %t 2>&1 | FileCheck %s
 // RUN: %clangxx_asan -O0 %s -o %t -fsanitize-address-use-after-return=always && not %run %t 2>&1 | FileCheck %s
 // RUN: %clangxx_asan -O2 %s -o %t -fsanitize-address-use-after-return=always && not %run %t 2>&1 | FileCheck %s
 // XFAIL: windows-msvc
Index: compiler-rt/test/asan/TestCases/handle_noreturn_bug.cpp
===
--- compiler-rt/test/asan/TestCases/handle_noreturn_bug.cpp
+++ compiler-rt/test/asan/TestCases/handle_noreturn_bug.cpp
@@ -1,9 +1,9 @@
 // Regression test: __asan_handle_no_return should unpoison stack even with poison_heap=0.
 // Fails with debug checks: https://bugs.llvm.org/show_bug.cgi?id=46862
 // XFAIL: !compiler-rt-optimized
-// RUN: 

[PATCH] D124288: [Index] Remove reference to `UnresolvedUsingIfExists`

2022-04-22 Thread Ben Barham via Phabricator via cfe-commits
bnbarham updated this revision to Diff 424631.
bnbarham added a comment.

Remove line for  check


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124288

Files:
  clang/lib/Index/IndexDecl.cpp
  clang/test/Index/using_if_exists.cpp


Index: clang/test/Index/using_if_exists.cpp
===
--- /dev/null
+++ clang/test/Index/using_if_exists.cpp
@@ -0,0 +1,9 @@
+// RUN: c-index-test core -print-source-symbols -- %s -target 
x86_64-unknown-unknown 2>&1 | FileCheck %s
+
+namespace ns {
+//  void foo();
+}
+
+using ns::foo __attribute__((using_if_exists));
+// CHECK: [[@LINE-1]]:11 | using/C++ | foo | c:@UD@foo |  | Decl | 
rel: 0
+// CHECK-NOT: 
Index: clang/lib/Index/IndexDecl.cpp
===
--- clang/lib/Index/IndexDecl.cpp
+++ clang/lib/Index/IndexDecl.cpp
@@ -605,9 +605,16 @@
 const NamedDecl *Parent = dyn_cast(DC);
 IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), Parent,
  D->getLexicalDeclContext());
-for (const auto *I : D->shadows())
+for (const auto *I : D->shadows()) {
+  // Skip unresolved using decls - we already have a decl for the using
+  // itself, so there's not much point adding another decl or reference to
+  // refer to the same location.
+  if (isa(I->getUnderlyingDecl()))
+continue;
+
   IndexCtx.handleReference(I->getUnderlyingDecl(), D->getLocation(), 
Parent,
D->getLexicalDeclContext(), SymbolRoleSet());
+}
 return true;
   }
 


Index: clang/test/Index/using_if_exists.cpp
===
--- /dev/null
+++ clang/test/Index/using_if_exists.cpp
@@ -0,0 +1,9 @@
+// RUN: c-index-test core -print-source-symbols -- %s -target x86_64-unknown-unknown 2>&1 | FileCheck %s
+
+namespace ns {
+//  void foo();
+}
+
+using ns::foo __attribute__((using_if_exists));
+// CHECK: [[@LINE-1]]:11 | using/C++ | foo | c:@UD@foo |  | Decl | rel: 0
+// CHECK-NOT: 
Index: clang/lib/Index/IndexDecl.cpp
===
--- clang/lib/Index/IndexDecl.cpp
+++ clang/lib/Index/IndexDecl.cpp
@@ -605,9 +605,16 @@
 const NamedDecl *Parent = dyn_cast(DC);
 IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), Parent,
  D->getLexicalDeclContext());
-for (const auto *I : D->shadows())
+for (const auto *I : D->shadows()) {
+  // Skip unresolved using decls - we already have a decl for the using
+  // itself, so there's not much point adding another decl or reference to
+  // refer to the same location.
+  if (isa(I->getUnderlyingDecl()))
+continue;
+
   IndexCtx.handleReference(I->getUnderlyingDecl(), D->getLocation(), Parent,
D->getLexicalDeclContext(), SymbolRoleSet());
+}
 return true;
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124253: [Clang][OpenMP] Fix the issue that temp cubin files are not removed after compilation when using new OpenMP driver

2022-04-22 Thread Shilei Tian via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG20a9fb953e46: [Clang][OpenMP] Fix the issue that temp cubin 
files are not removed after… (authored by tianshilei1992).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124253

Files:
  clang/lib/Driver/ToolChains/Cuda.cpp


Index: clang/lib/Driver/ToolChains/Cuda.cpp
===
--- clang/lib/Driver/ToolChains/Cuda.cpp
+++ clang/lib/Driver/ToolChains/Cuda.cpp
@@ -447,7 +447,10 @@
   CmdArgs.push_back("--gpu-name");
   CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
   CmdArgs.push_back("--output-file");
-  CmdArgs.push_back(Args.MakeArgString(TC.getInputFilename(Output)));
+  const char *OutputFileName = Args.MakeArgString(TC.getInputFilename(Output));
+  if (std::string(OutputFileName) != std::string(Output.getFilename()))
+C.addTempFile(OutputFileName);
+  CmdArgs.push_back(OutputFileName);
   for (const auto& II : Inputs)
 CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
 
@@ -606,8 +609,8 @@
 if (!II.isFilename())
   continue;
 
-const char *CubinF = C.addTempFile(
-C.getArgs().MakeArgString(getToolChain().getInputFilename(II)));
+const char *CubinF =
+C.getArgs().MakeArgString(getToolChain().getInputFilename(II));
 
 CmdArgs.push_back(CubinF);
   }


Index: clang/lib/Driver/ToolChains/Cuda.cpp
===
--- clang/lib/Driver/ToolChains/Cuda.cpp
+++ clang/lib/Driver/ToolChains/Cuda.cpp
@@ -447,7 +447,10 @@
   CmdArgs.push_back("--gpu-name");
   CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
   CmdArgs.push_back("--output-file");
-  CmdArgs.push_back(Args.MakeArgString(TC.getInputFilename(Output)));
+  const char *OutputFileName = Args.MakeArgString(TC.getInputFilename(Output));
+  if (std::string(OutputFileName) != std::string(Output.getFilename()))
+C.addTempFile(OutputFileName);
+  CmdArgs.push_back(OutputFileName);
   for (const auto& II : Inputs)
 CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
 
@@ -606,8 +609,8 @@
 if (!II.isFilename())
   continue;
 
-const char *CubinF = C.addTempFile(
-C.getArgs().MakeArgString(getToolChain().getInputFilename(II)));
+const char *CubinF =
+C.getArgs().MakeArgString(getToolChain().getInputFilename(II));
 
 CmdArgs.push_back(CubinF);
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 20a9fb9 - [Clang][OpenMP] Fix the issue that temp cubin files are not removed after compilation when using new OpenMP driver

2022-04-22 Thread Shilei Tian via cfe-commits

Author: Shilei Tian
Date: 2022-04-22T18:07:28-04:00
New Revision: 20a9fb953e46b1d97aaee7b182b0f3d48f340bd1

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

LOG: [Clang][OpenMP] Fix the issue that temp cubin files are not removed after 
compilation when using new OpenMP driver

The root cause of this is, in `NVPTX::Assembler::ConstructJob`, the output file 
name might not match the `Output`'s file name passed into the function because 
`CudaToolChain::getInputFilename` is a specialized version. That means the real 
output file is not added to the temp files list, which will be all removed in 
the d'tor of `Compilation`. In order to "fix" it, in the function 
`NVPTX::OpenMPLinker::ConstructJob`, before calling `clang-nvlink-wrapper`, the 
function calls `getToolChain().getInputFilename(II)` to get the right output 
file name for each input, and add it to temp file, and then they can be removed 
w/o any issue. However, this whole logic doesn't work when using the new OpenMP 
driver because `NVPTX::OpenMPLinker::ConstructJob` is not called at all, which 
causing the issue that the cubin file generated in each single unit compilation 
is out of track.

In this patch, we add the real output file into temp files if its name doesn't 
match `Output`. We add it when the file is an output instead of doing it when 
it is an input, like what we did in `NVPTX::OpenMPLinker::ConstructJob`, which 
makes more sense.

Reviewed By: jhuber6

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index f8a06a2e09ab7..6103c42bf7547 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -447,7 +447,10 @@ void NVPTX::Assembler::ConstructJob(Compilation , const 
JobAction ,
   CmdArgs.push_back("--gpu-name");
   CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
   CmdArgs.push_back("--output-file");
-  CmdArgs.push_back(Args.MakeArgString(TC.getInputFilename(Output)));
+  const char *OutputFileName = Args.MakeArgString(TC.getInputFilename(Output));
+  if (std::string(OutputFileName) != std::string(Output.getFilename()))
+C.addTempFile(OutputFileName);
+  CmdArgs.push_back(OutputFileName);
   for (const auto& II : Inputs)
 CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
 
@@ -606,8 +609,8 @@ void NVPTX::OpenMPLinker::ConstructJob(Compilation , 
const JobAction ,
 if (!II.isFilename())
   continue;
 
-const char *CubinF = C.addTempFile(
-C.getArgs().MakeArgString(getToolChain().getInputFilename(II)));
+const char *CubinF =
+C.getArgs().MakeArgString(getToolChain().getInputFilename(II));
 
 CmdArgs.push_back(CubinF);
   }



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


[PATCH] D124066: [clang-tidy] Ignore macros defined within declarations in modernize-macro-to-enum

2022-04-22 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood marked an inline comment as done.
LegalizeAdulthood added inline comments.



Comment at: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp:561-567
+  Finder->addMatcher(varDecl(TopLevelDecl).bind("top"), this);
+  Finder->addMatcher(functionDecl(TopLevelDecl).bind("top"), this);
+  Finder->addMatcher(recordDecl(TopLevelDecl).bind("top"), this);
+  Finder->addMatcher(typeAliasDecl(TopLevelDecl).bind("top"), this);
+  Finder->addMatcher(functionTemplateDecl(TopLevelDecl).bind("top"), this);
+  Finder->addMatcher(classTemplateDecl(TopLevelDecl).bind("top"), this);
+  Finder->addMatcher(typeAliasTemplateDecl(TopLevelDecl).bind("top"), this);

LegalizeAdulthood wrote:
> aaron.ballman wrote:
> > Can we mix these together with `anyOf()` so we're not adding so many 
> > matchers? e.g.,
> > ```
> > Finder->addMatcher(anyOf(varDecl(TopLevelDecl), 
> > functionDecl(topLevelDecl()), ...).bind("top"), this);
> > ```
> Oh, good idea, yep can do that.
Can't actually do `anyOf` as it is a narrowing matcher, but I think I can 
collapse all of these to just matching on `decl`, so I'm trying that.


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

https://reviews.llvm.org/D124066

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


[PATCH] D124288: [Index] Remove reference to `UnresolvedUsingIfExists`

2022-04-22 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir accepted this revision.
benlangmuir added a comment.
This revision is now accepted and ready to land.

Minor suggestion for the test case, but otherwise LGTM.




Comment at: clang/test/Index/using_if_exists.cpp:9
+// CHECK: [[@LINE-1]]:11 | using/C++ | foo | c:@UD@foo |  | Decl | 
rel: 0
+// CHECK-NOT: [[@LINE-2]]:11 | 

Could we drop the `[[@LINE-2]]:11 |` part of the CHECK-NOT to make it a bit 
more robust?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124288

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


[PATCH] D124288: [Index] Remove reference to `UnresolvedUsingIfExists`

2022-04-22 Thread Ben Barham via Phabricator via cfe-commits
bnbarham updated this revision to Diff 424622.
bnbarham retitled this revision from "[Index] Add a USR and symbol kind for 
UnresolvedUsingIfExists" to "[Index] Remove reference to 
`UnresolvedUsingIfExists`".
bnbarham edited the summary of this revision.
bnbarham added a comment.

Update title/message


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124288

Files:
  clang/lib/Index/IndexDecl.cpp
  clang/test/Index/using_if_exists.cpp


Index: clang/test/Index/using_if_exists.cpp
===
--- /dev/null
+++ clang/test/Index/using_if_exists.cpp
@@ -0,0 +1,9 @@
+// RUN: c-index-test core -print-source-symbols -- %s -target 
x86_64-unknown-unknown 2>&1 | FileCheck %s
+
+namespace ns {
+//  void foo();
+}
+
+using ns::foo __attribute__((using_if_exists));
+// CHECK: [[@LINE-1]]:11 | using/C++ | foo | c:@UD@foo |  | Decl | 
rel: 0
+// CHECK-NOT: [[@LINE-2]]:11 | 
Index: clang/lib/Index/IndexDecl.cpp
===
--- clang/lib/Index/IndexDecl.cpp
+++ clang/lib/Index/IndexDecl.cpp
@@ -605,9 +605,16 @@
 const NamedDecl *Parent = dyn_cast(DC);
 IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), Parent,
  D->getLexicalDeclContext());
-for (const auto *I : D->shadows())
+for (const auto *I : D->shadows()) {
+  // Skip unresolved using decls - we already have a decl for the using
+  // itself, so there's not much point adding another decl or reference to
+  // refer to the same location.
+  if (isa(I->getUnderlyingDecl()))
+continue;
+
   IndexCtx.handleReference(I->getUnderlyingDecl(), D->getLocation(), 
Parent,
D->getLexicalDeclContext(), SymbolRoleSet());
+}
 return true;
   }
 


Index: clang/test/Index/using_if_exists.cpp
===
--- /dev/null
+++ clang/test/Index/using_if_exists.cpp
@@ -0,0 +1,9 @@
+// RUN: c-index-test core -print-source-symbols -- %s -target x86_64-unknown-unknown 2>&1 | FileCheck %s
+
+namespace ns {
+//  void foo();
+}
+
+using ns::foo __attribute__((using_if_exists));
+// CHECK: [[@LINE-1]]:11 | using/C++ | foo | c:@UD@foo |  | Decl | rel: 0
+// CHECK-NOT: [[@LINE-2]]:11 | 
Index: clang/lib/Index/IndexDecl.cpp
===
--- clang/lib/Index/IndexDecl.cpp
+++ clang/lib/Index/IndexDecl.cpp
@@ -605,9 +605,16 @@
 const NamedDecl *Parent = dyn_cast(DC);
 IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), Parent,
  D->getLexicalDeclContext());
-for (const auto *I : D->shadows())
+for (const auto *I : D->shadows()) {
+  // Skip unresolved using decls - we already have a decl for the using
+  // itself, so there's not much point adding another decl or reference to
+  // refer to the same location.
+  if (isa(I->getUnderlyingDecl()))
+continue;
+
   IndexCtx.handleReference(I->getUnderlyingDecl(), D->getLocation(), Parent,
D->getLexicalDeclContext(), SymbolRoleSet());
+}
 return true;
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124288: [Index] Add a USR and symbol kind for UnresolvedUsingIfExists

2022-04-22 Thread Ben Barham via Phabricator via cfe-commits
bnbarham updated this revision to Diff 424621.
bnbarham added a comment.

After speaking with Ben, we decided it makes more sense to just remove the 
reference entirely.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124288

Files:
  clang/lib/Index/IndexDecl.cpp
  clang/test/Index/using_if_exists.cpp


Index: clang/test/Index/using_if_exists.cpp
===
--- /dev/null
+++ clang/test/Index/using_if_exists.cpp
@@ -0,0 +1,9 @@
+// RUN: c-index-test core -print-source-symbols -- %s -target 
x86_64-unknown-unknown 2>&1 | FileCheck %s
+
+namespace ns {
+//  void foo();
+}
+
+using ns::foo __attribute__((using_if_exists));
+// CHECK: [[@LINE-1]]:11 | using/C++ | foo | c:@UD@foo |  | Decl | 
rel: 0
+// CHECK-NOT: [[@LINE-2]]:11 | 
Index: clang/lib/Index/IndexDecl.cpp
===
--- clang/lib/Index/IndexDecl.cpp
+++ clang/lib/Index/IndexDecl.cpp
@@ -605,9 +605,16 @@
 const NamedDecl *Parent = dyn_cast(DC);
 IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), Parent,
  D->getLexicalDeclContext());
-for (const auto *I : D->shadows())
+for (const auto *I : D->shadows()) {
+  // Skip unresolved using decls - we already have a decl for the using
+  // itself, so there's not much point adding another decl or reference to
+  // refer to the same location.
+  if (isa(I->getUnderlyingDecl()))
+continue;
+
   IndexCtx.handleReference(I->getUnderlyingDecl(), D->getLocation(), 
Parent,
D->getLexicalDeclContext(), SymbolRoleSet());
+}
 return true;
   }
 


Index: clang/test/Index/using_if_exists.cpp
===
--- /dev/null
+++ clang/test/Index/using_if_exists.cpp
@@ -0,0 +1,9 @@
+// RUN: c-index-test core -print-source-symbols -- %s -target x86_64-unknown-unknown 2>&1 | FileCheck %s
+
+namespace ns {
+//  void foo();
+}
+
+using ns::foo __attribute__((using_if_exists));
+// CHECK: [[@LINE-1]]:11 | using/C++ | foo | c:@UD@foo |  | Decl | rel: 0
+// CHECK-NOT: [[@LINE-2]]:11 | 
Index: clang/lib/Index/IndexDecl.cpp
===
--- clang/lib/Index/IndexDecl.cpp
+++ clang/lib/Index/IndexDecl.cpp
@@ -605,9 +605,16 @@
 const NamedDecl *Parent = dyn_cast(DC);
 IndexCtx.indexNestedNameSpecifierLoc(D->getQualifierLoc(), Parent,
  D->getLexicalDeclContext());
-for (const auto *I : D->shadows())
+for (const auto *I : D->shadows()) {
+  // Skip unresolved using decls - we already have a decl for the using
+  // itself, so there's not much point adding another decl or reference to
+  // refer to the same location.
+  if (isa(I->getUnderlyingDecl()))
+continue;
+
   IndexCtx.handleReference(I->getUnderlyingDecl(), D->getLocation(), Parent,
D->getLexicalDeclContext(), SymbolRoleSet());
+}
 return true;
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124066: [clang-tidy] Ignore macros defined within declarations in modernize-macro-to-enum

2022-04-22 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood marked an inline comment as done.
LegalizeAdulthood added inline comments.



Comment at: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp:561-567
+  Finder->addMatcher(varDecl(TopLevelDecl).bind("top"), this);
+  Finder->addMatcher(functionDecl(TopLevelDecl).bind("top"), this);
+  Finder->addMatcher(recordDecl(TopLevelDecl).bind("top"), this);
+  Finder->addMatcher(typeAliasDecl(TopLevelDecl).bind("top"), this);
+  Finder->addMatcher(functionTemplateDecl(TopLevelDecl).bind("top"), this);
+  Finder->addMatcher(classTemplateDecl(TopLevelDecl).bind("top"), this);
+  Finder->addMatcher(typeAliasTemplateDecl(TopLevelDecl).bind("top"), this);

aaron.ballman wrote:
> Can we mix these together with `anyOf()` so we're not adding so many 
> matchers? e.g.,
> ```
> Finder->addMatcher(anyOf(varDecl(TopLevelDecl), functionDecl(topLevelDecl()), 
> ...).bind("top"), this);
> ```
Oh, good idea, yep can do that.


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

https://reviews.llvm.org/D124066

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


[PATCH] D124189: [CUDA][HIP] Externalize kernels with internal linkage

2022-04-22 Thread Yaxun Liu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
yaxunl marked 3 inline comments as done.
Closed by commit rG04fb81674ed7: [CUDA][HIP] Externalize kernels with internal 
linkage (authored by yaxunl).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D124189?vs=424364=424600#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124189

Files:
  clang/lib/AST/ASTContext.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGenCUDA/device-var-linkage.cu
  clang/test/CodeGenCUDA/kernel-in-anon-ns.cu
  clang/test/CodeGenCUDA/managed-var.cu
  clang/test/CodeGenCUDA/static-device-var-rdc.cu

Index: clang/test/CodeGenCUDA/static-device-var-rdc.cu
===
--- clang/test/CodeGenCUDA/static-device-var-rdc.cu
+++ clang/test/CodeGenCUDA/static-device-var-rdc.cu
@@ -40,6 +40,11 @@
 // RUN:   -std=c++11 -fgpu-rdc -emit-llvm -o - -x hip %s > %t.host
 // RUN: cat %t.host | FileCheck -check-prefix=HOST-NEG %s
 
+// Check postfix for CUDA.
+
+// RUN: %clang_cc1 -no-opaque-pointers -triple nvptx -fcuda-is-device -cuid=abc \
+// RUN:   -std=c++11 -fgpu-rdc -emit-llvm -o - %s | FileCheck \
+// RUN:   -check-prefixes=CUDA %s
 
 #include "Inputs/cuda.h"
 
@@ -55,11 +60,12 @@
 // INT-HOST-DAG: @[[DEVNAMEX:[0-9]+]] = {{.*}}c"_ZL1x\00"
 
 // Test externalized static device variables
-// EXT-DEV-DAG: @_ZL1x__static__[[HASH:.*]] = addrspace(1) externally_initialized global i32 0
-// EXT-HOST-DAG: @[[DEVNAMEX:[0-9]+]] = {{.*}}c"_ZL1x__static__[[HASH:.*]]\00"
+// EXT-DEV-DAG: @_ZL1x.static.[[HASH:.*]] = addrspace(1) externally_initialized global i32 0
+// EXT-HOST-DAG: @[[DEVNAMEX:[0-9]+]] = {{.*}}c"_ZL1x.static.[[HASH:.*]]\00"
+// CUDA-DAG: @_ZL1x__static__[[HASH:.*]] = addrspace(1) externally_initialized global i32 0
 
-// POSTFIX: @_ZL1x__static__[[HASH:.*]] = addrspace(1) externally_initialized global i32 0
-// POSTFIX: @[[DEVNAMEX:[0-9]+]] = {{.*}}c"_ZL1x__static__[[HASH]]\00"
+// POSTFIX: @_ZL1x.static.[[HASH:.*]] = addrspace(1) externally_initialized global i32 0
+// POSTFIX: @[[DEVNAMEX:[0-9]+]] = {{.*}}c"_ZL1x.static.[[HASH]]\00"
 
 static __device__ int x;
 
@@ -73,8 +79,8 @@
 // INT-HOST-DAG: @[[DEVNAMEY:[0-9]+]] = {{.*}}c"_ZL1y\00"
 
 // Test externalized static device variables
-// EXT-DEV-DAG: @_ZL1y__static__[[HASH]] = addrspace(4) externally_initialized global i32 0
-// EXT-HOST-DAG: @[[DEVNAMEY:[0-9]+]] = {{.*}}c"_ZL1y__static__[[HASH]]\00"
+// EXT-DEV-DAG: @_ZL1y.static.[[HASH]] = addrspace(4) externally_initialized global i32 0
+// EXT-HOST-DAG: @[[DEVNAMEY:[0-9]+]] = {{.*}}c"_ZL1y.static.[[HASH]]\00"
 
 static __constant__ int y;
 
Index: clang/test/CodeGenCUDA/managed-var.cu
===
--- clang/test/CodeGenCUDA/managed-var.cu
+++ clang/test/CodeGenCUDA/managed-var.cu
@@ -1,5 +1,3 @@
-// REQUIRES: x86-registered-target, amdgpu-registered-target
-
 // RUN: %clang_cc1 -no-opaque-pointers -triple amdgcn-amd-amdhsa -fcuda-is-device -std=c++11 \
 // RUN:   -emit-llvm -o - -x hip %s | FileCheck \
 // RUN:   -check-prefixes=COMMON,DEV,NORDC-D %s
@@ -52,15 +50,15 @@
 
 // NORDC-D-DAG: @_ZL2sx.managed = addrspace(1) externally_initialized global i32 1, align 4
 // NORDC-D-DAG: @_ZL2sx = addrspace(1) externally_initialized global i32 addrspace(1)* null
-// RDC-D-DAG: @_ZL2sx__static__[[HASH:.*]].managed = addrspace(1) externally_initialized global i32 1, align 4
-// RDC-D-DAG: @_ZL2sx__static__[[HASH]] = addrspace(1) externally_initialized global i32 addrspace(1)* null
+// RDC-D-DAG: @_ZL2sx.static.[[HASH:.*]].managed = addrspace(1) externally_initialized global i32 1, align 4
+// RDC-D-DAG: @_ZL2sx.static.[[HASH]] = addrspace(1) externally_initialized global i32 addrspace(1)* null
 // HOST-DAG: @_ZL2sx.managed = internal global i32 1
 // HOST-DAG: @_ZL2sx = internal externally_initialized global i32* null
 // NORDC-DAG: @[[DEVNAMESX:[0-9]+]] = {{.*}}c"_ZL2sx\00"
-// RDC-DAG: @[[DEVNAMESX:[0-9]+]] = {{.*}}c"_ZL2sx__static__[[HASH:.*]]\00"
+// RDC-DAG: @[[DEVNAMESX:[0-9]+]] = {{.*}}c"_ZL2sx.static.[[HASH:.*]]\00"
 
-// POSTFIX:  @_ZL2sx__static__[[HASH:.*]] = addrspace(1) externally_initialized global i32 addrspace(1)* null
-// POSTFIX: @[[DEVNAMESX:[0-9]+]] = {{.*}}c"_ZL2sx__static__[[HASH]]\00"
+// POSTFIX:  @_ZL2sx.static.[[HASH:.*]] = addrspace(1) externally_initialized global i32 addrspace(1)* null
+// POSTFIX: @[[DEVNAMESX:[0-9]+]] = {{.*}}c"_ZL2sx.static.[[HASH]]\00"
 static __managed__ int sx = 1;
 
 // DEV-DAG: @llvm.compiler.used
Index: clang/test/CodeGenCUDA/kernel-in-anon-ns.cu
===
--- clang/test/CodeGenCUDA/kernel-in-anon-ns.cu
+++ clang/test/CodeGenCUDA/kernel-in-anon-ns.cu
@@ -6,19 +6,53 @@
 // RUN:   -aux-triple amdgcn-amd-amdhsa 

[clang] 04fb816 - [CUDA][HIP] Externalize kernels with internal linkage

2022-04-22 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2022-04-22T17:05:36-04:00
New Revision: 04fb81674ed7981397ffe70fe6a07b7168f6fe2f

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

LOG: [CUDA][HIP] Externalize kernels with internal linkage

This patch is a continuation of https://reviews.llvm.org/D123353.

Not only kernels in anonymous namespace, but also template
kernels with template arguments in anonymous namespace
need to be externalized.

To be more generic, this patch checks the linkage of a kernel
assuming the kernel does not have __global__ attribute. If
the linkage is internal then clang will externalize it.

This patch also fixes the postfix for externalized symbol
since nvptx does not allow '.' in symbol name.

Reviewed by: Artem Belevich

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

Fixes: https://github.com/llvm/llvm-project/issues/54560

Added: 


Modified: 
clang/lib/AST/ASTContext.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/test/CodeGenCUDA/device-var-linkage.cu
clang/test/CodeGenCUDA/kernel-in-anon-ns.cu
clang/test/CodeGenCUDA/managed-var.cu
clang/test/CodeGenCUDA/static-device-var-rdc.cu

Removed: 




diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index eb8d53a20012b..85d2bcf268f3a 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -12298,7 +12298,9 @@ bool ASTContext::mayExternalize(const Decl *D) const {
   // anonymous name space needs to be externalized to avoid duplicate symbols.
   return (IsStaticVar &&
   (D->hasAttr() || IsExplicitDeviceVar)) ||
- (D->hasAttr() && D->isInAnonymousNamespace());
+ (D->hasAttr() &&
+  basicGVALinkageForFunction(*this, cast(D)) ==
+  GVA_Internal);
 }
 
 bool ASTContext::shouldExternalize(const Decl *D) const {

diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index e1afe81e5a80e..784f2d0e578fa 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -6809,6 +6809,12 @@ bool CodeGenModule::stopAutoInit() {
 
 void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream ,
 const Decl *D) const {
-  OS << (isa(D) ? "__static__" : ".anon.")
- << getContext().getCUIDHash();
+  StringRef Tag;
+  // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers
+  // postfix beginning with '.' since the symbol name can be demangled.
+  if (LangOpts.HIP)
+Tag = (isa(D) ? ".static." : ".intern.");
+  else
+Tag = (isa(D) ? "__static__" : "__intern__");
+  OS << Tag << getContext().getCUIDHash();
 }

diff  --git a/clang/test/CodeGenCUDA/device-var-linkage.cu 
b/clang/test/CodeGenCUDA/device-var-linkage.cu
index 6186d66127878..a214feb0541f9 100644
--- a/clang/test/CodeGenCUDA/device-var-linkage.cu
+++ b/clang/test/CodeGenCUDA/device-var-linkage.cu
@@ -1,15 +1,18 @@
-// RUN: %clang_cc1 -no-opaque-pointers -triple nvptx -fcuda-is-device \
+// RUN: %clang_cc1 -no-opaque-pointers -triple amdgcn -fcuda-is-device \
 // RUN:   -emit-llvm -o - -x hip %s \
 // RUN:   | FileCheck -check-prefixes=DEV,NORDC %s
-// RUN: %clang_cc1 -no-opaque-pointers -triple nvptx -fcuda-is-device \
+// RUN: %clang_cc1 -no-opaque-pointers -triple amdgcn -fcuda-is-device \
 // RUN:   -fgpu-rdc -cuid=abc -emit-llvm -o - -x hip %s \
 // RUN:   | FileCheck -check-prefixes=DEV,RDC %s
-// RUN: %clang_cc1 -no-opaque-pointers -triple nvptx \
+// RUN: %clang_cc1 -no-opaque-pointers -triple x86_64-unknown-gnu-linux \
 // RUN:   -emit-llvm -o - -x hip %s \
 // RUN:   | FileCheck -check-prefixes=HOST,NORDC-H %s
-// RUN: %clang_cc1 -no-opaque-pointers -triple nvptx \
+// RUN: %clang_cc1 -no-opaque-pointers -triple x86_64-unknown-gnu-linux \
 // RUN:   -fgpu-rdc -cuid=abc -emit-llvm -o - -x hip %s \
 // RUN:   | FileCheck -check-prefixes=HOST,RDC-H %s
+// RUN: %clang_cc1 -no-opaque-pointers -triple nvptx -fcuda-is-device \
+// RUN:   -fgpu-rdc -cuid=abc -emit-llvm -o - %s \
+// RUN:   | FileCheck -check-prefixes=CUDA %s
 
 #include "Inputs/cuda.h"
 
@@ -24,7 +27,9 @@ __constant__ int v2;
 // DEV-DAG: @v3 = addrspace(1) externally_initialized global i32 addrspace(1)* 
null
 // NORDC-H-DAG: @v3 = internal externally_initialized global i32* null
 // RDC-H-DAG: @v3 = externally_initialized global i32* null
+#if __HIP__
 __managed__ int v3;
+#endif
 
 // DEV-DAG: @ev1 = external addrspace(1) global i32
 // HOST-DAG: @ev1 = external global i32
@@ -34,25 +39,35 @@ extern __device__ int ev1;
 extern __constant__ int ev2;
 // DEV-DAG: @ev3 = external addrspace(1) externally_initialized global i32 
addrspace(1)*
 // HOST-DAG: @ev3 = external externally_initialized global i32*
+#if __HIP__
 extern __managed__ int 

[PATCH] D124253: [Clang][OpenMP] Fix the issue that temp cubin files are not removed after compilation when using new OpenMP driver

2022-04-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 accepted this revision.
jhuber6 added a comment.
This revision is now accepted and ready to land.

LG


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124253

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


[PATCH] D124260: [clang-format] ColumnLimit check for trailing comments alignment acts wrong for multi-byte UTF-8 #47624

2022-04-22 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

Hi,

could you please reupload your patch with the full diff context? And please add 
a regression test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124260

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


[PATCH] D124253: [Clang][OpenMP] Fix the issue that one temp cubin file is not removed after compilation

2022-04-22 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 updated this revision to Diff 424589.
tianshilei1992 added a comment.
Herald added a subscriber: MaskRay.

update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124253

Files:
  clang/lib/Driver/ToolChains/Cuda.cpp


Index: clang/lib/Driver/ToolChains/Cuda.cpp
===
--- clang/lib/Driver/ToolChains/Cuda.cpp
+++ clang/lib/Driver/ToolChains/Cuda.cpp
@@ -447,7 +447,10 @@
   CmdArgs.push_back("--gpu-name");
   CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
   CmdArgs.push_back("--output-file");
-  CmdArgs.push_back(Args.MakeArgString(TC.getInputFilename(Output)));
+  const char *OutputFileName = Args.MakeArgString(TC.getInputFilename(Output));
+  if (std::string(OutputFileName) != std::string(Output.getFilename()))
+C.addTempFile(OutputFileName);
+  CmdArgs.push_back(OutputFileName);
   for (const auto& II : Inputs)
 CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
 
@@ -606,8 +609,8 @@
 if (!II.isFilename())
   continue;
 
-const char *CubinF = C.addTempFile(
-C.getArgs().MakeArgString(getToolChain().getInputFilename(II)));
+const char *CubinF =
+C.getArgs().MakeArgString(getToolChain().getInputFilename(II));
 
 CmdArgs.push_back(CubinF);
   }


Index: clang/lib/Driver/ToolChains/Cuda.cpp
===
--- clang/lib/Driver/ToolChains/Cuda.cpp
+++ clang/lib/Driver/ToolChains/Cuda.cpp
@@ -447,7 +447,10 @@
   CmdArgs.push_back("--gpu-name");
   CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
   CmdArgs.push_back("--output-file");
-  CmdArgs.push_back(Args.MakeArgString(TC.getInputFilename(Output)));
+  const char *OutputFileName = Args.MakeArgString(TC.getInputFilename(Output));
+  if (std::string(OutputFileName) != std::string(Output.getFilename()))
+C.addTempFile(OutputFileName);
+  CmdArgs.push_back(OutputFileName);
   for (const auto& II : Inputs)
 CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
 
@@ -606,8 +609,8 @@
 if (!II.isFilename())
   continue;
 
-const char *CubinF = C.addTempFile(
-C.getArgs().MakeArgString(getToolChain().getInputFilename(II)));
+const char *CubinF =
+C.getArgs().MakeArgString(getToolChain().getInputFilename(II));
 
 CmdArgs.push_back(CubinF);
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124292: [OpenMP] Use CUDA's non-RDC mode when LTO has whole program visibility

2022-04-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 424587.
jhuber6 added a comment.

Add test line


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124292

Files:
  clang/test/Driver/linker-wrapper.c
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp


Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -595,7 +595,7 @@
 // TODO: Move these to a separate file.
 namespace nvptx {
 Expected assemble(StringRef InputFile, Triple TheTriple,
-   StringRef Arch) {
+   StringRef Arch, bool RDC = true) {
   // NVPTX uses the ptxas binary to create device object files.
   Expected PtxasPath = findProgram("ptxas", {CudaBinaryPath});
   if (!PtxasPath)
@@ -626,7 +626,8 @@
   CmdArgs.push_back(Opt);
   CmdArgs.push_back("--gpu-name");
   CmdArgs.push_back(Arch);
-  CmdArgs.push_back("-c");
+  if (RDC)
+CmdArgs.push_back("-c");
 
   CmdArgs.push_back(InputFile);
 
@@ -933,7 +934,8 @@
 }
 
 Error linkBitcodeFiles(SmallVectorImpl ,
-   const Triple , StringRef Arch) {
+   const Triple , StringRef Arch,
+   bool ) {
   SmallVector, 4> SavedBuffers;
   SmallVector, 4> BitcodeFiles;
   SmallVector NewInputFiles;
@@ -1009,7 +1011,7 @@
   };
 
   // We assume visibility of the whole program if every input file was bitcode.
-  bool WholeProgram = BitcodeFiles.size() == InputFiles.size();
+  WholeProgram = BitcodeFiles.size() == InputFiles.size();
   auto LTOBackend =
   (EmbedBitcode) ? createLTO(TheTriple, Arch, WholeProgram, OutputBitcode)
  : createLTO(TheTriple, Arch, WholeProgram);
@@ -1089,7 +1091,7 @@
   // Is we are compiling for NVPTX we need to run the assembler first.
   if (TheTriple.isNVPTX() && !EmbedBitcode) {
 for (auto  : Files) {
-  auto FileOrErr = nvptx::assemble(File, TheTriple, Arch);
+  auto FileOrErr = nvptx::assemble(File, TheTriple, Arch, !WholeProgram);
   if (!FileOrErr)
 return FileOrErr.takeError();
   File = *FileOrErr;
@@ -1117,10 +1119,11 @@
   for (auto  : LinkerInputMap) {
 DeviceFile  = LinkerInput.getFirst();
 Triple TheTriple = Triple(File.TheTriple);
+bool WholeProgram = false;
 
 // Run LTO on any bitcode files and replace the input with the result.
-if (Error Err =
-linkBitcodeFiles(LinkerInput.getSecond(), TheTriple, File.Arch))
+if (Error Err = linkBitcodeFiles(LinkerInput.getSecond(), TheTriple,
+ File.Arch, WholeProgram))
   return Err;
 
 // If we are embedding bitcode for JIT, skip the final device linking.
@@ -1130,6 +1133,14 @@
   continue;
 }
 
+// If we performed LTO on NVPTX and had whole program visibility, we can 
use
+// CUDA in non-RDC mode.
+if (WholeProgram && TheTriple.isNVPTX()) {
+  assert(!LinkerInput.getSecond().empty() && "No non-RDC image to embed");
+  LinkedImages.push_back(LinkerInput.getSecond().front());
+  continue;
+}
+
 auto ImageOrErr = linkDevice(LinkerInput.getSecond(), TheTriple, 
File.Arch);
 if (!ImageOrErr)
   return ImageOrErr.takeError();
Index: clang/test/Driver/linker-wrapper.c
===
--- clang/test/Driver/linker-wrapper.c
+++ clang/test/Driver/linker-wrapper.c
@@ -38,5 +38,5 @@
 // RUN: clang-linker-wrapper --host-triple x86_64-unknown-linux-gnu --dry-run 
-linker-path \
 // RUN:   /usr/bin/ld -- %t.o -o a.out 2>&1 | FileCheck %s --check-prefix=LTO
 
-// LTO: ptxas{{.*}}-m64 -o {{.*}}.cubin -O2 --gpu-name sm_70 -c {{.*}}.s
-// LTO: nvlink{{.*}}-m64 -o {{.*}}.out -arch sm_70 {{.*}}.cubin
+// LTO: ptxas{{.*}}-m64 -o {{.*}}.cubin -O2 --gpu-name sm_70 {{.*}}.s
+// LTO-NOT: nvlink


Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -595,7 +595,7 @@
 // TODO: Move these to a separate file.
 namespace nvptx {
 Expected assemble(StringRef InputFile, Triple TheTriple,
-   StringRef Arch) {
+   StringRef Arch, bool RDC = true) {
   // NVPTX uses the ptxas binary to create device object files.
   Expected PtxasPath = findProgram("ptxas", {CudaBinaryPath});
   if (!PtxasPath)
@@ -626,7 +626,8 @@
   CmdArgs.push_back(Opt);
   CmdArgs.push_back("--gpu-name");
   CmdArgs.push_back(Arch);
-  CmdArgs.push_back("-c");
+  if (RDC)
+CmdArgs.push_back("-c");
 
   CmdArgs.push_back(InputFile);
 
@@ -933,7 +934,8 @@
 }
 
 Error linkBitcodeFiles(SmallVectorImpl ,
-   

[PATCH] D124292: [OpenMP] Use CUDA's non-RDC mode when LTO has whole program visibility

2022-04-22 Thread Artem Belevich via Phabricator via cfe-commits
tra accepted this revision.
tra added a comment.
This revision is now accepted and ready to land.

LGTM with a minor test nit.




Comment at: clang/test/Driver/linker-wrapper.c:41
 
-// LTO: ptxas{{.*}}-m64 -o {{.*}}.cubin -O2 --gpu-name sm_70 -c {{.*}}.s
-// LTO: nvlink{{.*}}-m64 -o {{.*}}.out -arch sm_70 {{.*}}.cubin
+// LTO: ptxas{{.*}}-m64 -o {{.*}}.cubin -O2 --gpu-name sm_70 {{.*}}.s

// LTO-NOT: nvlink



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124292

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


[PATCH] D124221: Add new builtin __builtin_reflect_struct.

2022-04-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Thank you for looking into this! I've also thought that the 
`__builtin_dump_struct` implementation hasn't been quite as robust as it could 
be. However, the primary use case for that builtin has been for kernel folks to 
debug when they have no access to an actual debugger -- it being a super 
limited interface is actually a feature rather than a bug, in some ways.

I think what you're designing here is straight-up reflection, which is a 
different use case. If we're going to get something that's basically only 
usable in C++, I'm not certain there's much value in adding builtins for 
reflection until WG21 decides what reflection looks like, and then we can 
design around that. (Personally, I think designing usable reflection interfaces 
for C would be considerably harder but would provide considerably more benefit 
to users given the lack of reflection capabilities. There's almost no chance 
WG14 and WG21 would come up with the same interfaces for reflection, so I think 
we've got some opportunity for exploration here.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

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


[PATCH] D103096: [analyzer] Implement cast for ranges of symbolic integers

2022-04-22 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov marked 10 inline comments as done.
ASDenysPetrov added a comment.

Thank you for the review @martong! Your work is not less harder then mine. I'll 
rework and update the revision ASAP.




Comment at: clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp:421-426
+  // Unwrap symbolic expression to skip argument casts on function call.
+  // This is useful when there is no way for overloading function in C
+  // but we need to pass different types of arguments and
+  // implicit cast occures.
+  Sym = Sym->ignoreCasts();
+

martong wrote:
> Does it really matter? I mean, why do we need this change?
I investigated. This changes is not obligatory now. I'll remove it.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:2227-2251
+  llvm::SmallSet SimplifiedClasses;
+  // Iterate over all equivalence classes and try to simplify them.
+  ClassMembersTy Members = State->get();
+  for (std::pair ClassToSymbolSet : Members) {
+EquivalenceClass Class = ClassToSymbolSet.first;
+State = EquivalenceClass::simplify(Builder, RangeFactory, State, Class);
+if (!State)

martong wrote:
> I think this hunk should remain in `assignSymExprToConst`. Why did you move 
> it?
I'll remove. It's unrelated one.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:2280-2290
+/// Return a symbol which is the best canidate to save it in the constraint
+/// map. We should correct symbol because in case of truncation cast we can
+/// only reason about truncated bytes but not the whole value. E.g. (char)(int
+/// x), we can store constraints for the first lower byte but we still don't
+/// know the root value. Also in case of promotion or converion we should
+/// store the root value instead of cast symbol, because we can always get
+/// a correct range using `castTo` metho. And we are not intrested in any

martong wrote:
> I think, we should definitely store the constraints as they appear in the 
> analyzed code. This way we mix the infer logic into the constraint setting, 
> which is bad.
> I mean, we should simply store the constraint directly for the symbol as it 
> is. And then only in `VisitSymbolCast` should we infer the proper value from 
> the stored constraint (if we can).
> 
> (Of course, if we have related symbols (casts of the original symbol) then 
> their constraints must be updated.)
I see what you mean. I thought about this. Here what I've faced with.
# Let's say you meet `(wchar_t)x > 0`, which you store like a pair {(wchar_t)x, 
[1,32767]}.
# Then you meet `(short)x < 0`, where you have to answer whether it's `true` or 
`false`.
# So would be your next step? Brute forcing all the constraint pairs to find 
any `x`-related symbol? Obviously, O(n) complexity for every single integral 
symbol is inefficient.
What I propose is to "canonize" arbitrary types to a general form where this 
form could be a part of key along with `x` and we could get a constraint with a 
classic map complexity. So that:
# You meet `(wchar_t)x > 0`, which you convert `wchar_t` to `int16` and store 
like a pair {(int16)x, [1,32767]}.
# Then you meet `(short)x < 0`, where you convert `short` to `int16` and get a 
constraint.
That's why I've introduced `NominalTypeList`.
But now I admited your concern about arbitrary size of integers and will 
redesign my solution.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:2346-2350
+/// FIXME: Update bigger casts. We only can reason about ranges of smaller
+/// types, because it would be too complicated to update, say, the entire
+/// `int` range if you only have knowledge that its lowest byte has been
+/// changed. So we don't touch bigger casts and they may be potentially
+/// invalid. For future, for:

martong wrote:
> Instead of a noop we should be more conservative in this case. We should 
> invalidate (remove) the constraints of all the symbols that have more bits 
> than the currently set symbol. However, we might be clever in cases of 
> special values (e.g `0` or in case of the `true` rangeSet {[MIN, -1], [1, 
> MAX]}).
No, it's incorrect. Consider next:
```
int x;
if(x > 100 || x < 10) 
  return;
// x (100'000, 1000'000) 
if((int8)x != 42) 
  return;
// x (100'000, 1000'000) && (int8)x (42, 42) 
```
We can't just remove or invalidate `x (100'000, 1000'000)` because this range 
will still stay //true//.
Strictly speaking `x` range should be updated with values 100394, 102442, 
108586, ...,, 960554 and any other value within the range which has its lowest 
byte equals to 42.
We can't just update the `RangeSet` with such a big amount of values due to 
performance issues. So we just assume it as less accurate.


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

https://reviews.llvm.org/D103096

___
cfe-commits mailing 

[PATCH] D124292: [OpenMP] Use CUDA's non-RDC mode when LTO has whole program visibility

2022-04-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: jdoerfert, tianshilei1992, tra, JonChesterfield.
Herald added subscribers: mattd, guansong, inglorion, yaxunl.
Herald added a project: All.
jhuber6 requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1.
Herald added a project: clang.

When we do LTO we consider ourselves to have whole program visibility if
every single input file we have contains LLVM bitcode. If we have whole
program visibliity then we can create a single image and utilize CUDA's
non-RDC mode by not passing `-c` to `ptxas` and ignoring the `nvlink`
job. This should be faster for some situations and also saves us the
time executing `nvlink`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124292

Files:
  clang/test/Driver/linker-wrapper.c
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp


Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -595,7 +595,7 @@
 // TODO: Move these to a separate file.
 namespace nvptx {
 Expected assemble(StringRef InputFile, Triple TheTriple,
-   StringRef Arch) {
+   StringRef Arch, bool RDC = true) {
   // NVPTX uses the ptxas binary to create device object files.
   Expected PtxasPath = findProgram("ptxas", {CudaBinaryPath});
   if (!PtxasPath)
@@ -626,7 +626,8 @@
   CmdArgs.push_back(Opt);
   CmdArgs.push_back("--gpu-name");
   CmdArgs.push_back(Arch);
-  CmdArgs.push_back("-c");
+  if (RDC)
+CmdArgs.push_back("-c");
 
   CmdArgs.push_back(InputFile);
 
@@ -933,7 +934,8 @@
 }
 
 Error linkBitcodeFiles(SmallVectorImpl ,
-   const Triple , StringRef Arch) {
+   const Triple , StringRef Arch,
+   bool ) {
   SmallVector, 4> SavedBuffers;
   SmallVector, 4> BitcodeFiles;
   SmallVector NewInputFiles;
@@ -1009,7 +1011,7 @@
   };
 
   // We assume visibility of the whole program if every input file was bitcode.
-  bool WholeProgram = BitcodeFiles.size() == InputFiles.size();
+  WholeProgram = BitcodeFiles.size() == InputFiles.size();
   auto LTOBackend =
   (EmbedBitcode) ? createLTO(TheTriple, Arch, WholeProgram, OutputBitcode)
  : createLTO(TheTriple, Arch, WholeProgram);
@@ -1089,7 +1091,7 @@
   // Is we are compiling for NVPTX we need to run the assembler first.
   if (TheTriple.isNVPTX() && !EmbedBitcode) {
 for (auto  : Files) {
-  auto FileOrErr = nvptx::assemble(File, TheTriple, Arch);
+  auto FileOrErr = nvptx::assemble(File, TheTriple, Arch, !WholeProgram);
   if (!FileOrErr)
 return FileOrErr.takeError();
   File = *FileOrErr;
@@ -1117,10 +1119,11 @@
   for (auto  : LinkerInputMap) {
 DeviceFile  = LinkerInput.getFirst();
 Triple TheTriple = Triple(File.TheTriple);
+bool WholeProgram = false;
 
 // Run LTO on any bitcode files and replace the input with the result.
-if (Error Err =
-linkBitcodeFiles(LinkerInput.getSecond(), TheTriple, File.Arch))
+if (Error Err = linkBitcodeFiles(LinkerInput.getSecond(), TheTriple,
+ File.Arch, WholeProgram))
   return Err;
 
 // If we are embedding bitcode for JIT, skip the final device linking.
@@ -1130,6 +1133,14 @@
   continue;
 }
 
+// If we performed LTO on NVPTX and had whole program visibility, we can 
use
+// CUDA in non-RDC mode.
+if (WholeProgram && TheTriple.isNVPTX()) {
+  assert(!LinkerInput.getSecond().empty() && "No non-RDC image to embed");
+  LinkedImages.push_back(LinkerInput.getSecond().front());
+  continue;
+}
+
 auto ImageOrErr = linkDevice(LinkerInput.getSecond(), TheTriple, 
File.Arch);
 if (!ImageOrErr)
   return ImageOrErr.takeError();
Index: clang/test/Driver/linker-wrapper.c
===
--- clang/test/Driver/linker-wrapper.c
+++ clang/test/Driver/linker-wrapper.c
@@ -38,5 +38,4 @@
 // RUN: clang-linker-wrapper --host-triple x86_64-unknown-linux-gnu --dry-run 
-linker-path \
 // RUN:   /usr/bin/ld -- %t.o -o a.out 2>&1 | FileCheck %s --check-prefix=LTO
 
-// LTO: ptxas{{.*}}-m64 -o {{.*}}.cubin -O2 --gpu-name sm_70 -c {{.*}}.s
-// LTO: nvlink{{.*}}-m64 -o {{.*}}.out -arch sm_70 {{.*}}.cubin
+// LTO: ptxas{{.*}}-m64 -o {{.*}}.cubin -O2 --gpu-name sm_70 {{.*}}.s


Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -595,7 +595,7 @@
 // TODO: Move these to a separate file.
 namespace nvptx {
 Expected assemble(StringRef InputFile, Triple TheTriple,
-   

[PATCH] D124131: Thread safety analysis: Store capability kind in CapabilityExpr

2022-04-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Analysis/Analyses/ThreadSafetyCommon.h:277
+  /// The kind of capability as specified by @ref CapabilityAttr::getName.
+  StringRef CapKind;
+

Hr, I think this may actually be safe, but it does give me pause to store a 
`StringRef` as anything other than a local (or param/return type): 
https://llvm.org/docs/ProgrammersManual.html#the-stringref-class

Can you double-check my thinking? This is fine because it's pulling the 
`StringRef` from the `CapabilityAttr`, and that stores its name internally and 
isn't released until the AST is destroyed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124131

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


[PATCH] D124280: [git-clang-format] Change run line from python to python3

2022-04-22 Thread Nico Weber 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 rGc94a02e0e223: [git-clang-format] Change run line from python 
to python3 (authored by thakis).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124280

Files:
  clang/tools/clang-format/git-clang-format


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #
 #===- git-clang-format - ClangFormat Git Integration -*- python 
-*--===#
 #


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #
 #===- git-clang-format - ClangFormat Git Integration -*- python -*--===#
 #
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] c94a02e - [git-clang-format] Change run line from python to python3

2022-04-22 Thread Nico Weber via cfe-commits

Author: Nico Weber
Date: 2022-04-22T15:14:51-04:00
New Revision: c94a02e0e223bcce3b2c88741fae35d31a2d4f1d

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

LOG: [git-clang-format] Change run line from python to python3

Several systems no longer ship `python`.

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

Added: 


Modified: 
clang/tools/clang-format/git-clang-format

Removed: 




diff  --git a/clang/tools/clang-format/git-clang-format 
b/clang/tools/clang-format/git-clang-format
index 86f4497ed599d..96f415e8e561a 100755
--- a/clang/tools/clang-format/git-clang-format
+++ b/clang/tools/clang-format/git-clang-format
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #
 #===- git-clang-format - ClangFormat Git Integration -*- python 
-*--===#
 #



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


[clang] a45764f - [git-clang-format] Add some examples to the help text

2022-04-22 Thread Nico Weber via cfe-commits

Author: Nico Weber
Date: 2022-04-22T15:14:04-04:00
New Revision: a45764f2f9cf0d2d6ec5bd871cc9c36ebf785ccc

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

LOG: [git-clang-format] Add some examples to the help text

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

Added: 


Modified: 
clang/tools/clang-format/git-clang-format

Removed: 




diff  --git a/clang/tools/clang-format/git-clang-format 
b/clang/tools/clang-format/git-clang-format
index 1d6f216240c1c..86f4497ed599d 100755
--- a/clang/tools/clang-format/git-clang-format
+++ b/clang/tools/clang-format/git-clang-format
@@ -40,6 +40,16 @@ If zero or one commits are given, run clang-format on all 
lines that 
diff er
 between the working directory and , which defaults to HEAD.  Changes 
are
 only applied to the working directory, or in the stage/index.
 
+Examples:
+  To format staged changes, i.e everything that's been `git add`ed:
+git clang-format
+
+  To also format everything touched in the most recent commit:
+git clang-format HEAD~1
+
+  If you're on a branch off main, to format everything touched on your branch:
+git clang-format main
+
 If two commits are given (requires --
diff ), run clang-format on all lines in the
 second  that 
diff er from the first .
 



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


[PATCH] D124282: [git-clang-format] Add some examples to the help text

2022-04-22 Thread Nico Weber 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 rGa45764f2f9cf: [git-clang-format] Add some examples to the 
help text (authored by thakis).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124282

Files:
  clang/tools/clang-format/git-clang-format


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -40,6 +40,16 @@
 between the working directory and , which defaults to HEAD.  Changes 
are
 only applied to the working directory, or in the stage/index.
 
+Examples:
+  To format staged changes, i.e everything that's been `git add`ed:
+git clang-format
+
+  To also format everything touched in the most recent commit:
+git clang-format HEAD~1
+
+  If you're on a branch off main, to format everything touched on your branch:
+git clang-format main
+
 If two commits are given (requires --diff), run clang-format on all lines in 
the
 second  that differ from the first .
 


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -40,6 +40,16 @@
 between the working directory and , which defaults to HEAD.  Changes are
 only applied to the working directory, or in the stage/index.
 
+Examples:
+  To format staged changes, i.e everything that's been `git add`ed:
+git clang-format
+
+  To also format everything touched in the most recent commit:
+git clang-format HEAD~1
+
+  If you're on a branch off main, to format everything touched on your branch:
+git clang-format main
+
 If two commits are given (requires --diff), run clang-format on all lines in the
 second  that differ from the first .
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124258: [C89/C2x] Change the behavior of implicit int diagnostics

2022-04-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:168-169
+  ``-Wno-error=implicit-int``, or disabled entirely with ``-Wno-implicit-int``.
+  As of C2x, support for implicit int has been removed, and the warning options
+  will have no effect. Specifying ``-Wimplicit-int`` in C89 mode will now issue
+  warnings instead of being a noop.

rsmith wrote:
> Is there some fundamental reason why implicit int is harder to support in C2x 
> (as there was for implicit function declarations, because unprototyped 
> functions are gone), or are we merely taking the opportunity to do this 
> because C2x is new? I find the former more easily defensible than the latter, 
> but I suppose the fact that we removed implicit function declarations means 
> that C2x is the first really properly breaking change that C has had, so 
> maybe now is the time regardless.
Purely the latter -- C2x didn't make anything harder here. However, I'd like to 
position C23 as "not your grandfather's C" in Clang by strengthening 
diagnostics, especially ones related to safety or security vulnerabilities. 
Basically, I think it's time to cut ties with as many dangerous things that 
have been excised from C as possible. I think implicit int fits that goal in 
the same way that implicit function decls do (namely, the implicit choice can 
be wrong and you get surprising silent breakage at runtime if you're lucky).

(FWIW, I'm also hoping to get these sort of changes lumped into Clang 15 so 
that the pain of upgrading is more localized to just one release rather than 
strung out over several.)


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

https://reviews.llvm.org/D124258

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


[PATCH] D124066: [clang-tidy] Ignore macros defined within declarations in modernize-macro-to-enum

2022-04-22 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.

In D124066#3463109 , 
@LegalizeAdulthood wrote:

> In D124066#3463008 , @aaron.ballman 
> wrote:
>
>> This seems like a case where we might want a configuration option (maybe). 
>> [...]
>> WDYT?
>
> In my bug report on this problem, I sketch out a plan of attack:
>
> 1. **DON'T BREAK MY CODE** -- that is this review `:)`
> 2. Do some analysis of macro expansion locations to determine the nearest 
> enclosing scope at which the enum should be declared.
>
> https://github.com/llvm/llvm-project/issues/54883

Ah, thank you for the explanation. I like not breaking code. :-) LGTM aside 
from a possible simplification for the matchers.




Comment at: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp:561-567
+  Finder->addMatcher(varDecl(TopLevelDecl).bind("top"), this);
+  Finder->addMatcher(functionDecl(TopLevelDecl).bind("top"), this);
+  Finder->addMatcher(recordDecl(TopLevelDecl).bind("top"), this);
+  Finder->addMatcher(typeAliasDecl(TopLevelDecl).bind("top"), this);
+  Finder->addMatcher(functionTemplateDecl(TopLevelDecl).bind("top"), this);
+  Finder->addMatcher(classTemplateDecl(TopLevelDecl).bind("top"), this);
+  Finder->addMatcher(typeAliasTemplateDecl(TopLevelDecl).bind("top"), this);

Can we mix these together with `anyOf()` so we're not adding so many matchers? 
e.g.,
```
Finder->addMatcher(anyOf(varDecl(TopLevelDecl), functionDecl(topLevelDecl()), 
...).bind("top"), this);
```


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

https://reviews.llvm.org/D124066

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


[PATCH] D121176: [ASTStructuralEquivalence] Add support for comparing ObjCCategoryDecl.

2022-04-22 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai updated this revision to Diff 424561.
vsapsai added a comment.

Rebase and trigger pre-commit tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121176

Files:
  clang/include/clang/Testing/CommandLineArgs.h
  clang/lib/AST/ASTStructuralEquivalence.cpp
  clang/lib/Testing/CommandLineArgs.cpp
  clang/unittests/AST/MatchVerifier.h
  clang/unittests/AST/StructuralEquivalenceTest.cpp

Index: clang/unittests/AST/StructuralEquivalenceTest.cpp
===
--- clang/unittests/AST/StructuralEquivalenceTest.cpp
+++ clang/unittests/AST/StructuralEquivalenceTest.cpp
@@ -1120,6 +1120,187 @@
   EXPECT_FALSE(testStructuralMatch(t));
 }
 
+struct StructuralEquivalenceObjCCategoryTest : StructuralEquivalenceTest {};
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, MatchinCategoryNames) {
+  auto t = makeDecls("@interface A @end @interface A(X) @end",
+   "@interface A @end @interface A(X) @end",
+   Lang_OBJC, objcCategoryDecl());
+  EXPECT_TRUE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, CategoriesForDifferentClasses) {
+  auto t = makeDecls("@interface A @end @interface A(X) @end",
+   "@interface B @end @interface B(X) @end",
+   Lang_OBJC, objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, CategoriesWithDifferentNames) {
+  auto t = makeDecls("@interface A @end @interface A(X) @end",
+   "@interface A @end @interface A(Y) @end",
+   Lang_OBJC, objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, CategoryAndExtension) {
+  auto t = makeDecls("@interface A @end @interface A(X) @end",
+   "@interface A @end @interface A() @end",
+   Lang_OBJC, objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, MatchingProtocols) {
+  auto t = makeDecls(
+  "@protocol P @end @interface A @end @interface A(X) @end",
+  "@protocol P @end @interface A @end @interface A(X) @end", Lang_OBJC,
+  objcCategoryDecl());
+  EXPECT_TRUE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, DifferentProtocols) {
+  auto t = makeDecls(
+  "@protocol P @end @interface A @end @interface A(X) @end",
+  "@protocol Q @end @interface A @end @interface A(X) @end", Lang_OBJC,
+  objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, DifferentProtocolsOrder) {
+  auto t = makeDecls(
+  "@protocol P @end @protocol Q @end @interface A @end @interface A(X) @end",
+  "@protocol P @end @protocol Q @end @interface A @end @interface A(X) @end",
+  Lang_OBJC, objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, MatchingIvars) {
+  auto t = makeDecls(
+  "@interface A @end @interface A() { int x; } @end",
+  "@interface A @end @interface A() { int x; } @end", Lang_OBJC,
+  objcCategoryDecl());
+  EXPECT_TRUE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, DifferentIvarName) {
+  auto t = makeDecls(
+  "@interface A @end @interface A() { int x; } @end",
+  "@interface A @end @interface A() { int y; } @end", Lang_OBJC,
+  objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, DifferentIvarType) {
+  auto t = makeDecls(
+  "@interface A @end @interface A() { int x; } @end",
+  "@interface A @end @interface A() { float x; } @end", Lang_OBJC,
+  objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, DifferentIvarBitfieldWidth) {
+  auto t = makeDecls(
+  "@interface A @end @interface A() { int x: 1; } @end",
+  "@interface A @end @interface A() { int x: 2; } @end", Lang_OBJC,
+  objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, DifferentIvarVisibility) {
+  auto t = makeDecls(
+  "@interface A @end @interface A() { @public int x; } @end",
+  "@interface A @end @interface A() { @protected int x; } @end", Lang_OBJC,
+  objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceObjCCategoryTest, DifferentIvarNumber) {
+  auto t = makeDecls(
+  "@interface A @end @interface A() { int x; } @end",
+  "@interface A @end @interface A() {} @end", Lang_OBJC,
+  objcCategoryDecl());
+  EXPECT_FALSE(testStructuralMatch(t));
+}
+

[PATCH] D124258: [C89/C2x] Change the behavior of implicit int diagnostics

2022-04-22 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:168-169
+  ``-Wno-error=implicit-int``, or disabled entirely with ``-Wno-implicit-int``.
+  As of C2x, support for implicit int has been removed, and the warning options
+  will have no effect. Specifying ``-Wimplicit-int`` in C89 mode will now issue
+  warnings instead of being a noop.

Is there some fundamental reason why implicit int is harder to support in C2x 
(as there was for implicit function declarations, because unprototyped 
functions are gone), or are we merely taking the opportunity to do this because 
C2x is new? I find the former more easily defensible than the latter, but I 
suppose the fact that we removed implicit function declarations means that C2x 
is the first really properly breaking change that C has had, so maybe now is 
the time regardless.


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

https://reviews.llvm.org/D124258

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


[PATCH] D124280: [git-clang-format] Change run line from python to python3

2022-04-22 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added a comment.
This revision is now accepted and ready to land.

LGTM. Especially that we already use python3 in clang-format-diff and other 
scripts, and it's used in many places in LLVM.


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

https://reviews.llvm.org/D124280

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


[PATCH] D124286: [modules] Allow parsing a duplicate Obj-C interface if a previous one comes from a hidden [sub]module.

2022-04-22 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added a comment.

I also have a very similar change with `ActOnDuplicateDefinition` for 
`ObjCProtocolDecl`. If anybody is interested in how it compares with 
`ObjCInterfaceDecl`, I can publish that but it's not finished yet.




Comment at: clang/lib/Parse/ParseObjc.cpp:16
 #include "clang/Basic/CharInfo.h"
+#include "clang/Basic/DiagnosticSema.h"
 #include "clang/Basic/TargetInfo.h"

I'd like to get feedback on Parser/Sema layering. I'll check myself what can be 
done but at the first glance accessing pieces of Sema from Parser looks 
questionable.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124286

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


[PATCH] D124287: [modules][ODRHash] Compare ODR hashes to detect mismatches in duplicate ObjCInterfaceDecl.

2022-04-22 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added a comment.

As a proof of concept how ODR hash comparison can be used during  
deserialization, please see D124289 . My 
point is to highlight the amount of reuse we gain from using ODR hash (I 
particularly enjoy the test case reuse). I agree the error messages aren't 
particularly useful yet and it will take some work to make code in 
`ASTReader::diagnoseOdrViolations` usable from parser. But I believe that 
should be doable.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124287

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


[PATCH] D124288: [Index] Add a USR and symbol kind for UnresolvedUsingIfExists

2022-04-22 Thread Ben Barham via Phabricator via cfe-commits
bnbarham added inline comments.



Comment at: clang/test/Index/using_if_exists.cpp:9
+// CHECK: [[@LINE-1]]:11 | using/C++ | foo | c:@UD@foo |  | Decl | 
rel: 0
+// CHECK: [[@LINE-2]]:11 | using/using-unresolved/C++ | foo | 
c:using_if_exists.cpp@UUIE@foo |  | Ref | rel: 0

The AST here is:
UsingDecl -> UsingShadowDecl -> UnresolvedUsingIfExistsDecl

So the `UnresolvedUsingIfExistsDecl` is a reference, which is a bit weird since 
there is no decl. But... there is no decl ("foo" doesn't exist), so this seems 
somewhat reasonable. Any objections?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124288

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


[PATCH] D124289: [modules] Proof of concept in using ODR hash to detect mismatching duplicate ObjCInterfaceDecl during deserialization.

2022-04-22 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai created this revision.
Herald added a subscriber: ributzka.
Herald added a project: All.
vsapsai 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/D124289

Files:
  clang/include/clang/AST/DeclObjC.h
  clang/include/clang/Serialization/ASTReader.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/test/Modules/compare-objc-interface.m
  clang/test/Modules/interface-diagnose-missing-import.m
  clang/test/Modules/method_pool.m

Index: clang/test/Modules/method_pool.m
===
--- clang/test/Modules/method_pool.m
+++ clang/test/Modules/method_pool.m
@@ -28,6 +28,9 @@
 }
 
 @import MethodPoolB;
+//FIXME: main definition should come from MethodPoolA and definition in MethodPoolB should be a duplicate
+// expected-error@MethodPoolA.h:* {{duplicate interface definition for class 'B'}}
+// expected-note@MethodPoolB.h:* {{previous definition is here}}
 
 void testMethod1Again(id object) {
   [object method1];
Index: clang/test/Modules/interface-diagnose-missing-import.m
===
--- clang/test/Modules/interface-diagnose-missing-import.m
+++ clang/test/Modules/interface-diagnose-missing-import.m
@@ -1,7 +1,9 @@
 // RUN: rm -rf %t
 // RUN: %clang_cc1 %s -fsyntax-only -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -F%S/Inputs/interface-diagnose-missing-import -verify
 // expected-no-diagnostics
-@interface Buggy
+@interface NSObject
+@end
+@interface Buggy: NSObject
 @end
 
 @import Foo.Bar;
Index: clang/test/Modules/compare-objc-interface.m
===
--- clang/test/Modules/compare-objc-interface.m
+++ clang/test/Modules/compare-objc-interface.m
@@ -11,13 +11,21 @@
 // RUN: cat %t/test.m >> %t/include/second-textual.h
 // RUN: echo "#undef SECOND"  >> %t/include/second-textual.h
 
+// Build second modular header file
+// RUN: echo "#define SECOND" >> %t/include/second-modular.h
+// RUN: cat %t/test.m >> %t/include/second-modular.h
+// RUN: echo "#undef SECOND"  >> %t/include/second-modular.h
+
 // Test that each header can compile
 // RUN: %clang_cc1 -fsyntax-only -x objective-c %t/include/first.h -fblocks -fobjc-arc
 // RUN: %clang_cc1 -fsyntax-only -x objective-c %t/include/second-textual.h -fblocks -fobjc-arc
+// RUN: %clang_cc1 -fsyntax-only -x objective-c %t/include/second-modular.h -fblocks -fobjc-arc
 
 // Run test
 // RUN: %clang_cc1 -I%t/include -verify %t/test.m -fblocks -fobjc-arc \
 // RUN:-fmodules -fimplicit-module-maps -fmodules-cache-path=%t/modules.cache
+// RUN: %clang_cc1 -I%t/include -verify %t/test.m -fblocks -fobjc-arc -DTEST_MODULAR=1 \
+// RUN:-fmodules -fimplicit-module-maps -fmodules-cache-path=%t/modules.cache
 
 // In non-modular case we don't allow interface redefinitions. But with modules
 // previous definition can come from a hidden [sub]module. And in this case we
@@ -54,14 +62,23 @@
 export *
   }
 }
+module Second {
+  header "second-modular.h"
+  export *
+}
 
 //--- test.m
 #if defined(FIRST) || defined(SECOND)
-#include "common.h"
+# include "common.h"
 #endif
+
 #if !defined(FIRST) && !defined(SECOND)
-#include "first-empty.h"
-#include "second-textual.h"
+# include "first-empty.h"
+# ifdef TEST_MODULAR
+#  include "second-modular.h"
+# else
+#  include "second-textual.h"
+# endif
 #endif
 
 #if defined(FIRST)
@@ -81,6 +98,6 @@
 @interface CompareSuperClass : CommonClass @end
 #else
 CompareSuperClass *compareSuperClass;
-// expected-error@second-textual.h:* {{duplicate interface definition for class 'CompareSuperClass'}}
+// expected-error@*:* {{duplicate interface definition for class 'CompareSuperClass'}}
 // expected-note@first.h:* {{previous definition is here}}
 #endif
Index: clang/lib/Serialization/ASTWriterDecl.cpp
===
--- clang/lib/Serialization/ASTWriterDecl.cpp
+++ clang/lib/Serialization/ASTWriterDecl.cpp
@@ -761,6 +761,8 @@
 Record.AddSourceLocation(D->getEndOfDefinitionLoc());
 Record.push_back(Data.HasDesignatedInitializers);
 
+Record.push_back(D->getODRHash());
+
 // Write out the protocols that are directly referenced by the @interface.
 Record.push_back(Data.ReferencedProtocols.size());
 for (const auto *P : D->protocols())
Index: clang/lib/Serialization/ASTReaderDecl.cpp
===
--- clang/lib/Serialization/ASTReaderDecl.cpp
+++ clang/lib/Serialization/ASTReaderDecl.cpp
@@ -1152,6 +1152,8 @@
 
   Data.EndLoc = readSourceLocation();
   Data.HasDesignatedInitializers = Record.readInt();
+  Data.ODRHash = Record.readInt();
+  Data.HasODRHash = true;
 
   // Read the directly 

[PATCH] D124288: [Index] Add a USR and symbol kind for UnresolvedUsingIfExists

2022-04-22 Thread Ben Barham via Phabricator via cfe-commits
bnbarham created this revision.
bnbarham added reviewers: benlangmuir, arphaman, jansvoboda11.
Herald added a project: All.
bnbarham requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

`UnresolvedUsingIfExists` has existed for a long time now, but it never
had a USR or symbol kind added. Add those now.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124288

Files:
  clang/include/clang/Index/IndexSymbol.h
  clang/lib/Index/IndexSymbol.cpp
  clang/lib/Index/USRGeneration.cpp
  clang/test/Index/using_if_exists.cpp


Index: clang/test/Index/using_if_exists.cpp
===
--- /dev/null
+++ clang/test/Index/using_if_exists.cpp
@@ -0,0 +1,9 @@
+// RUN: c-index-test core -print-source-symbols -- %s -target 
x86_64-unknown-unknown 2>&1 | FileCheck %s
+
+namespace ns {
+//  void foo();
+}
+
+using ns::foo __attribute__((using_if_exists));
+// CHECK: [[@LINE-1]]:11 | using/C++ | foo | c:@UD@foo |  | Decl | 
rel: 0
+// CHECK: [[@LINE-2]]:11 | using/using-unresolved/C++ | foo | 
c:using_if_exists.cpp@UUIE@foo |  | Ref | rel: 0
Index: clang/lib/Index/USRGeneration.cpp
===
--- clang/lib/Index/USRGeneration.cpp
+++ clang/lib/Index/USRGeneration.cpp
@@ -103,6 +103,7 @@
   void VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl *D);
   void VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D);
   void VisitUnresolvedUsingTypenameDecl(const UnresolvedUsingTypenameDecl *D);
+  void VisitUnresolvedUsingIfExistsDecl(const UnresolvedUsingIfExistsDecl *D);
 
   void VisitLinkageSpecDecl(const LinkageSpecDecl *D) {
 IgnoreResults = true; // No USRs for linkage specs themselves.
@@ -1007,7 +1008,14 @@
   Out << D->getName(); // Simple name.
 }
 
-
+void USRGenerator::VisitUnresolvedUsingIfExistsDecl(
+const UnresolvedUsingIfExistsDecl *D) {
+  if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
+return;
+  VisitDeclContext(D->getDeclContext());
+  Out << "@UUIE@";
+  Out << D->getName();
+}
 
 
//===--===//
 // USR generation functions.
Index: clang/lib/Index/IndexSymbol.cpp
===
--- clang/lib/Index/IndexSymbol.cpp
+++ clang/lib/Index/IndexSymbol.cpp
@@ -334,6 +334,11 @@
   Info.Lang = SymbolLanguage::CXX;
   Info.SubKind = SymbolSubKind::UsingEnum;
   break;
+case Decl::UnresolvedUsingIfExists:
+  Info.Kind = SymbolKind::Using;
+  Info.SubKind = SymbolSubKind::UnresolvedUsing;
+  Info.Lang = SymbolLanguage::CXX;
+  break;
 case Decl::Binding:
   Info.Kind = SymbolKind::Variable;
   Info.Lang = SymbolLanguage::CXX;
@@ -549,6 +554,8 @@
   case SymbolSubKind::UsingValue: return "using-value";
   case SymbolSubKind::UsingEnum:
 return "using-enum";
+  case SymbolSubKind::UnresolvedUsing:
+return "using-unresolved";
   }
   llvm_unreachable("invalid symbol subkind");
 }
Index: clang/include/clang/Index/IndexSymbol.h
===
--- clang/include/clang/Index/IndexSymbol.h
+++ clang/include/clang/Index/IndexSymbol.h
@@ -76,6 +76,7 @@
   UsingTypename,
   UsingValue,
   UsingEnum,
+  UnresolvedUsing,
 };
 
 typedef uint16_t SymbolPropertySet;


Index: clang/test/Index/using_if_exists.cpp
===
--- /dev/null
+++ clang/test/Index/using_if_exists.cpp
@@ -0,0 +1,9 @@
+// RUN: c-index-test core -print-source-symbols -- %s -target x86_64-unknown-unknown 2>&1 | FileCheck %s
+
+namespace ns {
+//  void foo();
+}
+
+using ns::foo __attribute__((using_if_exists));
+// CHECK: [[@LINE-1]]:11 | using/C++ | foo | c:@UD@foo |  | Decl | rel: 0
+// CHECK: [[@LINE-2]]:11 | using/using-unresolved/C++ | foo | c:using_if_exists.cpp@UUIE@foo |  | Ref | rel: 0
Index: clang/lib/Index/USRGeneration.cpp
===
--- clang/lib/Index/USRGeneration.cpp
+++ clang/lib/Index/USRGeneration.cpp
@@ -103,6 +103,7 @@
   void VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl *D);
   void VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D);
   void VisitUnresolvedUsingTypenameDecl(const UnresolvedUsingTypenameDecl *D);
+  void VisitUnresolvedUsingIfExistsDecl(const UnresolvedUsingIfExistsDecl *D);
 
   void VisitLinkageSpecDecl(const LinkageSpecDecl *D) {
 IgnoreResults = true; // No USRs for linkage specs themselves.
@@ -1007,7 +1008,14 @@
   Out << D->getName(); // Simple name.
 }
 
-
+void USRGenerator::VisitUnresolvedUsingIfExistsDecl(
+const UnresolvedUsingIfExistsDecl *D) {
+  if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
+return;
+  VisitDeclContext(D->getDeclContext());
+  Out << "@UUIE@";
+  Out << 

[PATCH] D124287: [modules][ODRHash] Compare ODR hashes to detect mismatches in duplicate ObjCInterfaceDecl.

2022-04-22 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai created this revision.
vsapsai added reviewers: jansvoboda11, rsmith, bruno.
Herald added a subscriber: ributzka.
Herald added a project: All.
vsapsai requested review of this revision.
Herald added a project: clang.

The purpose of the change is to start using ODR hash for comparison
instead of ASTStructuralEquivalence and ODR hash calculation is,
unfortunately, incomplete. The decision to use ODR hash is made because
we can use the same mechanism while checking duplicates encountered
during deserialization. For that case ASTStructuralEquivalence is not a
good fit because it can lead to excessive deserialization and
deserialized decls would be used only for ASTStructuralEquivalence.

rdar://82908223


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124287

Files:
  clang/include/clang/AST/DeclObjC.h
  clang/include/clang/AST/ODRHash.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/DeclObjC.cpp
  clang/lib/AST/ODRHash.cpp
  clang/lib/Parse/ParseObjc.cpp
  clang/test/Modules/compare-objc-interface.m

Index: clang/test/Modules/compare-objc-interface.m
===
--- /dev/null
+++ clang/test/Modules/compare-objc-interface.m
@@ -0,0 +1,86 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// Build first header file
+// RUN: echo "#define FIRST" >> %t/include/first.h
+// RUN: cat %t/test.m>> %t/include/first.h
+// RUN: echo "#undef FIRST"  >> %t/include/first.h
+
+// Build second header file
+// RUN: echo "#define SECOND" >> %t/include/second-textual.h
+// RUN: cat %t/test.m >> %t/include/second-textual.h
+// RUN: echo "#undef SECOND"  >> %t/include/second-textual.h
+
+// Test that each header can compile
+// RUN: %clang_cc1 -fsyntax-only -x objective-c %t/include/first.h -fblocks -fobjc-arc
+// RUN: %clang_cc1 -fsyntax-only -x objective-c %t/include/second-textual.h -fblocks -fobjc-arc
+
+// Run test
+// RUN: %clang_cc1 -I%t/include -verify %t/test.m -fblocks -fobjc-arc \
+// RUN:-fmodules -fimplicit-module-maps -fmodules-cache-path=%t/modules.cache
+
+// In non-modular case we don't allow interface redefinitions. But with modules
+// previous definition can come from a hidden [sub]module. And in this case we
+// allow a new definition if it is equivalent to the hidden one.
+//
+// This test case is to verify equivalence checks.
+
+//--- include/common.h
+#ifndef COMMON_H
+#define COMMON_H
+__attribute__((objc_root_class))
+@interface NSObject
+@end
+
+@interface CommonClass: NSObject
+@end
+
+@protocol ProtoP @end
+@protocol ProtoQ @end
+#endif
+
+//--- include/first-empty.h
+//--- include/module.modulemap
+module Common {
+  header "common.h"
+  export *
+}
+module First {
+  module Empty {
+header "first-empty.h"
+  }
+  module InitiallyHidden {
+header "first.h"
+export *
+  }
+}
+
+//--- test.m
+#if defined(FIRST) || defined(SECOND)
+#include "common.h"
+#endif
+#if !defined(FIRST) && !defined(SECOND)
+#include "first-empty.h"
+#include "second-textual.h"
+#endif
+
+#if defined(FIRST)
+@class CompareForwardDeclaration1;
+@interface CompareForwardDeclaration2: NSObject @end
+#elif defined(SECOND)
+@interface CompareForwardDeclaration1: NSObject @end
+@class CompareForwardDeclaration2;
+#else
+CompareForwardDeclaration1 *compareForwardDeclaration1;
+CompareForwardDeclaration2 *compareForwardDeclaration2;
+#endif
+
+#if defined(FIRST)
+@interface CompareSuperClass : NSObject @end
+#elif defined(SECOND)
+@interface CompareSuperClass : CommonClass @end
+#else
+CompareSuperClass *compareSuperClass;
+// expected-error@second-textual.h:* {{duplicate interface definition for class 'CompareSuperClass'}}
+// expected-note@first.h:* {{previous definition is here}}
+#endif
Index: clang/lib/Parse/ParseObjc.cpp
===
--- clang/lib/Parse/ParseObjc.cpp
+++ clang/lib/Parse/ParseObjc.cpp
@@ -367,9 +367,9 @@
   ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
 
   if (SkipBody.CheckSameAsPrevious) {
-if (Actions.ActOnDuplicateDefinition(SkipBody.Previous, SkipBody)) {
-  ClsType->mergeDuplicateDefinitionWithCommon(
-  cast(SkipBody.Previous)->getDefinition());
+auto *PreviousDef = cast(SkipBody.Previous);
+if (Actions.ActOnDuplicateDefinition(ClsType, PreviousDef)) {
+  ClsType->mergeDuplicateDefinitionWithCommon(PreviousDef->getDefinition());
 } else {
   Diag(AtLoc, diag::err_duplicate_class_def) << ClsType->getDeclName();
   Diag(SkipBody.Previous->getLocation(), diag::note_previous_definition);
Index: clang/lib/AST/ODRHash.cpp
===
--- clang/lib/AST/ODRHash.cpp
+++ clang/lib/AST/ODRHash.cpp
@@ -517,6 +517,28 @@
   }
 }
 
+void ODRHash::AddObjCInterfaceDecl(const ObjCInterfaceDecl *IF) {
+  AddDecl(IF);
+
+  ObjCInterfaceDecl *SuperClass = IF->getSuperClass();
+  AddBoolean(SuperClass);
+  if (SuperClass)
+

[PATCH] D124189: [CUDA][HIP] Externalize kernels with internal linkage

2022-04-22 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked 7 inline comments as done.
yaxunl added inline comments.



Comment at: clang/test/CodeGenCUDA/device-var-linkage.cu:1-2
 // RUN: %clang_cc1 -no-opaque-pointers -triple nvptx -fcuda-is-device \
 // RUN:   -emit-llvm -o - -x hip %s \
 // RUN:   | FileCheck -check-prefixes=DEV,NORDC %s

tra wrote:
> This is odd -- the tests use `-x hip` and  `-triple nvptx`.
> 
> I think we need to change them  into HIP+amdgpu and CUDA +nvptx variants ans 
> we now have language-dependent behavior here and are interested in the 
> language/triple combinations that we do use in practice.
will change them to amdgcn and add CUDA variant when committing.



Comment at: clang/test/CodeGenCUDA/kernel-in-anon-ns.cu:3
 // RUN:   -aux-triple x86_64-unknown-linux-gnu -std=c++11 -fgpu-rdc \
 // RUN:   -emit-llvm -o - -x hip %s > %t.dev
 

tra wrote:
> We should have CUDA test variants here, too.
will add CUDA test when committing.



Comment at: clang/test/CodeGenCUDA/managed-var.cu:1
 // REQUIRES: x86-registered-target, amdgpu-registered-target
 

tra wrote:
> Tests above do not have REQUIRED. Is it needed here?
> 
No. I will remove it when committing.


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

https://reviews.llvm.org/D124189

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


[PATCH] D124286: [modules] Allow parsing a duplicate Obj-C interface if a previous one comes from a hidden [sub]module.

2022-04-22 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai created this revision.
vsapsai added reviewers: jansvoboda11, rsmith.
Herald added a subscriber: ributzka.
Herald added a project: All.
vsapsai requested review of this revision.
Herald added a project: clang.

Instead of emitting a redefinition error, check that definitions are
equivalent and allow such scenario. As an implementation detail we use
the previous decl to avoid disrupting existing canonical decl. And to
avoid multiple definitions in redeclaration chain we just drop the new
definition after checking equivalence.

This patch covers only duplicates encountered during parsing. We can
encounter duplicates also during deserialization but that's responsibility of
ASTReaderDecl.

rdar://82908223


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124286

Files:
  clang/include/clang/AST/DeclObjC.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/DeclObjC.cpp
  clang/lib/Parse/ParseObjc.cpp
  clang/lib/Sema/SemaDeclObjC.cpp
  clang/test/Modules/hidden-duplicates.m

Index: clang/test/Modules/hidden-duplicates.m
===
--- /dev/null
+++ clang/test/Modules/hidden-duplicates.m
@@ -0,0 +1,62 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: %clang_cc1 -emit-llvm -o %t/test.bc -I %t/include %t/test.m -verify \
+// RUN:-fmodules -fimplicit-module-maps -fmodules-cache-path=%t/modules.cache
+// RUN: %clang_cc1 -emit-llvm -o %t/test.bc -I %t/include %t/test.m -verify -DTEST_MAKE_HIDDEN_VISIBLE=1 \
+// RUN:-fmodules -fimplicit-module-maps -fmodules-cache-path=%t/modules.cache
+// RUN: %clang_cc1 -emit-llvm -o %t/test.bc -I %t/include %t/test.m -verify -x objective-c++ \
+// RUN:-fmodules -fimplicit-module-maps -fmodules-cache-path=%t/modules.cache
+// RUN: %clang_cc1 -emit-llvm -o %t/test.bc -I %t/include %t/test.m -verify -DTEST_MAKE_HIDDEN_VISIBLE=1 -x objective-c++ \
+// RUN:-fmodules -fimplicit-module-maps -fmodules-cache-path=%t/modules.cache
+
+// Test parsing duplicate Objective-C entities when a previous entity is defined
+// in a hidden [sub]module and cannot be used.
+//
+// Testing with header guards and includes on purpose as tracking imports in
+// modules is a separate issue.
+
+//--- include/textual.h
+#ifndef TEXTUAL_H
+#define TEXTUAL_H
+
+__attribute__((objc_root_class))
+@interface NSObject {
+@public
+  int ivarName;
+}
+@property (assign, nonatomic) int propName;
+@end
+
+@class ForwardDeclaredClassWithoutDefinition;
+
+#endif
+
+//--- include/empty.h
+//--- include/initially_hidden.h
+#include "textual.h"
+
+//--- include/module.modulemap
+module Piecewise {
+  module Empty {
+header "empty.h"
+  }
+  module InitiallyHidden {
+header "initially_hidden.h"
+export *
+  }
+}
+
+//--- test.m
+// Including empty.h loads the entire module Piecewise but keeps InitiallyHidden hidden.
+#include "empty.h"
+#include "textual.h"
+#ifdef TEST_MAKE_HIDDEN_VISIBLE
+#include "initially_hidden.h"
+#endif
+// expected-no-diagnostics
+
+void testAccessingInterface(NSObject *obj) {
+  obj->ivarName = obj.propName;
+}
+
+void testForwardDecl(ForwardDeclaredClassWithoutDefinition *obj);
Index: clang/lib/Sema/SemaDeclObjC.cpp
===
--- clang/lib/Sema/SemaDeclObjC.cpp
+++ clang/lib/Sema/SemaDeclObjC.cpp
@@ -978,7 +978,7 @@
 ArrayRef SuperTypeArgs, SourceRange SuperTypeArgsRange,
 Decl *const *ProtoRefs, unsigned NumProtoRefs,
 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
-const ParsedAttributesView ) {
+const ParsedAttributesView , SkipBodyInfo *SkipBody) {
   assert(ClassName && "Missing class identifier");
 
   // Check for another declaration kind with the same name.
@@ -1057,10 +1057,16 @@
   if (PrevIDecl) {
 // Class already seen. Was it a definition?
 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
-  Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
-<< PrevIDecl->getDeclName();
-  Diag(Def->getLocation(), diag::note_previous_definition);
-  IDecl->setInvalidDecl();
+  if (SkipBody && !hasVisibleDefinition(Def)) {
+SkipBody->CheckSameAsPrevious = true;
+SkipBody->New = IDecl;
+SkipBody->Previous = Def;
+  } else {
+Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
+  << PrevIDecl->getDeclName();
+Diag(Def->getLocation(), diag::note_previous_definition);
+IDecl->setInvalidDecl();
+  }
 }
   }
 
@@ -1075,7 +1081,9 @@
 
   // Start the definition of this class. If we're in a redefinition case, there
   // may already be a definition, so we'll end up adding to it.
-  if (!IDecl->hasDefinition())
+  if (SkipBody && SkipBody->CheckSameAsPrevious)
+IDecl->startDuplicateDefinitionForComparison();
+  else if (!IDecl->hasDefinition())
 IDecl->startDefinition();
 
   if (SuperName) {
Index: clang/lib/Parse/ParseObjc.cpp

[PATCH] D124285: [clang][NFC] In parts of Objective-C Sema use Obj-C-specific types instead of `Decl`.

2022-04-22 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai created this revision.
vsapsai added reviewers: jansvoboda11, Bigcheese.
Herald added a subscriber: ributzka.
Herald added a project: All.
vsapsai requested review of this revision.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124285

Files:
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseObjc.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclObjC.cpp

Index: clang/lib/Sema/SemaDeclObjC.cpp
===
--- clang/lib/Sema/SemaDeclObjC.cpp
+++ clang/lib/Sema/SemaDeclObjC.cpp
@@ -971,7 +971,7 @@
   return false;
 }
 
-Decl *Sema::ActOnStartClassInterface(
+ObjCInterfaceDecl *Sema::ActOnStartClassInterface(
 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
 IdentifierInfo *SuperName, SourceLocation SuperLoc,
@@ -1100,7 +1100,8 @@
   }
 
   CheckObjCDeclScope(IDecl);
-  return ActOnObjCContainerStartDefinition(IDecl);
+  ActOnObjCContainerStartDefinition(IDecl);
+  return IDecl;
 }
 
 /// ActOnTypedefedProtocols - this action finds protocol list as part of the
@@ -1208,7 +1209,7 @@
   return res;
 }
 
-Decl *Sema::ActOnStartProtocolInterface(
+ObjCProtocolDecl *Sema::ActOnStartProtocolInterface(
 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
 SourceLocation ProtocolLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs,
 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
@@ -1272,7 +1273,8 @@
   }
 
   CheckObjCDeclScope(PDecl);
-  return ActOnObjCContainerStartDefinition(PDecl);
+  ActOnObjCContainerStartDefinition(PDecl);
+  return PDecl;
 }
 
 static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
@@ -1799,7 +1801,7 @@
   return BuildDeclaratorGroup(DeclsInGroup);
 }
 
-Decl *Sema::ActOnStartCategoryInterface(
+ObjCCategoryDecl *Sema::ActOnStartCategoryInterface(
 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
@@ -1826,7 +1828,8 @@
 
 if (!IDecl)
   Diag(ClassLoc, diag::err_undef_interface) << ClassName;
-return ActOnObjCContainerStartDefinition(CDecl);
+ActOnObjCContainerStartDefinition(CDecl);
+return CDecl;
   }
 
   if (!CategoryName && IDecl->getImplementation()) {
@@ -1889,17 +1892,17 @@
   }
 
   CheckObjCDeclScope(CDecl);
-  return ActOnObjCContainerStartDefinition(CDecl);
+  ActOnObjCContainerStartDefinition(CDecl);
+  return CDecl;
 }
 
 /// ActOnStartCategoryImplementation - Perform semantic checks on the
 /// category implementation declaration and build an ObjCCategoryImplDecl
 /// object.
-Decl *Sema::ActOnStartCategoryImplementation(
-  SourceLocation AtCatImplLoc,
-  IdentifierInfo *ClassName, SourceLocation ClassLoc,
-  IdentifierInfo *CatName, SourceLocation CatLoc,
-  const ParsedAttributesView ) {
+ObjCCategoryImplDecl *Sema::ActOnStartCategoryImplementation(
+SourceLocation AtCatImplLoc, IdentifierInfo *ClassName,
+SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc,
+const ParsedAttributesView ) {
   ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
   ObjCCategoryDecl *CatIDecl = nullptr;
   if (IDecl && IDecl->hasDefinition()) {
@@ -1958,15 +1961,14 @@
   }
 
   CheckObjCDeclScope(CDecl);
-  return ActOnObjCContainerStartDefinition(CDecl);
+  ActOnObjCContainerStartDefinition(CDecl);
+  return CDecl;
 }
 
-Decl *Sema::ActOnStartClassImplementation(
-  SourceLocation AtClassImplLoc,
-  IdentifierInfo *ClassName, SourceLocation ClassLoc,
-  IdentifierInfo *SuperClassname,
-  SourceLocation SuperClassLoc,
-  const ParsedAttributesView ) {
+ObjCImplementationDecl *Sema::ActOnStartClassImplementation(
+SourceLocation AtClassImplLoc, IdentifierInfo *ClassName,
+SourceLocation ClassLoc, IdentifierInfo *SuperClassname,
+SourceLocation SuperClassLoc, const ParsedAttributesView ) {
   ObjCInterfaceDecl *IDecl = nullptr;
   // Check for another declaration kind with the same name.
   NamedDecl *PrevDecl
@@ -2063,8 +2065,10 @@
   ProcessDeclAttributeList(TUScope, IMPDecl, Attrs);
   AddPragmaAttributes(TUScope, IMPDecl);
 
-  if (CheckObjCDeclScope(IMPDecl))
-return ActOnObjCContainerStartDefinition(IMPDecl);
+  if (CheckObjCDeclScope(IMPDecl)) {
+ActOnObjCContainerStartDefinition(IMPDecl);
+return IMPDecl;
+  }
 
   // Check that there is no duplicate implementation of this class.
   if (IDecl->getImplementation()) {
@@ -2090,7 +2094,8 @@
   << IDecl->getSuperClass()->getDeclName();
   }
 
-  return ActOnObjCContainerStartDefinition(IMPDecl);
+  

[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 424543.
jhuber6 added a comment.

Making suggested changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

Files:
  clang/include/clang/Basic/Cuda.h
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/lib/Driver/ToolChains/HIPAMD.cpp
  clang/test/Driver/cuda-openmp-driver.cu
  clang/test/Driver/cuda-phases.cu

Index: clang/test/Driver/cuda-phases.cu
===
--- clang/test/Driver/cuda-phases.cu
+++ clang/test/Driver/cuda-phases.cu
@@ -217,3 +217,32 @@
 // DASM2-DAG: [[P8:[0-9]+]]: backend, {[[P7]]}, assembler, (device-[[T]], [[ARCH2]])
 // DASM2-DAG: [[P9:[0-9]+]]: offload, "device-[[T]] ([[TRIPLE]]:[[ARCH2]])" {[[P8]]}, assembler
 // DASM2-NOT: host
+
+//
+// Test the phases generated when using the new offloading driver.
+//
+// RUN: %clang -### -target powerpc64le-ibm-linux-gnu -ccc-print-phases -foffload-new-driver \
+// RUN: --offload-arch=sm_52 --offload-arch=sm_70 %s 2>&1 | FileCheck --check-prefix=NEW_DRIVER %s
+// NEW_DRIVER: 0: input, "[[INPUT:.*]]", cuda, (host-cuda)
+// NEW_DRIVER: 1: preprocessor, {0}, cuda-cpp-output, (host-cuda)
+// NEW_DRIVER: 2: compiler, {1}, ir, (host-cuda)
+// NEW_DRIVER: 3: input, "[[INPUT]]", cuda, (device-cuda, sm_52)
+// NEW_DRIVER: 4: preprocessor, {3}, cuda-cpp-output, (device-cuda, sm_52)
+// NEW_DRIVER: 5: compiler, {4}, ir, (device-cuda, sm_52)
+// NEW_DRIVER: 6: backend, {5}, assembler, (device-cuda, sm_52)
+// NEW_DRIVER: 7: assembler, {6}, object, (device-cuda, sm_52)
+// NEW_DRIVER: 8: offload, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {7}, object
+// NEW_DRIVER: 9: offload, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {6}, assembler
+// NEW_DRIVER: 10: linker, {8, 9}, cuda-fatbin, (device-cuda, sm_52)
+// NEW_DRIVER: 11: input, "[[INPUT]]", cuda, (device-cuda, sm_70)
+// NEW_DRIVER: 12: preprocessor, {11}, cuda-cpp-output, (device-cuda, sm_70)
+// NEW_DRIVER: 13: compiler, {12}, ir, (device-cuda, sm_70)
+// NEW_DRIVER: 14: backend, {13}, assembler, (device-cuda, sm_70)
+// NEW_DRIVER: 15: assembler, {14}, object, (device-cuda, sm_70)
+// NEW_DRIVER: 16: offload, "device-cuda (nvptx64-nvidia-cuda:sm_70)" {15}, object
+// NEW_DRIVER: 17: offload, "device-cuda (nvptx64-nvidia-cuda:sm_70)" {14}, assembler
+// NEW_DRIVER: 18: linker, {16, 17}, cuda-fatbin, (device-cuda, sm_70)
+// NEW_DRIVER: 19: offload, "host-cuda (powerpc64le-ibm-linux-gnu)" {2}, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {10}, "device-cuda (nvptx64-nvidia-cuda:sm_70)" {18}, ir
+// NEW_DRIVER: 20: backend, {19}, assembler, (host-cuda)
+// NEW_DRIVER: 21: assembler, {20}, object, (host-cuda)
+// NEW_DRIVER: 22: clang-linker-wrapper, {21}, image, (host-cuda)
Index: clang/test/Driver/cuda-openmp-driver.cu
===
--- /dev/null
+++ clang/test/Driver/cuda-openmp-driver.cu
@@ -0,0 +1,19 @@
+// REQUIRES: x86-registered-target
+// REQUIRES: nvptx-registered-target
+
+// RUN: %clang -### -target x86_64-linux-gnu -nocudalib -ccc-print-bindings -fgpu-rdc \
+// RUN:-foffload-new-driver --offload-arch=sm_35 --offload-arch=sm_70 %s 2>&1 \
+// RUN: | FileCheck -check-prefix BINDINGS %s
+
+// BINDINGS: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT:.+]]"], output: "[[PTX_SM_35:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX_SM_35]]"], output: "[[CUBIN_SM_35:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Linker", inputs: ["[[CUBIN_SM_35]]", "[[PTX_SM_35]]"], output: "[[FATBIN_SM_35:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]"], output: "[[PTX_SM_70:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX_SM_70:.+]]"], output: "[[CUBIN_SM_70:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Linker", inputs: ["[[CUBIN_SM_70]]", "[[PTX_SM_70:.+]]"], output: "[[FATBIN_SM_70:.+]]"
+// BINDINGS-NEXT: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT]]", "[[FATBIN_SM_35]]", "[[FATBIN_SM_70]]"], output: "[[HOST_OBJ:.+]]"
+// BINDINGS-NEXT: "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["[[HOST_OBJ]]"], output: "a.out"
+
+// RUN: %clang -### -nocudalib -foffload-new-driver %s 2>&1 | FileCheck -check-prefix RDC %s
+// RDC: clang{{.*}}"-cc1" "-triple" "nvptx64-nvidia-cuda"{{.*}}"-fgpu-rdc"
+// RDC: ptxas{{.*}}-c
Index: clang/lib/Driver/ToolChains/HIPAMD.cpp
===
--- clang/lib/Driver/ToolChains/HIPAMD.cpp
+++ clang/lib/Driver/ToolChains/HIPAMD.cpp
@@ -222,7 +222,8 @@
 CC1Args.push_back("-fcuda-approx-transcendentals");
 
   if (!DriverArgs.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
-  false))
+   

[clang] 2518d4f - [nfc][msan] Add D123875 into release notes

2022-04-22 Thread Vitaly Buka via cfe-commits

Author: Vitaly Buka
Date: 2022-04-22T11:14:28-07:00
New Revision: 2518d4f6d8548d558968749e6d728ccac98cc1c1

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

LOG: [nfc][msan] Add D123875 into release notes

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cb5cad717e347..8560ab921ef9f 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -173,6 +173,8 @@ Non-comprehensive list of changes in this release
   - Improve the dump format, dump both bitwidth(if its a bitfield) and field 
value.
   - Remove anonymous tag locations.
   - Beautify dump format, add indent for nested struct and struct members.
+- Previously disabled sanitizer options now enabled by default
+  - MSAN_OPTIONS=poison_in_dtor=1.
 
 New Compiler Flags
 --



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


[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6225
   if (IsCuda || IsHIP) {
-if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
+if (Args.hasArg(options::OPT_fno_gpu_rdc) && IsCudaDevice &&
+Args.hasArg(options::OPT_foffload_new_driver))

tra wrote:
> This has to be `Args.hasArg(options::OPT_fno_gpu_rdc) && 
> Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false) == false`
> 
> E.g. we don't want a warning if we have `-foffload-new-driver -fno-gpu-rdc 
> -fgpu-rdc`.
K, will do



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6228
+D.Diag(diag::warn_drv_no_rdc_new_driver) 
+<< "SampleUse with PGO options";
+if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false) ||

tra wrote:
> The warning does not take any parameters and this one looks wrong anyways.
Whoops, deleted that previously but had a little SNAFU with my commits and 
forgot to do it again.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6896
+  if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
+   false))
 CmdArgs.push_back("-fgpu-rdc");

tra wrote:
> I'm not sure why we're no longer checking for `OPT_foffload_new_driver` here. 
> Don't we want to have the same RDC mode on the host and device sides?
> I think we do as that affects the way we mangle some symbols and it has to be 
> consistent on both sides.
> 
> 
This is only checked with `CudaDeviceInput` which we don't use with the new 
driver.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

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


[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-22 Thread Artem Belevich via Phabricator via cfe-commits
tra added a subscriber: rnk.
tra added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6225
   if (IsCuda || IsHIP) {
-if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
+if (Args.hasArg(options::OPT_fno_gpu_rdc) && IsCudaDevice &&
+Args.hasArg(options::OPT_foffload_new_driver))

This has to be `Args.hasArg(options::OPT_fno_gpu_rdc) && 
Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false) == false`

E.g. we don't want a warning if we have `-foffload-new-driver -fno-gpu-rdc 
-fgpu-rdc`.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6228
+D.Diag(diag::warn_drv_no_rdc_new_driver) 
+<< "SampleUse with PGO options";
+if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false) ||

The warning does not take any parameters and this one looks wrong anyways.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6896
+  if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
+   false))
 CmdArgs.push_back("-fgpu-rdc");

I'm not sure why we're no longer checking for `OPT_foffload_new_driver` here. 
Don't we want to have the same RDC mode on the host and device sides?
I think we do as that affects the way we mangle some symbols and it has to be 
consistent on both sides.





Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6223-6224
   if (IsCuda || IsHIP) {
-if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
+if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false) ||
+Args.hasArg(options::OPT_foffload_new_driver))
   CmdArgs.push_back("-fgpu-rdc");

jhuber6 wrote:
> tra wrote:
> > tra wrote:
> > > jhuber6 wrote:
> > > > tra wrote:
> > > > > If user specifies both `-fno-gpu-rdc` and `-foffload-new-driver` we 
> > > > > would still enable RDC compilation.
> > > > > We may want to at least issue a warning. 
> > > > > 
> > > > > Considering that  we have multiple places where we may check for 
> > > > > `-f[no]gpu-rdc` we should make sure we don't get different ideas 
> > > > > whether RDC has been enabled.
> > > > > I think it may make sense to provide a common way to figure it out. 
> > > > > Either via a helper function that would process CLI arguments or 
> > > > > calculate it once and save it somewhere.
> > > > I haven't quite finalized how to handle this. The new driver should be 
> > > > compatible with a non-RDC build since we simply wouldn't embed the 
> > > > device image or create offloading entries. It's a little bit more 
> > > > difficult here since the new method is opt-in so it requires a flag. We 
> > > > should definitely emit a warning if both are enabled (I'm assuming 
> > > > there's one for passing both `fgpu-rdc` and `fno-gpu-rdc`). I'll add 
> > > > one in.
> > > > 
> > > > Also we could consider the new driver *the* RDC in the future which 
> > > > would be the easiest. The problem is if we want to support CUDA's 
> > > > method of RDC considering how other build systems seem to expect it. I 
> > > > could see us embedding the fatbinary in the object file, even if 
> > > > unused, just so that cuobjdump works. However we couldn't support the 
> > > > generation of `__cudaRegisterFatBinary_nv` functions because then 
> > > > those would cause linker errors. WDYT?
> > > > I'm assuming there's one for passing both fgpu-rdc and fno-gpu-rdc
> > > 
> > > This is not a valid assumption. The whole idea behind `-fno-something` is 
> > > that the options can be overridden. E.g. if the build specifies a 
> > > standard set of compiler options, but we need to override some of them 
> > > when building a particular file. We can only do so by appending to the 
> > > standard options. Potentially we may end up having those options 
> > > overridden again. While it's not very common, it's certainly possible. 
> > > It's also possible to start with '-fno-gpu-rdc' and then override it with 
> > > `-fgpu-rdc`.
> > > 
> > > In this case, we care about the final state of RDC specified by 
> > > -f*gpu-rdc options, not by the fact that `-fno-gpu-rdc` is present. 
> > > `Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)` 
> > > does exactly that -- gives you the final state. If it returns false, but 
> > > we have `-foffload-new-driver`, then we need a warning as these options 
> > > are contradictory.
> > > 
> > > The new driver should be compatible with a non-RDC build 
> > 
> > In that case, we don't need a warning, but we do need a test verifying this 
> > behavior.
> > 
> > > Also we could consider the new driver *the* RDC in the future which would 
> > > be the easiest. 
> > 
> > SGTM. I do not know how it all will work out in the end. Your proposed 
> > model makes a lot of sense, and I'm guardedly optimistic about it.
> > Eventually we would 

[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6223-6224
   if (IsCuda || IsHIP) {
-if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
+if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false) ||
+Args.hasArg(options::OPT_foffload_new_driver))
   CmdArgs.push_back("-fgpu-rdc");

tra wrote:
> tra wrote:
> > jhuber6 wrote:
> > > tra wrote:
> > > > If user specifies both `-fno-gpu-rdc` and `-foffload-new-driver` we 
> > > > would still enable RDC compilation.
> > > > We may want to at least issue a warning. 
> > > > 
> > > > Considering that  we have multiple places where we may check for 
> > > > `-f[no]gpu-rdc` we should make sure we don't get different ideas 
> > > > whether RDC has been enabled.
> > > > I think it may make sense to provide a common way to figure it out. 
> > > > Either via a helper function that would process CLI arguments or 
> > > > calculate it once and save it somewhere.
> > > I haven't quite finalized how to handle this. The new driver should be 
> > > compatible with a non-RDC build since we simply wouldn't embed the device 
> > > image or create offloading entries. It's a little bit more difficult here 
> > > since the new method is opt-in so it requires a flag. We should 
> > > definitely emit a warning if both are enabled (I'm assuming there's one 
> > > for passing both `fgpu-rdc` and `fno-gpu-rdc`). I'll add one in.
> > > 
> > > Also we could consider the new driver *the* RDC in the future which would 
> > > be the easiest. The problem is if we want to support CUDA's method of RDC 
> > > considering how other build systems seem to expect it. I could see us 
> > > embedding the fatbinary in the object file, even if unused, just so that 
> > > cuobjdump works. However we couldn't support the generation of 
> > > `__cudaRegisterFatBinary_nv` functions because then those would cause 
> > > linker errors. WDYT?
> > > I'm assuming there's one for passing both fgpu-rdc and fno-gpu-rdc
> > 
> > This is not a valid assumption. The whole idea behind `-fno-something` is 
> > that the options can be overridden. E.g. if the build specifies a standard 
> > set of compiler options, but we need to override some of them when building 
> > a particular file. We can only do so by appending to the standard options. 
> > Potentially we may end up having those options overridden again. While it's 
> > not very common, it's certainly possible. It's also possible to start with 
> > '-fno-gpu-rdc' and then override it with `-fgpu-rdc`.
> > 
> > In this case, we care about the final state of RDC specified by -f*gpu-rdc 
> > options, not by the fact that `-fno-gpu-rdc` is present. 
> > `Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)` does 
> > exactly that -- gives you the final state. If it returns false, but we have 
> > `-foffload-new-driver`, then we need a warning as these options are 
> > contradictory.
> > 
> > The new driver should be compatible with a non-RDC build 
> 
> In that case, we don't need a warning, but we do need a test verifying this 
> behavior.
> 
> > Also we could consider the new driver *the* RDC in the future which would 
> > be the easiest. 
> 
> SGTM. I do not know how it all will work out in the end. Your proposed model 
> makes a lot of sense, and I'm guardedly optimistic about it.
> Eventually we would deprecate RDC options, but we still need to work sensibly 
> when user specifies a mix of these options. 
> 
> 
> In that case, we don't need a warning, but we do need a test verifying this 
> behavior.
> 
It's possible but I don't have the logic here to do it, figured we can cross 
that bridge later.

> SGTM. I do not know how it all will work out in the end. Your proposed model 
> makes a lot of sense, and I'm guardedly optimistic about it.
>
So the only downsides I know of, is that we don't currently replicate CUDA's 
magic to JIT RDC code (We can do this with LTO anyway), and that registering 
offload entries relies on the linker defining `__start / __stop` variables, 
which I don't know if linkers on Windows / MacOS provide. I'd be really 
interested if someone on the LLD team knew the answer to that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

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


[PATCH] D124189: [CUDA][HIP] Externalize kernels with internal linkage

2022-04-22 Thread Artem Belevich via Phabricator via cfe-commits
tra accepted this revision.
tra added a comment.
This revision is now accepted and ready to land.

LGTM overal, with few test nits.




Comment at: clang/lib/AST/ASTContext.cpp:12300
+ (D->hasAttr() &&
+  GetGVALinkageForFunction(cast(D),
+   /*IgnoreCUDAGlobalAttr=*/true) ==

yaxunl wrote:
> tra wrote:
> > yaxunl wrote:
> > > tra wrote:
> > > > yaxunl wrote:
> > > > > tra wrote:
> > > > > > Perhaps we don't need to change the public AST API and plumb 
> > > > > > `IgnoreCUDAGlobalAttr` through.
> > > > > > We cold create CUDA-aware static version of 
> > > > > > `GetGVALinkageForCudaKernel` instead, which would call 
> > > > > > `adjustGVALinkageForExternalDefinitionKind(..., 
> > > > > > adjustGVALinkageForAttributes(IgnoreCUDAGlobalAttr=true))`.
> > > > > We could have a static function but it would be 
> > > > > GetGVALinkageForCUDAKernelWithoutGlobalAttr since we need to know the 
> > > > > linkage of the kernel assuming it has no `__global__` attribute.
> > > > > 
> > > > > If you think it is OK I can make the change.
> > > > No point making public what's of no use to anybody other than this 
> > > > particular instance.
> > > > 
> > > > To think of it, we don't even need a function and could just do 
> > > > ```
> > > >   if (D->hasAttr() ) {
> > > > bool OriginalKernelLinkage = 
> > > > adjustGVALinkageForExternalDefinitionKind(..., 
> > > > adjustGVALinkageForAttributes(IgnoreCUDAGlobalAttr=true));
> > > > return OriginalKernelLinkage == GVA_Internal;
> > > >   }
> > > >   return (IsStaticVar &&)
> > > > ```
> > > > 
> > > > 
> > > One disadvantage of this approach is that it duplicates the code in 
> > > GetGVALinkageForFunction. In the future, if GetGVALinkageForFunction 
> > > changes, the same change needs to be applied to the duplicated code, 
> > > which is error-prone.
> > Good point.  Looking at the code closer, it appears that what we're 
> > interested in is whether the kernel was internal and *became* externally 
> > visible due to it being a kernel. 
> > 
> > Right now we're checking if the function would normally be `GVA_Internal` 
> > (shouldn't we have considered GVA_DiscardableODR, too, BTW?)
> > This is a somewhat indirect way of figuring out what we really need.
> > 
> > The code that determines what we want is essentially this code in 
> > adjustGVALinkageForAttributes that we're trying to enable/disable with 
> > `ConsiderCudaGlobalAttr`. 
> > 
> > It can be easily extracted into a static function, which could then be used 
> > from both `adjustGVALinkageForAttributes`, (which would no longer need 
> > `ConsiderCudaGlobalAttr`) and from here. 
> > 
> > ```
> > bool isInternalKernel(ASTContext *Context, Decl *D) {
> >   L=basicGVALinkageForFunction(Context, D);
> >   return (D->hasAttr() &&
> >   (L == GVA_DiscardableODR || L == GVA_Internal));
> > }
> > ```
> > 
> > This would both avoid logic duplication and would better match our intent.
> > 
> > Does it make sense? Or did I miss something else?
> GVA_DiscardableODR  usually maps to linkonce_odr linkage in LLVM IR. It 
> follows the ODR, therefore we should not make them unique.
> 
> If we use isInternalKernel in adjustGVALinkageForAttributes, there will be 
> two calls of basicGVALinkageForFunction when GetGVALinkageForFunction is 
> called, which seems inefficient. I think we can keep GetGVALinkageForFunction 
> as it was, and use basicGVALinkageForFunction directly in mayExternalize.
SGTM.



Comment at: clang/test/CodeGenCUDA/device-var-linkage.cu:1-2
 // RUN: %clang_cc1 -no-opaque-pointers -triple nvptx -fcuda-is-device \
 // RUN:   -emit-llvm -o - -x hip %s \
 // RUN:   | FileCheck -check-prefixes=DEV,NORDC %s

This is odd -- the tests use `-x hip` and  `-triple nvptx`.

I think we need to change them  into HIP+amdgpu and CUDA +nvptx variants ans we 
now have language-dependent behavior here and are interested in the 
language/triple combinations that we do use in practice.



Comment at: clang/test/CodeGenCUDA/kernel-in-anon-ns.cu:3
 // RUN:   -aux-triple x86_64-unknown-linux-gnu -std=c++11 -fgpu-rdc \
 // RUN:   -emit-llvm -o - -x hip %s > %t.dev
 

We should have CUDA test variants here, too.



Comment at: clang/test/CodeGenCUDA/managed-var.cu:1
 // REQUIRES: x86-registered-target, amdgpu-registered-target
 

Tests above do not have REQUIRED. Is it needed here?



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

https://reviews.llvm.org/D124189

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


[PATCH] D124282: [git-clang-format] Add some examples to the help text

2022-04-22 Thread Nico Weber via Phabricator via cfe-commits
thakis created this revision.
thakis added reviewers: MyDeveloperDay, curdeius.
Herald added a project: All.
thakis requested review of this revision.

https://reviews.llvm.org/D124282

Files:
  clang/tools/clang-format/git-clang-format


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -40,6 +40,16 @@
 between the working directory and , which defaults to HEAD.  Changes 
are
 only applied to the working directory, or in the stage/index.
 
+Examples:
+  To format staged changes, i.e everything that's been `git add`ed:
+git clang-format
+
+  To also format everything touched in the most recent commit:
+git clang-format HEAD~1
+
+  If you're on a branch off main, to format everything touched on your branch:
+git clang-format main
+
 If two commits are given (requires --diff), run clang-format on all lines in 
the
 second  that differ from the first .
 


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -40,6 +40,16 @@
 between the working directory and , which defaults to HEAD.  Changes are
 only applied to the working directory, or in the stage/index.
 
+Examples:
+  To format staged changes, i.e everything that's been `git add`ed:
+git clang-format
+
+  To also format everything touched in the most recent commit:
+git clang-format HEAD~1
+
+  If you're on a branch off main, to format everything touched on your branch:
+git clang-format main
+
 If two commits are given (requires --diff), run clang-format on all lines in the
 second  that differ from the first .
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 424537.
jhuber6 added a comment.

Adding warning for using both -fno-gpu-rdc and -foffload-new-driver. I think 
this is a good warning to have for now while this is being worked in as opt-in. 
Once this has matured I plan on adding the necessary logic to handle RDC and 
non-RDC builds correctly with this. But for the purposes of this patch just 
warning is fine.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

Files:
  clang/include/clang/Basic/Cuda.h
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/lib/Driver/ToolChains/HIPAMD.cpp
  clang/test/Driver/cuda-openmp-driver.cu
  clang/test/Driver/cuda-phases.cu

Index: clang/test/Driver/cuda-phases.cu
===
--- clang/test/Driver/cuda-phases.cu
+++ clang/test/Driver/cuda-phases.cu
@@ -217,3 +217,32 @@
 // DASM2-DAG: [[P8:[0-9]+]]: backend, {[[P7]]}, assembler, (device-[[T]], [[ARCH2]])
 // DASM2-DAG: [[P9:[0-9]+]]: offload, "device-[[T]] ([[TRIPLE]]:[[ARCH2]])" {[[P8]]}, assembler
 // DASM2-NOT: host
+
+//
+// Test the phases generated when using the new offloading driver.
+//
+// RUN: %clang -### -target powerpc64le-ibm-linux-gnu -ccc-print-phases -foffload-new-driver \
+// RUN: --offload-arch=sm_52 --offload-arch=sm_70 %s 2>&1 | FileCheck --check-prefix=NEW_DRIVER %s
+// NEW_DRIVER: 0: input, "[[INPUT:.*]]", cuda, (host-cuda)
+// NEW_DRIVER: 1: preprocessor, {0}, cuda-cpp-output, (host-cuda)
+// NEW_DRIVER: 2: compiler, {1}, ir, (host-cuda)
+// NEW_DRIVER: 3: input, "[[INPUT]]", cuda, (device-cuda, sm_52)
+// NEW_DRIVER: 4: preprocessor, {3}, cuda-cpp-output, (device-cuda, sm_52)
+// NEW_DRIVER: 5: compiler, {4}, ir, (device-cuda, sm_52)
+// NEW_DRIVER: 6: backend, {5}, assembler, (device-cuda, sm_52)
+// NEW_DRIVER: 7: assembler, {6}, object, (device-cuda, sm_52)
+// NEW_DRIVER: 8: offload, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {7}, object
+// NEW_DRIVER: 9: offload, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {6}, assembler
+// NEW_DRIVER: 10: linker, {8, 9}, cuda-fatbin, (device-cuda, sm_52)
+// NEW_DRIVER: 11: input, "[[INPUT]]", cuda, (device-cuda, sm_70)
+// NEW_DRIVER: 12: preprocessor, {11}, cuda-cpp-output, (device-cuda, sm_70)
+// NEW_DRIVER: 13: compiler, {12}, ir, (device-cuda, sm_70)
+// NEW_DRIVER: 14: backend, {13}, assembler, (device-cuda, sm_70)
+// NEW_DRIVER: 15: assembler, {14}, object, (device-cuda, sm_70)
+// NEW_DRIVER: 16: offload, "device-cuda (nvptx64-nvidia-cuda:sm_70)" {15}, object
+// NEW_DRIVER: 17: offload, "device-cuda (nvptx64-nvidia-cuda:sm_70)" {14}, assembler
+// NEW_DRIVER: 18: linker, {16, 17}, cuda-fatbin, (device-cuda, sm_70)
+// NEW_DRIVER: 19: offload, "host-cuda (powerpc64le-ibm-linux-gnu)" {2}, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {10}, "device-cuda (nvptx64-nvidia-cuda:sm_70)" {18}, ir
+// NEW_DRIVER: 20: backend, {19}, assembler, (host-cuda)
+// NEW_DRIVER: 21: assembler, {20}, object, (host-cuda)
+// NEW_DRIVER: 22: clang-linker-wrapper, {21}, image, (host-cuda)
Index: clang/test/Driver/cuda-openmp-driver.cu
===
--- /dev/null
+++ clang/test/Driver/cuda-openmp-driver.cu
@@ -0,0 +1,19 @@
+// REQUIRES: x86-registered-target
+// REQUIRES: nvptx-registered-target
+
+// RUN: %clang -### -target x86_64-linux-gnu -nocudalib -ccc-print-bindings -fgpu-rdc \
+// RUN:-foffload-new-driver --offload-arch=sm_35 --offload-arch=sm_70 %s 2>&1 \
+// RUN: | FileCheck -check-prefix BINDINGS %s
+
+// BINDINGS: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT:.+]]"], output: "[[PTX_SM_35:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX_SM_35]]"], output: "[[CUBIN_SM_35:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Linker", inputs: ["[[CUBIN_SM_35]]", "[[PTX_SM_35]]"], output: "[[FATBIN_SM_35:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]"], output: "[[PTX_SM_70:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX_SM_70:.+]]"], output: "[[CUBIN_SM_70:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Linker", inputs: ["[[CUBIN_SM_70]]", "[[PTX_SM_70:.+]]"], output: "[[FATBIN_SM_70:.+]]"
+// BINDINGS-NEXT: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT]]", "[[FATBIN_SM_35]]", "[[FATBIN_SM_70]]"], output: "[[HOST_OBJ:.+]]"
+// BINDINGS-NEXT: "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["[[HOST_OBJ]]"], output: "a.out"
+
+// RUN: %clang -### -nocudalib -foffload-new-driver %s 2>&1 | FileCheck -check-prefix RDC %s
+// RDC: clang{{.*}}"-cc1" "-triple" "nvptx64-nvidia-cuda"{{.*}}"-fgpu-rdc"
+// RDC: ptxas{{.*}}-c
Index: clang/lib/Driver/ToolChains/HIPAMD.cpp

[PATCH] D123812: [CUDA] Add wrapper code generation for registering CUDA images

2022-04-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 424536.
jhuber6 added a comment.

Applied changes to wrong commit, whoops.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123812

Files:
  clang/test/Driver/linker-wrapper-image.c
  clang/test/Driver/linker-wrapper.c
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  clang/tools/clang-linker-wrapper/OffloadWrapper.cpp

Index: clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
+++ clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
@@ -20,6 +20,8 @@
 using namespace llvm;
 
 namespace {
+/// Magic number that begins the section containing the CUDA fatbinary.
+constexpr unsigned CudaFatMagic = 0x466243b1;
 
 IntegerType *getSizeTTy(Module ) {
   LLVMContext  = M.getContext();
@@ -255,6 +257,265 @@
   appendToGlobalDtors(M, Func, /*Priority*/ 1);
 }
 
+// struct fatbin_wrapper {
+//  int32_t magic;
+//  int32_t version;
+//  void *image;
+//  void *reserved;
+//};
+StructType *getFatbinWrapperTy(Module ) {
+  LLVMContext  = M.getContext();
+  StructType *FatbinTy = StructType::getTypeByName(C, "fatbin_wrapper");
+  if (!FatbinTy)
+FatbinTy = StructType::create("fatbin_wrapper", Type::getInt32Ty(C),
+  Type::getInt32Ty(C), Type::getInt8PtrTy(C),
+  Type::getInt8PtrTy(C));
+  return FatbinTy;
+}
+
+/// Embed the image \p Image into the module \p M so it can be found by the
+/// runtime.
+GlobalVariable *createFatbinDesc(Module , ArrayRef Image) {
+  LLVMContext  = M.getContext();
+  llvm::Type *Int8PtrTy = Type::getInt8PtrTy(C);
+  llvm::Triple Triple = llvm::Triple(M.getTargetTriple());
+
+  // Create the global string containing the fatbinary.
+  StringRef FatbinConstantSection =
+  Triple.isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin";
+  auto *Data = ConstantDataArray::get(C, Image);
+  auto *Fatbin = new GlobalVariable(M, Data->getType(), /*isConstant*/ true,
+GlobalVariable::InternalLinkage, Data,
+".fatbin_image");
+  Fatbin->setSection(FatbinConstantSection);
+
+  // Create the fatbinary wrapper
+  StringRef FatbinWrapperSection =
+  Triple.isMacOSX() ? "__NV_CUDA,__fatbin" : ".nvFatBinSegment";
+  Constant *FatbinWrapper[] = {
+  ConstantInt::get(Type::getInt32Ty(C), CudaFatMagic),
+  ConstantInt::get(Type::getInt32Ty(C), 1),
+  ConstantExpr::getPointerBitCastOrAddrSpaceCast(Fatbin, Int8PtrTy),
+  ConstantPointerNull::get(Type::getInt8PtrTy(C))};
+
+  Constant *FatbinInitializer =
+  ConstantStruct::get(getFatbinWrapperTy(M), FatbinWrapper);
+
+  auto *FatbinDesc =
+  new GlobalVariable(M, getFatbinWrapperTy(M),
+ /*isConstant*/ true, GlobalValue::InternalLinkage,
+ FatbinInitializer, ".fatbin_wrapper");
+  FatbinDesc->setSection(FatbinWrapperSection);
+  FatbinDesc->setAlignment(Align(8));
+
+  // We create a dummy entry to ensure the linker will define the begin / end
+  // symbols. The CUDA runtime should ignore the null address if we attempt to
+  // register it.
+  auto *DummyInit =
+  ConstantAggregateZero::get(ArrayType::get(getEntryTy(M), 0u));
+  auto *DummyEntry = new GlobalVariable(
+  M, DummyInit->getType(), true, GlobalVariable::ExternalLinkage, DummyInit,
+  "__dummy.cuda_offloading.entry");
+  DummyEntry->setSection("cuda_offloading_entries");
+  DummyEntry->setVisibility(GlobalValue::HiddenVisibility);
+
+  return FatbinDesc;
+}
+
+/// Create the register globals function. We will iterate all of the offloading
+/// entries stored at the begin / end symbols and register them according to
+/// their type. This creates the following function in IR:
+///
+/// extern struct __tgt_offload_entry __start_cuda_offloading_entries;
+/// extern struct __tgt_offload_entry __stop_cuda_offloading_entries;
+///
+/// extern void __cudaRegisterFunction(void **, void *, void *, void *, int,
+///void *, void *, void *, void *, int *);
+/// extern void __cudaRegisterVar(void **, void *, void *, void *, int32_t,
+///   int64_t, int32_t, int32_t);
+///
+/// void __cudaRegisterTest(void **fatbinHandle) {
+///   for (struct __tgt_offload_entry *entry = &__start_cuda_offloading_entries;
+///entry != &__stop_cuda_offloading_entries; ++entry) {
+/// if (!entry->size)
+///   __cudaRegisterFunction(fatbinHandle, entry->addr, entry->name,
+///  entry->name, -1, 0, 0, 0, 0, 0);
+/// else
+///   __cudaRegisterVar(fatbinHandle, entry->addr, entry->name, entry->name,
+/// 0, entry->size, 0, 0);
+///   }
+/// }
+///
+/// TODO: This only registers functions are variables. Additional support is

[PATCH] D123812: [CUDA] Add wrapper code generation for registering CUDA images

2022-04-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 424534.
jhuber6 added a comment.
Herald added a subscriber: MaskRay.

Adding warning for using both `-fno-gpu-rdc` and `-foffload-new-driver`. I 
think this is a good warning to have for now while this is being worked in as 
opt-in. Once this has matured I plan on adding the necessary logic to handle 
RDC and non-RDC builds correctly with this. But for the purposes of this patch 
just warning is fine.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123812

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/linker-wrapper-image.c
  clang/test/Driver/linker-wrapper.c
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  clang/tools/clang-linker-wrapper/OffloadWrapper.cpp

Index: clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
+++ clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
@@ -20,6 +20,8 @@
 using namespace llvm;
 
 namespace {
+/// Magic number that begins the section containing the CUDA fatbinary.
+constexpr unsigned CudaFatMagic = 0x466243b1;
 
 IntegerType *getSizeTTy(Module ) {
   LLVMContext  = M.getContext();
@@ -255,6 +257,265 @@
   appendToGlobalDtors(M, Func, /*Priority*/ 1);
 }
 
+// struct fatbin_wrapper {
+//  int32_t magic;
+//  int32_t version;
+//  void *image;
+//  void *reserved;
+//};
+StructType *getFatbinWrapperTy(Module ) {
+  LLVMContext  = M.getContext();
+  StructType *FatbinTy = StructType::getTypeByName(C, "fatbin_wrapper");
+  if (!FatbinTy)
+FatbinTy = StructType::create("fatbin_wrapper", Type::getInt32Ty(C),
+  Type::getInt32Ty(C), Type::getInt8PtrTy(C),
+  Type::getInt8PtrTy(C));
+  return FatbinTy;
+}
+
+/// Embed the image \p Image into the module \p M so it can be found by the
+/// runtime.
+GlobalVariable *createFatbinDesc(Module , ArrayRef Image) {
+  LLVMContext  = M.getContext();
+  llvm::Type *Int8PtrTy = Type::getInt8PtrTy(C);
+  llvm::Triple Triple = llvm::Triple(M.getTargetTriple());
+
+  // Create the global string containing the fatbinary.
+  StringRef FatbinConstantSection =
+  Triple.isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin";
+  auto *Data = ConstantDataArray::get(C, Image);
+  auto *Fatbin = new GlobalVariable(M, Data->getType(), /*isConstant*/ true,
+GlobalVariable::InternalLinkage, Data,
+".fatbin_image");
+  Fatbin->setSection(FatbinConstantSection);
+
+  // Create the fatbinary wrapper
+  StringRef FatbinWrapperSection =
+  Triple.isMacOSX() ? "__NV_CUDA,__fatbin" : ".nvFatBinSegment";
+  Constant *FatbinWrapper[] = {
+  ConstantInt::get(Type::getInt32Ty(C), CudaFatMagic),
+  ConstantInt::get(Type::getInt32Ty(C), 1),
+  ConstantExpr::getPointerBitCastOrAddrSpaceCast(Fatbin, Int8PtrTy),
+  ConstantPointerNull::get(Type::getInt8PtrTy(C))};
+
+  Constant *FatbinInitializer =
+  ConstantStruct::get(getFatbinWrapperTy(M), FatbinWrapper);
+
+  auto *FatbinDesc =
+  new GlobalVariable(M, getFatbinWrapperTy(M),
+ /*isConstant*/ true, GlobalValue::InternalLinkage,
+ FatbinInitializer, ".fatbin_wrapper");
+  FatbinDesc->setSection(FatbinWrapperSection);
+  FatbinDesc->setAlignment(Align(8));
+
+  // We create a dummy entry to ensure the linker will define the begin / end
+  // symbols. The CUDA runtime should ignore the null address if we attempt to
+  // register it.
+  auto *DummyInit =
+  ConstantAggregateZero::get(ArrayType::get(getEntryTy(M), 0u));
+  auto *DummyEntry = new GlobalVariable(
+  M, DummyInit->getType(), true, GlobalVariable::ExternalLinkage, DummyInit,
+  "__dummy.cuda_offloading.entry");
+  DummyEntry->setSection("cuda_offloading_entries");
+  DummyEntry->setVisibility(GlobalValue::HiddenVisibility);
+
+  return FatbinDesc;
+}
+
+/// Create the register globals function. We will iterate all of the offloading
+/// entries stored at the begin / end symbols and register them according to
+/// their type. This creates the following function in IR:
+///
+/// extern struct __tgt_offload_entry __start_cuda_offloading_entries;
+/// extern struct __tgt_offload_entry __stop_cuda_offloading_entries;
+///
+/// extern void __cudaRegisterFunction(void **, void *, void *, void *, int,
+///void *, void *, void *, void *, int *);
+/// extern void __cudaRegisterVar(void **, void *, void *, void *, int32_t,
+///   int64_t, int32_t, int32_t);
+///
+/// void __cudaRegisterTest(void **fatbinHandle) {
+///   for (struct __tgt_offload_entry *entry = &__start_cuda_offloading_entries;
+///entry != &__stop_cuda_offloading_entries; 

[PATCH] D124280: [git-clang-format] Change run line from python to python3

2022-04-22 Thread Nico Weber via Phabricator via cfe-commits
thakis created this revision.
thakis added a reviewer: MyDeveloperDay.
Herald added a project: All.
thakis requested review of this revision.

Several systems no longer ship `python`.


https://reviews.llvm.org/D124280

Files:
  clang/tools/clang-format/git-clang-format


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #
 #===- git-clang-format - ClangFormat Git Integration -*- python 
-*--===#
 #


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #
 #===- git-clang-format - ClangFormat Git Integration -*- python -*--===#
 #
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-22 Thread Artem Belevich via Phabricator via cfe-commits
tra added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6223-6224
   if (IsCuda || IsHIP) {
-if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
+if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false) ||
+Args.hasArg(options::OPT_foffload_new_driver))
   CmdArgs.push_back("-fgpu-rdc");

tra wrote:
> jhuber6 wrote:
> > tra wrote:
> > > If user specifies both `-fno-gpu-rdc` and `-foffload-new-driver` we would 
> > > still enable RDC compilation.
> > > We may want to at least issue a warning. 
> > > 
> > > Considering that  we have multiple places where we may check for 
> > > `-f[no]gpu-rdc` we should make sure we don't get different ideas whether 
> > > RDC has been enabled.
> > > I think it may make sense to provide a common way to figure it out. 
> > > Either via a helper function that would process CLI arguments or 
> > > calculate it once and save it somewhere.
> > I haven't quite finalized how to handle this. The new driver should be 
> > compatible with a non-RDC build since we simply wouldn't embed the device 
> > image or create offloading entries. It's a little bit more difficult here 
> > since the new method is opt-in so it requires a flag. We should definitely 
> > emit a warning if both are enabled (I'm assuming there's one for passing 
> > both `fgpu-rdc` and `fno-gpu-rdc`). I'll add one in.
> > 
> > Also we could consider the new driver *the* RDC in the future which would 
> > be the easiest. The problem is if we want to support CUDA's method of RDC 
> > considering how other build systems seem to expect it. I could see us 
> > embedding the fatbinary in the object file, even if unused, just so that 
> > cuobjdump works. However we couldn't support the generation of 
> > `__cudaRegisterFatBinary_nv` functions because then those would cause 
> > linker errors. WDYT?
> > I'm assuming there's one for passing both fgpu-rdc and fno-gpu-rdc
> 
> This is not a valid assumption. The whole idea behind `-fno-something` is 
> that the options can be overridden. E.g. if the build specifies a standard 
> set of compiler options, but we need to override some of them when building a 
> particular file. We can only do so by appending to the standard options. 
> Potentially we may end up having those options overridden again. While it's 
> not very common, it's certainly possible. It's also possible to start with 
> '-fno-gpu-rdc' and then override it with `-fgpu-rdc`.
> 
> In this case, we care about the final state of RDC specified by -f*gpu-rdc 
> options, not by the fact that `-fno-gpu-rdc` is present. 
> `Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)` does 
> exactly that -- gives you the final state. If it returns false, but we have 
> `-foffload-new-driver`, then we need a warning as these options are 
> contradictory.
> 
> The new driver should be compatible with a non-RDC build 

In that case, we don't need a warning, but we do need a test verifying this 
behavior.

> Also we could consider the new driver *the* RDC in the future which would be 
> the easiest. 

SGTM. I do not know how it all will work out in the end. Your proposed model 
makes a lot of sense, and I'm guardedly optimistic about it.
Eventually we would deprecate RDC options, but we still need to work sensibly 
when user specifies a mix of these options. 




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

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


[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-22 Thread Artem Belevich via Phabricator via cfe-commits
tra added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6223-6224
   if (IsCuda || IsHIP) {
-if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
+if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false) ||
+Args.hasArg(options::OPT_foffload_new_driver))
   CmdArgs.push_back("-fgpu-rdc");

jhuber6 wrote:
> tra wrote:
> > If user specifies both `-fno-gpu-rdc` and `-foffload-new-driver` we would 
> > still enable RDC compilation.
> > We may want to at least issue a warning. 
> > 
> > Considering that  we have multiple places where we may check for 
> > `-f[no]gpu-rdc` we should make sure we don't get different ideas whether 
> > RDC has been enabled.
> > I think it may make sense to provide a common way to figure it out. Either 
> > via a helper function that would process CLI arguments or calculate it once 
> > and save it somewhere.
> I haven't quite finalized how to handle this. The new driver should be 
> compatible with a non-RDC build since we simply wouldn't embed the device 
> image or create offloading entries. It's a little bit more difficult here 
> since the new method is opt-in so it requires a flag. We should definitely 
> emit a warning if both are enabled (I'm assuming there's one for passing both 
> `fgpu-rdc` and `fno-gpu-rdc`). I'll add one in.
> 
> Also we could consider the new driver *the* RDC in the future which would be 
> the easiest. The problem is if we want to support CUDA's method of RDC 
> considering how other build systems seem to expect it. I could see us 
> embedding the fatbinary in the object file, even if unused, just so that 
> cuobjdump works. However we couldn't support the generation of 
> `__cudaRegisterFatBinary_nv` functions because then those would cause 
> linker errors. WDYT?
> I'm assuming there's one for passing both fgpu-rdc and fno-gpu-rdc

This is not a valid assumption. The whole idea behind `-fno-something` is that 
the options can be overridden. E.g. if the build specifies a standard set of 
compiler options, but we need to override some of them when building a 
particular file. We can only do so by appending to the standard options. 
Potentially we may end up having those options overridden again. While it's not 
very common, it's certainly possible. It's also possible to start with 
'-fno-gpu-rdc' and then override it with `-fgpu-rdc`.

In this case, we care about the final state of RDC specified by -f*gpu-rdc 
options, not by the fact that `-fno-gpu-rdc` is present. 
`Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)` does 
exactly that -- gives you the final state. If it returns false, but we have 
`-foffload-new-driver`, then we need a warning as these options are 
contradictory.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

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


[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6223-6224
   if (IsCuda || IsHIP) {
-if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
+if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false) ||
+Args.hasArg(options::OPT_foffload_new_driver))
   CmdArgs.push_back("-fgpu-rdc");

tra wrote:
> If user specifies both `-fno-gpu-rdc` and `-foffload-new-driver` we would 
> still enable RDC compilation.
> We may want to at least issue a warning. 
> 
> Considering that  we have multiple places where we may check for 
> `-f[no]gpu-rdc` we should make sure we don't get different ideas whether RDC 
> has been enabled.
> I think it may make sense to provide a common way to figure it out. Either 
> via a helper function that would process CLI arguments or calculate it once 
> and save it somewhere.
I haven't quite finalized how to handle this. The new driver should be 
compatible with a non-RDC build since we simply wouldn't embed the device image 
or create offloading entries. It's a little bit more difficult here since the 
new method is opt-in so it requires a flag. We should definitely emit a warning 
if both are enabled (I'm assuming there's one for passing both `fgpu-rdc` and 
`fno-gpu-rdc`). I'll add one in.

Also we could consider the new driver *the* RDC in the future which would be 
the easiest. The problem is if we want to support CUDA's method of RDC 
considering how other build systems seem to expect it. I could see us embedding 
the fatbinary in the object file, even if unused, just so that cuobjdump works. 
However we couldn't support the generation of `__cudaRegisterFatBinary_nv` 
functions because then those would cause linker errors. WDYT?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

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


[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-22 Thread Artem Belevich via Phabricator via cfe-commits
tra added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6223-6224
   if (IsCuda || IsHIP) {
-if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
+if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false) ||
+Args.hasArg(options::OPT_foffload_new_driver))
   CmdArgs.push_back("-fgpu-rdc");

If user specifies both `-fno-gpu-rdc` and `-foffload-new-driver` we would still 
enable RDC compilation.
We may want to at least issue a warning. 

Considering that  we have multiple places where we may check for 
`-f[no]gpu-rdc` we should make sure we don't get different ideas whether RDC 
has been enabled.
I think it may make sense to provide a common way to figure it out. Either via 
a helper function that would process CLI arguments or calculate it once and 
save it somewhere.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

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


[PATCH] D124221: Add new builtin __builtin_reflect_struct.

2022-04-22 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/docs/LanguageExtensions.rst:2434
+
+ bool print(int arg1, int arg2, std::initializer_list fields) {
+   for (auto f : fields) {

rsmith wrote:
> erichkeane wrote:
> > rsmith wrote:
> > > erichkeane wrote:
> > > > I'm curious as to the need for the 'arg1' and 'arg2'?  Also, what is 
> > > > the type of the 'fields' array that works in C?
> > > This is aimed to fix a major deficiency in `__builtin_dump_struct`, that 
> > > there's no way to pass information into its callback (other than stashing 
> > > it in TLS).
> > > 
> > > As noted in the patch description, this builtin is not especially usable 
> > > in C. I'm not sure whether that's fixable, given the very limited 
> > > metaprogramming support in C.
> > Presumably one could also put it in the functor for the callback, or even 
> > as a capture in the lambda.  Though, I'm not positive I see the VALUE to 
> > passing this information, but was just curious as to the intent.
> Suppose you want to dump a struct to a log file, or you want the dump in a 
> string. Or you want to carry along an indentation level. My first attempt at 
> using `__builtin_dump_struct` essentially failed because it doesn't have 
> anything like this; even if we don't want this patch, this is functionality 
> we should add to that builtin.
Ah, I see!  Sure, I can see how those are useful, though again, mostly to the C 
implementation (as those should all be part of the functor's state), and this 
doesn't work particularly well in C.



Comment at: clang/docs/LanguageExtensions.rst:2462
+to the type to reflect. The second argument ``f`` should be some callable
+expression, and can be a function object or an overload set. The builtin calls
+``f``, passing any further arguments ``args...`` followed by an initializer

rsmith wrote:
> erichkeane wrote:
> > rsmith wrote:
> > > erichkeane wrote:
> > > > Is the purpose of the overload set/functor so you can support multiple 
> > > > types (seeing how the 'base' below works)?  How does this all work in 
> > > > C? (or do we just do fields in C, since they cannot have the rest?
> > > > 
> > > > I wonder if we would be better if we treated this function as a 
> > > > 'callback' or a 'callback set' that returned a discriminated union of a 
> > > > pre-defined type that describes what is being returned.  That way it 
> > > > could handle member functions, static variables, etc.
> > > This doesn't really work well in C, as noted in the patch description. A 
> > > set of callbacks might work a bit better across both languages, but I 
> > > don't think it solves the larger problem that there's no good way to pass 
> > > type information into a callback in C.
> > Well, if the callback itself took the discriminated union for each thing, 
> > and we did 1 callback per base/field/etc, perhaps that would be useful? I 
> > just am having a hard time seeing this being all that useful in C, which is 
> > a shame.
> > 
> > 
> I think that would work. I'm not sure it would be better, though, given that 
> it loses the ability to build a type whose shape depends on the number of 
> bases and fields, because you're not given them all at once. (Eg, if you want 
> to build a static array of field names.)
Yep, thats definitely true. There are ways to DO that (either a 2-pass at this 
to get the sizes, allocate something, then go through again filling in your 
struct OR a constant 'append' thing with a `vector` like type), but I see what 
you mean.  It seems that either case we are limiting a couple of useful use 
cases.



Comment at: clang/docs/LanguageExtensions.rst:2473
+
+* For each direct base class, the address of the base class, in declaration
+  order.

rsmith wrote:
> erichkeane wrote:
> > rsmith wrote:
> > > erichkeane wrote:
> > > > I wonder if bases should include their virtualness or access specifier.
> > > I mean, maybe, but I don't have a use case for either. For access in 
> > > general my leaning is to say that the built-in doesn't get special access 
> > > rights -- either it can access everything or you'll get an access error 
> > > if you use it -- in which case including the access for bases and fields 
> > > doesn't seem likely to be super useful.
> > I guess it depends on the use case for these builtins.  I saw the 
> > 'dump-struct' builtin's purpose was for quick & dirty printf-debugging.  At 
> > which point the format/features were less important than the action.  So 
> > from that perspective, I would see this having 'special access rights' as 
> > sort of a necessity.  
> > 
> > Though again, this is a significantly more general builtin, which comes 
> > with additional potential use cases.
> The use cases are the things that `__builtin_dump_struct` gets close to but 
> fails at, such as: I have an `EXPECT_EQ` macro that I'd like to log the 
> difference in input and output 

[PATCH] D124221: Add new builtin __builtin_reflect_struct.

2022-04-22 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:420
+auto *FD = IFD ? IFD->getAnonField() : dyn_cast(D);
+if (!FD || (FD->isUnnamedBitfield() || FD->isAnonymousStructOrUnion()))
+  continue;

rsmith wrote:
> erichkeane wrote:
> > rsmith wrote:
> > > erichkeane wrote:
> > > > Losing the unnamed bitfield is unfortunate, and I the 'dump struct' 
> > > > handles.  As is losing the anonymous struct/union.
> > > > 
> > > > Also, how does this handle 'record type' members?  Does the user have 
> > > > to know the inner type already?  If they already know that much 
> > > > information about the type, they wouldn't really need this, right?
> > > If `__builtin_dump_struct` includes unnamed bitfields, that's a bug in 
> > > that builtin.
> > > 
> > > In general, the user function gets given the bases and members with the 
> > > right types, so they can use an overload set or a template to dispatch 
> > > based on that type. See the SemaCXX test for a basic example of that.
> > I thought it did?  For the use case I see `__builtin_dump_struct` having, I 
> > would think printing the existence of unnamed bitfields to be quite useful.
> > 
> > 
> Why? They're not part of the value, they're just padding.
Looks like `__builtin_dump_struct` currently includes them *and* prints a value 
(whatever garbage happens to be in those padding bits). That's obviously a bug.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

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


[PATCH] D123787: [clang][OpenMP][DebugInfo] Debug support for TLS variables when present in OpenMP consructs

2022-04-22 Thread Adrian Prantl via Phabricator via cfe-commits
aprantl accepted this revision.
aprantl added a comment.
This revision is now accepted and ready to land.

Oh, it's a //global// variable that supposed to shadow the function parameter! 
Thanks for clarifying.


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

https://reviews.llvm.org/D123787

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


[PATCH] D124186: [RISCV] Fix incorrect policy implement for unmasked vslidedown and vslideup.

2022-04-22 Thread Zakk Chen via Phabricator via cfe-commits
khchen updated this revision to Diff 424517.
khchen edited the summary of this revision.
khchen added a comment.

update clang tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124186

Files:
  clang/include/clang/Basic/riscv_vector.td
  clang/test/CodeGen/RISCV/rvv-intrinsics-overloaded/vslidedown.c
  clang/test/CodeGen/RISCV/rvv-intrinsics-overloaded/vslideup.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vslidedown.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vslideup.c
  llvm/include/llvm/IR/IntrinsicsRISCV.td
  llvm/lib/Target/RISCV/RISCVInstrInfoVPseudos.td
  llvm/lib/Target/RISCV/RISCVInstrInfoVVLPatterns.td
  llvm/test/CodeGen/RISCV/rvv/emergency-slot.mir
  llvm/test/CodeGen/RISCV/rvv/extract-subvector.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-calling-conv.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-extload-truncstore.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-extract-subvector.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-fp-buildvec.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-fp-conv.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-fp-setcc.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-fp-shuffles.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-fp2i.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-i2fp.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-insert-i1.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-insert-subvector.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-insert.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-int-buildvec.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-int-exttrunc.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-int-shuffles.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-int.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-mask-buildvec.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-mask-load-store.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-mask-splat.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-masked-gather.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-unaligned.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-vpgather.ll
  llvm/test/CodeGen/RISCV/rvv/insert-subvector.ll
  llvm/test/CodeGen/RISCV/rvv/insertelt-fp-rv32.ll
  llvm/test/CodeGen/RISCV/rvv/insertelt-fp-rv64.ll
  llvm/test/CodeGen/RISCV/rvv/insertelt-i1.ll
  llvm/test/CodeGen/RISCV/rvv/insertelt-int-rv32.ll
  llvm/test/CodeGen/RISCV/rvv/insertelt-int-rv64.ll
  llvm/test/CodeGen/RISCV/rvv/masked-tama.ll
  llvm/test/CodeGen/RISCV/rvv/setcc-fp.ll
  llvm/test/CodeGen/RISCV/rvv/setcc-integer.ll
  llvm/test/CodeGen/RISCV/rvv/unmasked-ta.ll
  llvm/test/CodeGen/RISCV/rvv/vector-splice.ll
  llvm/test/CodeGen/RISCV/rvv/vslidedown-rv32.ll
  llvm/test/CodeGen/RISCV/rvv/vslidedown-rv64.ll
  llvm/test/CodeGen/RISCV/rvv/vslideup-rv32.ll
  llvm/test/CodeGen/RISCV/rvv/vslideup-rv64.ll

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


[PATCH] D124221: Add new builtin __builtin_reflect_struct.

2022-04-22 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: clang/docs/LanguageExtensions.rst:2434
+
+ bool print(int arg1, int arg2, std::initializer_list fields) {
+   for (auto f : fields) {

erichkeane wrote:
> rsmith wrote:
> > erichkeane wrote:
> > > I'm curious as to the need for the 'arg1' and 'arg2'?  Also, what is the 
> > > type of the 'fields' array that works in C?
> > This is aimed to fix a major deficiency in `__builtin_dump_struct`, that 
> > there's no way to pass information into its callback (other than stashing 
> > it in TLS).
> > 
> > As noted in the patch description, this builtin is not especially usable in 
> > C. I'm not sure whether that's fixable, given the very limited 
> > metaprogramming support in C.
> Presumably one could also put it in the functor for the callback, or even as 
> a capture in the lambda.  Though, I'm not positive I see the VALUE to passing 
> this information, but was just curious as to the intent.
Suppose you want to dump a struct to a log file, or you want the dump in a 
string. Or you want to carry along an indentation level. My first attempt at 
using `__builtin_dump_struct` essentially failed because it doesn't have 
anything like this; even if we don't want this patch, this is functionality we 
should add to that builtin.



Comment at: clang/docs/LanguageExtensions.rst:2462
+to the type to reflect. The second argument ``f`` should be some callable
+expression, and can be a function object or an overload set. The builtin calls
+``f``, passing any further arguments ``args...`` followed by an initializer

erichkeane wrote:
> rsmith wrote:
> > erichkeane wrote:
> > > Is the purpose of the overload set/functor so you can support multiple 
> > > types (seeing how the 'base' below works)?  How does this all work in C? 
> > > (or do we just do fields in C, since they cannot have the rest?
> > > 
> > > I wonder if we would be better if we treated this function as a 
> > > 'callback' or a 'callback set' that returned a discriminated union of a 
> > > pre-defined type that describes what is being returned.  That way it 
> > > could handle member functions, static variables, etc.
> > This doesn't really work well in C, as noted in the patch description. A 
> > set of callbacks might work a bit better across both languages, but I don't 
> > think it solves the larger problem that there's no good way to pass type 
> > information into a callback in C.
> Well, if the callback itself took the discriminated union for each thing, and 
> we did 1 callback per base/field/etc, perhaps that would be useful? I just am 
> having a hard time seeing this being all that useful in C, which is a shame.
> 
> 
I think that would work. I'm not sure it would be better, though, given that it 
loses the ability to build a type whose shape depends on the number of bases 
and fields, because you're not given them all at once. (Eg, if you want to 
build a static array of field names.)



Comment at: clang/docs/LanguageExtensions.rst:2473
+
+* For each direct base class, the address of the base class, in declaration
+  order.

erichkeane wrote:
> rsmith wrote:
> > erichkeane wrote:
> > > I wonder if bases should include their virtualness or access specifier.
> > I mean, maybe, but I don't have a use case for either. For access in 
> > general my leaning is to say that the built-in doesn't get special access 
> > rights -- either it can access everything or you'll get an access error if 
> > you use it -- in which case including the access for bases and fields 
> > doesn't seem likely to be super useful.
> I guess it depends on the use case for these builtins.  I saw the 
> 'dump-struct' builtin's purpose was for quick & dirty printf-debugging.  At 
> which point the format/features were less important than the action.  So from 
> that perspective, I would see this having 'special access rights' as sort of 
> a necessity.  
> 
> Though again, this is a significantly more general builtin, which comes with 
> additional potential use cases.
The use cases are the things that `__builtin_dump_struct` gets close to but 
fails at, such as: I have an `EXPECT_EQ` macro that I'd like to log the 
difference in input and output values where possible, or I want to build a 
simple print-to-string utility for structs. Or I want a dump to stout but I 
want it formatted differently from what `__builtin_dump_struct` thinks is best.

The fact that the dump built-in gets us into this area but can't solve these 
problems is frustrating.



Comment at: clang/lib/Sema/SemaChecking.cpp:420
+auto *FD = IFD ? IFD->getAnonField() : dyn_cast(D);
+if (!FD || (FD->isUnnamedBitfield() || FD->isAnonymousStructOrUnion()))
+  continue;

erichkeane wrote:
> rsmith wrote:
> > erichkeane wrote:
> > > Losing the unnamed bitfield is unfortunate, and I the 'dump struct' 
> > > handles.  As is 

[PATCH] D123667: [clang][AST] Fix crash getting name of a template decl

2022-04-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman closed this revision.
aaron.ballman added a comment.

Thank you for the fix! I've commit on your behalf in 
225b91e6cbba31ff1ce787a152a67977d08fdcab 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123667

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


[clang] 225b91e - Fix crash getting name of a template decl

2022-04-22 Thread Aaron Ballman via cfe-commits

Author: Tom Eccles
Date: 2022-04-22T13:03:28-04:00
New Revision: 225b91e6cbba31ff1ce787a152a67977d08fdcab

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

LOG: Fix crash getting name of a template decl

NamedDecl::getIdentifier can return a nullptr when
DeclarationName::isIdentifier is false, which leads to a null pointer
dereference when TypePrinter::printTemplateId calls ->getName().

NamedDecl::getName does the same thing in the successful case and
returns an empty string in the failure case.

This crash affects the llvm 14 packages on llvm.org.

Added: 


Modified: 
clang/lib/AST/TypePrinter.cpp
clang/unittests/AST/TypePrinterTest.cpp

Removed: 




diff  --git a/clang/lib/AST/TypePrinter.cpp b/clang/lib/AST/TypePrinter.cpp
index 32ca7643a7603..d2feb1c10f06c 100644
--- a/clang/lib/AST/TypePrinter.cpp
+++ b/clang/lib/AST/TypePrinter.cpp
@@ -1467,8 +1467,7 @@ void TypePrinter::printTemplateId(const 
TemplateSpecializationType *T,
 if (!Policy.SuppressScope)
   AppendScope(TD->getDeclContext(), OS, TD->getDeclName());
 
-IdentifierInfo *II = TD->getIdentifier();
-OS << II->getName();
+OS << TD->getName();
   } else {
 T->getTemplateName().print(OS, Policy);
   }

diff  --git a/clang/unittests/AST/TypePrinterTest.cpp 
b/clang/unittests/AST/TypePrinterTest.cpp
index 7b44b1ecece24..12801a7018125 100644
--- a/clang/unittests/AST/TypePrinterTest.cpp
+++ b/clang/unittests/AST/TypePrinterTest.cpp
@@ -64,6 +64,22 @@ TEST(TypePrinter, TemplateId) {
   [](PrintingPolicy ) { Policy.FullyQualifiedName = true; }));
 }
 
+TEST(TypePrinter, TemplateId2) {
+  std::string Code = R"cpp(
+  template  class TemplatedType>
+  void func(TemplatedType Param);
+)cpp";
+  auto Matcher = parmVarDecl(hasType(qualType().bind("id")));
+
+  // Regression test ensuring we do not segfault getting the QualType as a
+  // string.
+  ASSERT_TRUE(PrintedTypeMatches(Code, {}, Matcher, "",
+ [](PrintingPolicy ) {
+   Policy.FullyQualifiedName = true;
+   Policy.PrintCanonicalTypes = true;
+ }));
+}
+
 TEST(TypePrinter, ParamsUglified) {
   llvm::StringLiteral Code = R"cpp(
 template  class __f>



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


[PATCH] D124258: [C89/C2x] Change the behavior of implicit int diagnostics

2022-04-22 Thread Erich Keane via Phabricator via cfe-commits
erichkeane accepted this revision.
erichkeane added a comment.
This revision is now accepted and ready to land.

I'm happy enough.  I see both sides of the C89 debate enough to 'disagree and 
commit' on that one.


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

https://reviews.llvm.org/D124258

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


[PATCH] D124258: [C89/C2x] Change the behavior of implicit int diagnostics

2022-04-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman marked 7 inline comments as done.
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/LangOptions.h:534
+  /// Returns true if implicit int is supported at all.
+  bool implicitIntEnabled() const { return !CPlusPlus && !C2x; }
+

cor3ntin wrote:
> erichkeane wrote:
> > aaron.ballman wrote:
> > > erichkeane wrote:
> > > > cor3ntin wrote:
> > > > > erichkeane wrote:
> > > > > > This name seems inverse of what you mean to me?  IDK if you're 
> > > > > > bike-shed-sniping me here, but:
> > > > > > 
> > > > > > `prohibitsImplicitInt` to be the reverse of above? It becomes 
> > > > > > SLIGHTLY ambiguous to me (in that we don't mean "the language 
> > > > > > standard prohibits", we mean "the compiler implementation 
> > > > > > prohibits"), but that can be fixed up with a comment.
> > > > > > 
> > > > > > If you want to keep the direction, perhaps `implicitIntPermitted`, 
> > > > > > at which point I might suggest the one above become 
> > > > > > `implicitIntRequired`.
> > > > > @erichkeane `requiresImplicitInt` is only used twice. Does it needs a 
> > > > > name?
> > > > > 
> > > > *shrug*, I tend to be of the feeling that if you have to say something 
> > > > this often, and functions are basically free, mind as well make one.
> > > The idea here is that `requiresImplicitInt()` tells you when the support 
> > > is mandatory per spec, and `implicitIntEnabled()` tells you when the 
> > > support is either mandatory or an extension. I'm not strongly tied to the 
> > > names, how do these sound?
> > > 
> > > `isImplicitIntRequired()` and `isImplicitIntAllowed()`?
> > > 
> > > (I could also add the word `Support` in there as in 
> > > `isImplicitIntSupportRequired()` but then the function names start to get 
> > > a bit longer than I think is reasonable.)
> > >> The idea here is that requiresImplicitInt() tells you when the support 
> > >> is mandatory per spec, and implicitIntEnabled() tells you when the 
> > >> support is either mandatory or an extension. I'm not strongly tied to 
> > >> the names, how do these sound?
> > 
> > Well, as it is now, the latter tells you whether 'it is allowed as an 
> > extension'.
> > 
> > 
> > >>`isImplicitIntRequired()` and `isImplicitIntAllowed()`?
> > 
> > These seem pretty clear to me.  I don't see 'Support' as being valuable.
> > 
> `implicitIntEnabled` makes sense to me. I guess my question is, is there 
> precedence for options for language-mandated features?
> I guess my question is, is there precedence for options for language-mandated 
> features?

Sure, though many of them also have user-facing command line flags to set the 
options. (wchar_t support, digraphs, etc)

I added these as helper functions mostly because there's no way to have 
language options whose default value is dependent on other language options.


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

https://reviews.llvm.org/D124258

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


[PATCH] D123667: [clang][AST] Fix crash getting name of a template decl

2022-04-22 Thread Tom Eccles via Phabricator via cfe-commits
tblah added a comment.

Yes please commit on my behalf. My details are

Tom Eccles

tom.ecc...@codethink.co.uk

Thanks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123667

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


[PATCH] D123667: [clang][AST] Fix crash getting name of a template decl

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

LGTM, with a commenting nit. The Precommit CI test failures look unrelated to 
me as well.

Do you need me to commit on your behalf? If so, what name and email address 
would you like me to use for patch attribution? (I can fix the commenting issue 
when I land, so don't worry about pushing up a new patch.)




Comment at: clang/unittests/AST/TypePrinterTest.cpp:74-75
+
+  // regression test ensuring we do not segfault getting the qualtype as a
+  // string
+  ASSERT_TRUE(PrintedTypeMatches(Code, {}, Matcher, "",




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123667

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


[PATCH] D124258: [C89/C2x] Change the behavior of implicit int diagnostics

2022-04-22 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:169
+  As of C2x, support for implicit int has been removed, and the warning options
+  will have no effect. Specifying ``-Wimplicit-int`` in C89 mode will now issue
+  warnings instead of being a noop.

aaron.ballman wrote:
> erichkeane wrote:
> > I find myself thinking that despite it being 'valid code' that 
> > `-Wimplicit-int` should be on-by-default in C89 mode. We often warn about 
> > 'valid, but non-future-proof' code, by default, particularly when they are 
> > code-breaking like this is.
> On the one hand, yes. On the other hand, this is only for people who specify 
> `-std=c89` explicitly (which is not the default language mode for C), and I 
> think we've been taking the viewpoint that these folks are mostly trying to 
> keep old, mostly unmaintained code working.
I'm annoyed by how much I understand/agree with both sides of this argument.  



Comment at: clang/include/clang/Basic/LangOptions.h:534
+  /// Returns true if implicit int is supported at all.
+  bool implicitIntEnabled() const { return !CPlusPlus && !C2x; }
+

aaron.ballman wrote:
> erichkeane wrote:
> > cor3ntin wrote:
> > > erichkeane wrote:
> > > > This name seems inverse of what you mean to me?  IDK if you're 
> > > > bike-shed-sniping me here, but:
> > > > 
> > > > `prohibitsImplicitInt` to be the reverse of above? It becomes SLIGHTLY 
> > > > ambiguous to me (in that we don't mean "the language standard 
> > > > prohibits", we mean "the compiler implementation prohibits"), but that 
> > > > can be fixed up with a comment.
> > > > 
> > > > If you want to keep the direction, perhaps `implicitIntPermitted`, at 
> > > > which point I might suggest the one above become `implicitIntRequired`.
> > > @erichkeane `requiresImplicitInt` is only used twice. Does it needs a 
> > > name?
> > > 
> > *shrug*, I tend to be of the feeling that if you have to say something this 
> > often, and functions are basically free, mind as well make one.
> The idea here is that `requiresImplicitInt()` tells you when the support is 
> mandatory per spec, and `implicitIntEnabled()` tells you when the support is 
> either mandatory or an extension. I'm not strongly tied to the names, how do 
> these sound?
> 
> `isImplicitIntRequired()` and `isImplicitIntAllowed()`?
> 
> (I could also add the word `Support` in there as in 
> `isImplicitIntSupportRequired()` but then the function names start to get a 
> bit longer than I think is reasonable.)
>> The idea here is that requiresImplicitInt() tells you when the support is 
>> mandatory per spec, and implicitIntEnabled() tells you when the support is 
>> either mandatory or an extension. I'm not strongly tied to the names, how do 
>> these sound?

Well, as it is now, the latter tells you whether 'it is allowed as an 
extension'.


>>`isImplicitIntRequired()` and `isImplicitIntAllowed()`?

These seem pretty clear to me.  I don't see 'Support' as being valuable.




Comment at: clang/lib/Sema/SemaDecl.cpp:14329
   if (FTI.Params[i].Param == nullptr) {
-SmallString<256> Code;
-llvm::raw_svector_ostream(Code)
-<< "  int " << FTI.Params[i].Ident->getName() << ";\n";
-Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
-<< FTI.Params[i].Ident
-<< FixItHint::CreateInsertion(LocAfterDecls, Code);
+if (getLangOpts().C99) {
+  SmallString<256> Code;

aaron.ballman wrote:
> erichkeane wrote:
> > cor3ntin wrote:
> > > erichkeane wrote:
> > > > IMO there should be a warning here for C89.  Warning for 
> > > > non-future-proof code is pretty typical.
> > > Isn't the counter argument that was made on similar changes that people 
> > > specifically asking for C89 have peculiar expectations?
> > > Otherwise i agree
> > Yep, folks asking for C89 ARE peculiar :D  However, warnings-not-as-error 
> > are, IMO, simply 'helpful'. 
> Same here as above -- we *could* warn, but I suspect it wouldn't be 
> particularly helpful. The fact that we were warning with an extension warning 
> was non-conforming though (we shouldn't fail `-pedantic-errors` in C89 over 
> that).
*grumble grumble*.


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

https://reviews.llvm.org/D124258

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


[PATCH] D124258: [C89/C2x] Change the behavior of implicit int diagnostics

2022-04-22 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/include/clang/Basic/LangOptions.h:534
+  /// Returns true if implicit int is supported at all.
+  bool implicitIntEnabled() const { return !CPlusPlus && !C2x; }
+

aaron.ballman wrote:
> erichkeane wrote:
> > cor3ntin wrote:
> > > erichkeane wrote:
> > > > This name seems inverse of what you mean to me?  IDK if you're 
> > > > bike-shed-sniping me here, but:
> > > > 
> > > > `prohibitsImplicitInt` to be the reverse of above? It becomes SLIGHTLY 
> > > > ambiguous to me (in that we don't mean "the language standard 
> > > > prohibits", we mean "the compiler implementation prohibits"), but that 
> > > > can be fixed up with a comment.
> > > > 
> > > > If you want to keep the direction, perhaps `implicitIntPermitted`, at 
> > > > which point I might suggest the one above become `implicitIntRequired`.
> > > @erichkeane `requiresImplicitInt` is only used twice. Does it needs a 
> > > name?
> > > 
> > *shrug*, I tend to be of the feeling that if you have to say something this 
> > often, and functions are basically free, mind as well make one.
> The idea here is that `requiresImplicitInt()` tells you when the support is 
> mandatory per spec, and `implicitIntEnabled()` tells you when the support is 
> either mandatory or an extension. I'm not strongly tied to the names, how do 
> these sound?
> 
> `isImplicitIntRequired()` and `isImplicitIntAllowed()`?
> 
> (I could also add the word `Support` in there as in 
> `isImplicitIntSupportRequired()` but then the function names start to get a 
> bit longer than I think is reasonable.)
`implicitIntEnabled` makes sense to me. I guess my question is, is there 
precedence for options for language-mandated features?


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

https://reviews.llvm.org/D124258

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


[PATCH] D124221: Add new builtin __builtin_reflect_struct.

2022-04-22 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

>> I think you've misunderstood; that is not required. Though with the design 
>> as-is, it might make sense to restrict this to being C++-only, given that 
>> there's not really a way to effectively use this from C.

Ah, I see the example in SemaCXX.  its sad we can't do this from C, I would 
consider the use case of `__builtin_dump_struct` to be very handy in C.

I guess I think I would want to start off with, "what do we see the 'usecase' 
of these builtins" being.  `__builtin_dump_struct` to me seems to have a pretty 
clear and semantically enforced one: its useful to printf it for debugging 
purposes.

This seems to be more useful-enough that it leaves me feeling like users would 
very quickly fall into, "man, I wish this did more" because of it.  Its just a 
shame we can't get SG7 to work quicker :)




Comment at: clang/docs/LanguageExtensions.rst:2434
+
+ bool print(int arg1, int arg2, std::initializer_list fields) {
+   for (auto f : fields) {

rsmith wrote:
> erichkeane wrote:
> > I'm curious as to the need for the 'arg1' and 'arg2'?  Also, what is the 
> > type of the 'fields' array that works in C?
> This is aimed to fix a major deficiency in `__builtin_dump_struct`, that 
> there's no way to pass information into its callback (other than stashing it 
> in TLS).
> 
> As noted in the patch description, this builtin is not especially usable in 
> C. I'm not sure whether that's fixable, given the very limited 
> metaprogramming support in C.
Presumably one could also put it in the functor for the callback, or even as a 
capture in the lambda.  Though, I'm not positive I see the VALUE to passing 
this information, but was just curious as to the intent.



Comment at: clang/docs/LanguageExtensions.rst:2437
+ std::cout << f.name;
+ if (f.bitwidth)
+   std::cout << " : " << f.bitwidth;

rsmith wrote:
> erichkeane wrote:
> > Hmm... what is the type of f.bitwidth?  A zero-length bitwidth is a valid 
> > thing, so having it just be an 'int' doesn't seem workable.
> It's a `size_t`. There are no zero-size bitfield members. (Unnamed bitfield 
> aren't members, so are excluded here.) In any case, you can tell the 
> difference between a bitfield and a regular member by the length of the 
> initialiser list; we don't pass a bit width for non-bit-field members.
>>There are no zero-size bitfield members. (Unnamed bitfield aren't members, so 
>>are excluded here.)
Hrm... Semantically YES, lexically I'm not sure folks make that 
differentiation.  One issue with skipping 'unnamed bitfields' is it makes 
something like:

```
struct Foo {
int : 31; // Take up some space so something else could have been put there.
int field : 1; 
int field2 : 2;
};
```
and comparing `sizeof` the type with the output to be... jarring at least.

>> you can tell the difference between a bitfield and a regular member by the 
>> length of the initialiser list;

I see now how you've done that with ctors in C++.  It feels that the way of 
doing this in C is unfortunately quite clunky (in addition, not being able to 
use arbitrary types).



Comment at: clang/docs/LanguageExtensions.rst:2462
+to the type to reflect. The second argument ``f`` should be some callable
+expression, and can be a function object or an overload set. The builtin calls
+``f``, passing any further arguments ``args...`` followed by an initializer

rsmith wrote:
> erichkeane wrote:
> > Is the purpose of the overload set/functor so you can support multiple 
> > types (seeing how the 'base' below works)?  How does this all work in C? 
> > (or do we just do fields in C, since they cannot have the rest?
> > 
> > I wonder if we would be better if we treated this function as a 'callback' 
> > or a 'callback set' that returned a discriminated union of a pre-defined 
> > type that describes what is being returned.  That way it could handle 
> > member functions, static variables, etc.
> This doesn't really work well in C, as noted in the patch description. A set 
> of callbacks might work a bit better across both languages, but I don't think 
> it solves the larger problem that there's no good way to pass type 
> information into a callback in C.
Well, if the callback itself took the discriminated union for each thing, and 
we did 1 callback per base/field/etc, perhaps that would be useful? I just am 
having a hard time seeing this being all that useful in C, which is a shame.





Comment at: clang/docs/LanguageExtensions.rst:2471
+
+The initializer list contains the following components:
+

rsmith wrote:
> erichkeane wrote:
> > I find myself wishing this was a more complete list.
> What else do you want? My goal here was to be able to do what 
> `__builtin_dump_struct` does but without its many arbitrary limitations. From 
> C++, this is enough for that.
I think this is again falling 

[PATCH] D123885: Revert "Revert "Revert "[clang][pp] adds '#pragma include_instead'"""

2022-04-22 Thread Christopher Di Bella 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 rGe9a902c7f755: Revert Revert Revert 
[clang][pp] adds #pragma include_instead 
(authored by cjdb).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123885

Files:
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/pseudo/lib/Lex.cpp
  clang/include/clang/Basic/DiagnosticLexKinds.td
  clang/include/clang/Basic/SourceManager.h
  clang/include/clang/Lex/HeaderSearch.h
  clang/include/clang/Lex/Lexer.h
  clang/include/clang/Lex/Preprocessor.h
  clang/include/clang/Lex/PreprocessorLexer.h
  clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
  clang/lib/Lex/Lexer.cpp
  clang/lib/Lex/PPDirectives.cpp
  clang/lib/Lex/PPLexerChange.cpp
  clang/lib/Lex/Pragma.cpp
  clang/test/PCH/ms-pch-macro-include_instead-regression.c
  clang/test/Preprocessor/Inputs/include_instead/bad-syntax.h
  clang/test/Preprocessor/Inputs/include_instead/file-not-found.h
  clang/test/Preprocessor/Inputs/include_instead/non-system-header.h
  clang/test/Preprocessor/Inputs/include_instead/private-x.h
  clang/test/Preprocessor/Inputs/include_instead/private1.h
  clang/test/Preprocessor/Inputs/include_instead/private2.h
  clang/test/Preprocessor/Inputs/include_instead/private3.h
  clang/test/Preprocessor/Inputs/include_instead/public-after.h
  clang/test/Preprocessor/Inputs/include_instead/public-before.h
  clang/test/Preprocessor/Inputs/include_instead/public-empty.h
  clang/test/Preprocessor/include_instead.cpp
  clang/test/Preprocessor/include_instead_file_not_found.cpp

Index: clang/test/Preprocessor/include_instead_file_not_found.cpp
===
--- clang/test/Preprocessor/include_instead_file_not_found.cpp
+++ /dev/null
@@ -1,2 +0,0 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -I %S/Inputs %s
-#include 
Index: clang/test/Preprocessor/include_instead.cpp
===
--- clang/test/Preprocessor/include_instead.cpp
+++ /dev/null
@@ -1,16 +0,0 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -I %S/Inputs %s
-
-#include 
-#include 
-
-#include 
-// expected-error@-1{{header '' is an implementation detail; #include '' instead}}
-
-#include "include_instead/private2.h"
-// expected-error@-1{{header '"include_instead/private2.h"' is an implementation detail; #include either '' or '"include_instead/public-after.h"' instead}}
-
-#include 
-// expected-error@-1{{header '' is an implementation detail; #include one of {'', '', '"include_instead/public-before.h"'} instead}}
-
-#include 
-#include 
Index: clang/test/Preprocessor/Inputs/include_instead/public-empty.h
===
--- clang/test/Preprocessor/Inputs/include_instead/public-empty.h
+++ /dev/null
@@ -1 +0,0 @@
-// This file simply needs to exist.
Index: clang/test/Preprocessor/Inputs/include_instead/public-before.h
===
--- clang/test/Preprocessor/Inputs/include_instead/public-before.h
+++ /dev/null
@@ -1,5 +0,0 @@
-#pragma GCC system_header
-
-#include  // no warning expected
-#include  // no warning expected
-#include  // no warning expected
Index: clang/test/Preprocessor/Inputs/include_instead/public-after.h
===
--- clang/test/Preprocessor/Inputs/include_instead/public-after.h
+++ /dev/null
@@ -1,2 +0,0 @@
-#include 
-#pragma GCC system_header
Index: clang/test/Preprocessor/Inputs/include_instead/private3.h
===
--- clang/test/Preprocessor/Inputs/include_instead/private3.h
+++ /dev/null
@@ -1,5 +0,0 @@
-#pragma GCC system_header
-
-#pragma clang include_instead()
-#pragma clang include_instead()
-#pragma clang include_instead("include_instead/public-before.h")
Index: clang/test/Preprocessor/Inputs/include_instead/private2.h
===
--- clang/test/Preprocessor/Inputs/include_instead/private2.h
+++ /dev/null
@@ -1,4 +0,0 @@
-#pragma GCC system_header
-
-#pragma clang include_instead()
-#pragma clang include_instead("include_instead/public-after.h")
Index: clang/test/Preprocessor/Inputs/include_instead/private1.h
===
--- clang/test/Preprocessor/Inputs/include_instead/private1.h
+++ /dev/null
@@ -1,2 +0,0 @@
-#pragma GCC system_header
-#pragma clang include_instead()
Index: clang/test/Preprocessor/Inputs/include_instead/private-x.h
===
--- clang/test/Preprocessor/Inputs/include_instead/private-x.h
+++ /dev/null
@@ -1,4 +0,0 @@
-#include 
-
-#pragma GCC system_header
-#pragma clang include_instead()
Index: 

[clang-tools-extra] e9a902c - Revert "Revert "Revert "[clang][pp] adds '#pragma include_instead'"""

2022-04-22 Thread Christopher Di Bella via cfe-commits

Author: Christopher Di Bella
Date: 2022-04-22T16:37:20Z
New Revision: e9a902c7f755a378e197c4b246a32859c0ee162d

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

LOG: Revert "Revert "Revert "[clang][pp] adds '#pragma include_instead'"""

> Includes regression test for problem noted by @hans.
> is reverts commit 973de71.
>
> Differential Revision: https://reviews.llvm.org/D106898

Feature implemented as-is is fairly expensive and hasn't been used by
libc++. A potential reimplementation is possible if libc++ become
interested in this feature again.

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

Added: 


Modified: 
clang-tools-extra/clangd/Selection.cpp
clang-tools-extra/pseudo/lib/Lex.cpp
clang/include/clang/Basic/DiagnosticLexKinds.td
clang/include/clang/Basic/SourceManager.h
clang/include/clang/Lex/HeaderSearch.h
clang/include/clang/Lex/Lexer.h
clang/include/clang/Lex/Preprocessor.h
clang/include/clang/Lex/PreprocessorLexer.h
clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
clang/lib/Lex/Lexer.cpp
clang/lib/Lex/PPDirectives.cpp
clang/lib/Lex/PPLexerChange.cpp
clang/lib/Lex/Pragma.cpp

Removed: 
clang/test/PCH/ms-pch-macro-include_instead-regression.c
clang/test/Preprocessor/Inputs/include_instead/bad-syntax.h
clang/test/Preprocessor/Inputs/include_instead/file-not-found.h
clang/test/Preprocessor/Inputs/include_instead/non-system-header.h
clang/test/Preprocessor/Inputs/include_instead/private-x.h
clang/test/Preprocessor/Inputs/include_instead/private1.h
clang/test/Preprocessor/Inputs/include_instead/private2.h
clang/test/Preprocessor/Inputs/include_instead/private3.h
clang/test/Preprocessor/Inputs/include_instead/public-after.h
clang/test/Preprocessor/Inputs/include_instead/public-before.h
clang/test/Preprocessor/Inputs/include_instead/public-empty.h
clang/test/Preprocessor/include_instead.cpp
clang/test/Preprocessor/include_instead_file_not_found.cpp



diff  --git a/clang-tools-extra/clangd/Selection.cpp 
b/clang-tools-extra/clangd/Selection.cpp
index ba2f253eb0757..fa3e6ff22a00a 100644
--- a/clang-tools-extra/clangd/Selection.cpp
+++ b/clang-tools-extra/clangd/Selection.cpp
@@ -30,6 +30,7 @@
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
+#include 
 #include 
 
 namespace clang {

diff  --git a/clang-tools-extra/pseudo/lib/Lex.cpp 
b/clang-tools-extra/pseudo/lib/Lex.cpp
index e99bf3a63e5e1..72eff3c12f25c 100644
--- a/clang-tools-extra/pseudo/lib/Lex.cpp
+++ b/clang-tools-extra/pseudo/lib/Lex.cpp
@@ -7,6 +7,7 @@
 
//===--===//
 
 #include "clang-pseudo/Token.h"
+#include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/Lexer.h"

diff  --git a/clang/include/clang/Basic/DiagnosticLexKinds.td 
b/clang/include/clang/Basic/DiagnosticLexKinds.td
index 0f424b02c812a..543ce8a3649d1 100644
--- a/clang/include/clang/Basic/DiagnosticLexKinds.td
+++ b/clang/include/clang/Basic/DiagnosticLexKinds.td
@@ -315,12 +315,6 @@ def pp_pragma_sysheader_in_main_file : Warning<
   "#pragma system_header ignored in main file">,
   InGroup>;
 
-def err_pragma_include_instead_not_sysheader : Error<
-  "'#pragma clang include_instead' cannot be used outside of system headers">;
-def err_pragma_include_instead_system_reserved : Error<
-  "header '%0' is an implementation detail; #include %select{'%2'|either '%2' "
-  "or '%3'|one of %2}1 instead">;
-
 def err_illegal_use_of_flt_eval_macro : Error<
   "'__FLT_EVAL_METHOD__' cannot be expanded inside a scope containing "
   "'#pragma clang fp eval_method'">;

diff  --git a/clang/include/clang/Basic/SourceManager.h 
b/clang/include/clang/Basic/SourceManager.h
index cc29c24f5a35f..3f3f1bb65c2c1 100644
--- a/clang/include/clang/Basic/SourceManager.h
+++ b/clang/include/clang/Basic/SourceManager.h
@@ -36,6 +36,7 @@
 
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/FileEntry.h"
+#include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceLocation.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/BitVector.h"

diff  --git a/clang/include/clang/Lex/HeaderSearch.h 
b/clang/include/clang/Lex/HeaderSearch.h
index 3a170d2d3fa8d..e88e600ba2b97 100644
--- a/clang/include/clang/Lex/HeaderSearch.h
+++ b/clang/include/clang/Lex/HeaderSearch.h
@@ -20,9 +20,6 @@
 #include "clang/Lex/ModuleMap.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
-#include "llvm/ADT/SetVector.h"
-#include "llvm/ADT/SmallSet.h"
-#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSet.h"
@@ 

[PATCH] D124258: [C89/C2x] Change the behavior of implicit int diagnostics

2022-04-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman marked 2 inline comments as done.
aaron.ballman added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:169
+  As of C2x, support for implicit int has been removed, and the warning options
+  will have no effect. Specifying ``-Wimplicit-int`` in C89 mode will now issue
+  warnings instead of being a noop.

erichkeane wrote:
> I find myself thinking that despite it being 'valid code' that 
> `-Wimplicit-int` should be on-by-default in C89 mode. We often warn about 
> 'valid, but non-future-proof' code, by default, particularly when they are 
> code-breaking like this is.
On the one hand, yes. On the other hand, this is only for people who specify 
`-std=c89` explicitly (which is not the default language mode for C), and I 
think we've been taking the viewpoint that these folks are mostly trying to 
keep old, mostly unmaintained code working.



Comment at: clang/include/clang/Basic/LangOptions.h:534
+  /// Returns true if implicit int is supported at all.
+  bool implicitIntEnabled() const { return !CPlusPlus && !C2x; }
+

erichkeane wrote:
> cor3ntin wrote:
> > erichkeane wrote:
> > > This name seems inverse of what you mean to me?  IDK if you're 
> > > bike-shed-sniping me here, but:
> > > 
> > > `prohibitsImplicitInt` to be the reverse of above? It becomes SLIGHTLY 
> > > ambiguous to me (in that we don't mean "the language standard prohibits", 
> > > we mean "the compiler implementation prohibits"), but that can be fixed 
> > > up with a comment.
> > > 
> > > If you want to keep the direction, perhaps `implicitIntPermitted`, at 
> > > which point I might suggest the one above become `implicitIntRequired`.
> > @erichkeane `requiresImplicitInt` is only used twice. Does it needs a name?
> > 
> *shrug*, I tend to be of the feeling that if you have to say something this 
> often, and functions are basically free, mind as well make one.
The idea here is that `requiresImplicitInt()` tells you when the support is 
mandatory per spec, and `implicitIntEnabled()` tells you when the support is 
either mandatory or an extension. I'm not strongly tied to the names, how do 
these sound?

`isImplicitIntRequired()` and `isImplicitIntAllowed()`?

(I could also add the word `Support` in there as in 
`isImplicitIntSupportRequired()` but then the function names start to get a bit 
longer than I think is reasonable.)



Comment at: clang/lib/Parse/Parser.cpp:1198
 
   // If this is C90 and the declspecs were completely missing, fudge in an
   // implicit int.  We do this here because this is the only place where

erichkeane wrote:
> C90?
I'll fix the comment up. This confusion exists all over the place. :-D



Comment at: clang/lib/Sema/SemaDecl.cpp:14329
   if (FTI.Params[i].Param == nullptr) {
-SmallString<256> Code;
-llvm::raw_svector_ostream(Code)
-<< "  int " << FTI.Params[i].Ident->getName() << ";\n";
-Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
-<< FTI.Params[i].Ident
-<< FixItHint::CreateInsertion(LocAfterDecls, Code);
+if (getLangOpts().C99) {
+  SmallString<256> Code;

erichkeane wrote:
> cor3ntin wrote:
> > erichkeane wrote:
> > > IMO there should be a warning here for C89.  Warning for non-future-proof 
> > > code is pretty typical.
> > Isn't the counter argument that was made on similar changes that people 
> > specifically asking for C89 have peculiar expectations?
> > Otherwise i agree
> Yep, folks asking for C89 ARE peculiar :D  However, warnings-not-as-error 
> are, IMO, simply 'helpful'. 
Same here as above -- we *could* warn, but I suspect it wouldn't be 
particularly helpful. The fact that we were warning with an extension warning 
was non-conforming though (we shouldn't fail `-pedantic-errors` in C89 over 
that).



Comment at: clang/lib/Sema/SemaDecl.cpp:14342-14343
 DeclSpec DS(attrs);
-const char* PrevSpec; // unused
-unsigned DiagID; // unused
+const char *PrevSpec; // unused
+unsigned DiagID;  // unused
 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,

erichkeane wrote:
> cor3ntin wrote:
> > Nitpick: whitespace only change
> This might be a clang-format thing based on the previous line.
Yeah, clang-format got a bit aggressive there, I'll be the formatting changes 
out, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124258

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


[clang] c9e7eec - [clang-format][NFC] Use isComment() in setCommentLineLevels()

2022-04-22 Thread via cfe-commits

Author: owenca
Date: 2022-04-22T09:21:28-07:00
New Revision: c9e7eec7bc41e9cb86e01acd5c91faa5c9ee0bf1

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

LOG: [clang-format][NFC] Use isComment() in setCommentLineLevels()

Also replace an unnecessary check with assert() in the unwrapped
line parser.

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/UnwrappedLineParser.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 5f3b434dba956..cb950f2b2198d 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2505,17 +2505,10 @@ void TokenAnnotator::setCommentLineLevels(
   const AnnotatedLine *NextNonCommentLine = nullptr;
   for (AnnotatedLine *Line : llvm::reverse(Lines)) {
 assert(Line->First);
-bool CommentLine = true;
-for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
-  if (!Tok->is(tok::comment)) {
-CommentLine = false;
-break;
-  }
-}
 
 // If the comment is currently aligned with the line immediately following
 // it, that's probably intentional and we should keep it.
-if (NextNonCommentLine && CommentLine &&
+if (NextNonCommentLine && Line->isComment() &&
 NextNonCommentLine->First->NewlinesBefore <= 1 &&
 NextNonCommentLine->First->OriginalColumn ==
 Line->First->OriginalColumn) {

diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 018a7ae3ee794..1e2f4d6761e1e 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2470,8 +2470,9 @@ FormatToken 
*UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
 Kind = IfStmtKind::IfElseIf;
   addUnwrappedLine();
 } else if (FormatTok->is(tok::kw_if)) {
-  FormatToken *Previous = Tokens->getPreviousToken();
-  const bool IsPrecededByComment = Previous && Previous->is(tok::comment);
+  const FormatToken *Previous = Tokens->getPreviousToken();
+  assert(Previous);
+  const bool IsPrecededByComment = Previous->is(tok::comment);
   if (IsPrecededByComment) {
 addUnwrappedLine();
 ++Line->Level;



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


[PATCH] D124215: [clang-format][NFC] Use isComment() in setCommentLineLevels()

2022-04-22 Thread Owen Pan 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 rGc9e7eec7bc41: [clang-format][NFC] Use isComment() in 
setCommentLineLevels() (authored by owenpan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124215

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/lib/Format/UnwrappedLineParser.cpp


Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2470,8 +2470,9 @@
 Kind = IfStmtKind::IfElseIf;
   addUnwrappedLine();
 } else if (FormatTok->is(tok::kw_if)) {
-  FormatToken *Previous = Tokens->getPreviousToken();
-  const bool IsPrecededByComment = Previous && Previous->is(tok::comment);
+  const FormatToken *Previous = Tokens->getPreviousToken();
+  assert(Previous);
+  const bool IsPrecededByComment = Previous->is(tok::comment);
   if (IsPrecededByComment) {
 addUnwrappedLine();
 ++Line->Level;
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2505,17 +2505,10 @@
   const AnnotatedLine *NextNonCommentLine = nullptr;
   for (AnnotatedLine *Line : llvm::reverse(Lines)) {
 assert(Line->First);
-bool CommentLine = true;
-for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
-  if (!Tok->is(tok::comment)) {
-CommentLine = false;
-break;
-  }
-}
 
 // If the comment is currently aligned with the line immediately following
 // it, that's probably intentional and we should keep it.
-if (NextNonCommentLine && CommentLine &&
+if (NextNonCommentLine && Line->isComment() &&
 NextNonCommentLine->First->NewlinesBefore <= 1 &&
 NextNonCommentLine->First->OriginalColumn ==
 Line->First->OriginalColumn) {


Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2470,8 +2470,9 @@
 Kind = IfStmtKind::IfElseIf;
   addUnwrappedLine();
 } else if (FormatTok->is(tok::kw_if)) {
-  FormatToken *Previous = Tokens->getPreviousToken();
-  const bool IsPrecededByComment = Previous && Previous->is(tok::comment);
+  const FormatToken *Previous = Tokens->getPreviousToken();
+  assert(Previous);
+  const bool IsPrecededByComment = Previous->is(tok::comment);
   if (IsPrecededByComment) {
 addUnwrappedLine();
 ++Line->Level;
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2505,17 +2505,10 @@
   const AnnotatedLine *NextNonCommentLine = nullptr;
   for (AnnotatedLine *Line : llvm::reverse(Lines)) {
 assert(Line->First);
-bool CommentLine = true;
-for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
-  if (!Tok->is(tok::comment)) {
-CommentLine = false;
-break;
-  }
-}
 
 // If the comment is currently aligned with the line immediately following
 // it, that's probably intentional and we should keep it.
-if (NextNonCommentLine && CommentLine &&
+if (NextNonCommentLine && Line->isComment() &&
 NextNonCommentLine->First->NewlinesBefore <= 1 &&
 NextNonCommentLine->First->OriginalColumn ==
 Line->First->OriginalColumn) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D119296: KCFI sanitizer

2022-04-22 Thread Sami Tolvanen via Phabricator via cfe-commits
samitolvanen added a comment.

In D119296#3466027 , @joaomoreira 
wrote:

> I played a little bit with kcfi and here are some thoughts:
>
> - under -Os I saw functions being inlined, regardless of the source code 
> calling them indirectly. In these scenarios, the KCFI check was still in 
> place, even though there was not a pointer involved in the call. Although not 
> semantically incorrect, it would be great to prevent the unnecessary overhead 
> (see attached source/compile it with -Os and -fsanitize=kcfi).

Yes, I suspect this might be an issue with Clang's existing CFI schemes too, 
and would probably require an additional pass to drop checks before calls that 
were either inlined or optimized into direct calls.

> - I noticed that KCFI checks are placed much before the indirect call 
> arguments are properly placed in the passing registers. This makes the 
> position of the check unpredictable. I assume this is a bad thing in case the 
> kernel eventually decides to come up with an approach that uses alternatives 
> CFI schemes through text-patching.

It shouldn't matter for text patching as we'll still know the exact location of 
the instruction sequence that we want to patch by looking at the `.kcfi_traps` 
section.

> Because of things like the above, in the past I decided to implement these 
> things in the very backend of the compiler, so other optimizations would not 
> break the layout nor leave dummy checks around. I find it nice to have this 
> implemented as a more architecture general feature, but maybe it would be 
> cool to have a finalization pass in the X86 backend just to tie things.

@pcc, any thoughts about these issues?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119296

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


[PATCH] D124221: Add new builtin __builtin_reflect_struct.

2022-04-22 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

In D124221#3467467 , @erichkeane 
wrote:

> I generally just question the usefulness of this.  Despite its shortcomings, 
> the 'dump struct' has the capability of runtime introspection into a type, 
> whereas this seems to require that the user 'know' a significant amount about 
> the type that they are introspecting (number of bases, number of fields, 
> field TYPES).

I think you've misunderstood; that is not required. Though with the design 
as-is, it might make sense to restrict this to being C++-only, given that 
there's not really a way to effectively use this from C.




Comment at: clang/docs/LanguageExtensions.rst:2434
+
+ bool print(int arg1, int arg2, std::initializer_list fields) {
+   for (auto f : fields) {

erichkeane wrote:
> I'm curious as to the need for the 'arg1' and 'arg2'?  Also, what is the type 
> of the 'fields' array that works in C?
This is aimed to fix a major deficiency in `__builtin_dump_struct`, that 
there's no way to pass information into its callback (other than stashing it in 
TLS).

As noted in the patch description, this builtin is not especially usable in C. 
I'm not sure whether that's fixable, given the very limited metaprogramming 
support in C.



Comment at: clang/docs/LanguageExtensions.rst:2437
+ std::cout << f.name;
+ if (f.bitwidth)
+   std::cout << " : " << f.bitwidth;

erichkeane wrote:
> Hmm... what is the type of f.bitwidth?  A zero-length bitwidth is a valid 
> thing, so having it just be an 'int' doesn't seem workable.
It's a `size_t`. There are no zero-size bitfield members. (Unnamed bitfield 
aren't members, so are excluded here.) In any case, you can tell the difference 
between a bitfield and a regular member by the length of the initialiser list; 
we don't pass a bit width for non-bit-field members.



Comment at: clang/docs/LanguageExtensions.rst:2462
+to the type to reflect. The second argument ``f`` should be some callable
+expression, and can be a function object or an overload set. The builtin calls
+``f``, passing any further arguments ``args...`` followed by an initializer

erichkeane wrote:
> Is the purpose of the overload set/functor so you can support multiple types 
> (seeing how the 'base' below works)?  How does this all work in C? (or do we 
> just do fields in C, since they cannot have the rest?
> 
> I wonder if we would be better if we treated this function as a 'callback' or 
> a 'callback set' that returned a discriminated union of a pre-defined type 
> that describes what is being returned.  That way it could handle member 
> functions, static variables, etc.
This doesn't really work well in C, as noted in the patch description. A set of 
callbacks might work a bit better across both languages, but I don't think it 
solves the larger problem that there's no good way to pass type information 
into a callback in C.



Comment at: clang/docs/LanguageExtensions.rst:2471
+
+The initializer list contains the following components:
+

erichkeane wrote:
> I find myself wishing this was a more complete list.
What else do you want? My goal here was to be able to do what 
`__builtin_dump_struct` does but without its many arbitrary limitations. From 
C++, this is enough for that.



Comment at: clang/docs/LanguageExtensions.rst:2473
+
+* For each direct base class, the address of the base class, in declaration
+  order.

erichkeane wrote:
> I wonder if bases should include their virtualness or access specifier.
I mean, maybe, but I don't have a use case for either. For access in general my 
leaning is to say that the built-in doesn't get special access rights -- either 
it can access everything or you'll get an access error if you use it -- in 
which case including the access for bases and fields doesn't seem likely to be 
super useful.



Comment at: clang/lib/Sema/SemaChecking.cpp:420
+auto *FD = IFD ? IFD->getAnonField() : dyn_cast(D);
+if (!FD || (FD->isUnnamedBitfield() || FD->isAnonymousStructOrUnion()))
+  continue;

erichkeane wrote:
> Losing the unnamed bitfield is unfortunate, and I the 'dump struct' handles.  
> As is losing the anonymous struct/union.
> 
> Also, how does this handle 'record type' members?  Does the user have to know 
> the inner type already?  If they already know that much information about the 
> type, they wouldn't really need this, right?
If `__builtin_dump_struct` includes unnamed bitfields, that's a bug in that 
builtin.

In general, the user function gets given the bases and members with the right 
types, so they can use an overload set or a template to dispatch based on that 
type. See the SemaCXX test for a basic example of that.



Comment at: 

[PATCH] D85528: [analyzer] Fix cast evaluation on scoped enums in ExprEngine

2022-04-22 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 424497.
steakhal added a comment.

Added the missing `-verify` flag for the new RUN line.
Also, add an elaborate description in the test for explaining the situation.


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

https://reviews.llvm.org/D85528

Files:
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/test/Analysis/z3-refute-enum-crash.cpp


Index: clang/test/Analysis/z3-refute-enum-crash.cpp
===
--- /dev/null
+++ clang/test/Analysis/z3-refute-enum-crash.cpp
@@ -0,0 +1,77 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config crosscheck-with-z3=true -verify %s
+//
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -verify %s
+//
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config support-symbolic-integer-casts=true 
-verify=symbolic %s
+//
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config support-symbolic-integer-casts=false -verify %s
+//
+// REQUIRES: asserts, z3
+//
+// Requires z3 only for refutation. Works with both constraint managers.
+
+void clang_analyzer_dump(int);
+
+using sugar_t = unsigned char;
+
+// Enum types
+enum class ScopedSugared : sugar_t {};
+enum class ScopedPrimitive : unsigned char {};
+enum UnscopedSugared : sugar_t {};
+enum UnscopedPrimitive : unsigned char {};
+
+template 
+T conjure();
+
+void test_enum_types() {
+  // Let's construct a 'binop(sym, int)', where the binop will trigger an
+  // integral promotion to int. Note that we need to first explicit cast
+  // the scoped-enum to an integral, to make it compile. We could have choosen
+  // any other binary operator.
+  int sym1 = static_cast(conjure()) & 0x0F;
+  int sym2 = static_cast(conjure()) & 0x0F;
+  int sym3 = static_cast(conjure()) & 0x0F;
+  int sym4 = static_cast(conjure()) & 0x0F;
+
+  // We need to introduce a constraint referring to the binop, to get it
+  // serialized during the z3-refutation.
+  if (sym1 && sym2 && sym3 && sym4) {
+// no-crash on these dumps
+//
+// The 'clang_analyzer_dump' will construct a bugreport, which in turn will
+// trigger a z3-refutation. Refutation will walk the bugpath, collect and
+// serialize the path-constraints into z3 expressions. The binop will
+// operate over 'int' type, but the symbolic operand might have a different
+// type - surprisingly.
+// Historically, the static analyzer did not emit symbolic casts in a lot
+// of cases, not even when the c++ standard mandated it, like for casting
+// a scoped enum to its underlying type. Hence, during the z3 constraint
+// serialization, it made up these 'missing' integral casts - for the
+// implicit cases at least.
+// However, it would still not emit the cast for missing explicit casts,
+// hence 8-bit wide symbol would be bitwise 'and'-ed with a 32-bit wide
+// int, violating an assertion stating that the operands should have the
+// same bitwidths.
+
+clang_analyzer_dump(sym1);
+// expected-warning-re@-1 {{((unsigned char) (conj_${{[0-9]+}}{enum 
ScopedSugared, LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}})) & 15}}
+// symbolic-warning-re@-2   {{((int) (conj_${{[0-9]+}}{enum 
ScopedSugared, LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}})) & 15}}
+
+clang_analyzer_dump(sym2);
+// expected-warning-re@-1 {{((unsigned char) (conj_${{[0-9]+}}{enum 
ScopedPrimitive, LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}})) & 15}}
+// symbolic-warning-re@-2   {{((int) (conj_${{[0-9]+}}{enum 
ScopedPrimitive, LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}})) & 15}}
+
+clang_analyzer_dump(sym3);
+// expected-warning-re@-1{{(conj_${{[0-9]+}}{enum UnscopedSugared, 
LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}}) & 15}}
+// symbolic-warning-re@-2 {{((int) (conj_${{[0-9]+}}{enum UnscopedSugared, 
LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}})) & 15}}
+
+clang_analyzer_dump(sym4);
+// expected-warning-re@-1{{(conj_${{[0-9]+}}{enum 
UnscopedPrimitive, LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}}) & 15}}
+// symbolic-warning-re@-2 {{((int) (conj_${{[0-9]+}}{enum 
UnscopedPrimitive, LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}})) & 15}}
+  }
+}
+
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -983,8 +983,8 @@
 
 // Produce SymbolCast if CastTy and T are different integers.
 // NOTE: In the end the type of SymbolCast shall be equal to CastTy.
-if (T->isIntegralOrEnumerationType() &&
-CastTy->isIntegralOrEnumerationType()) {
+if (T->isIntegralOrUnscopedEnumerationType() &&
+CastTy->isIntegralOrUnscopedEnumerationType()) {
   

[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

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


[PATCH] D124244: [analyzer] add StoreToImmutable and ModelConstQualifiedReturn checkers

2022-04-22 Thread Zurab Tsinadze via Phabricator via cfe-commits
zukatsinadze updated this revision to Diff 424493.
zukatsinadze added a comment.

fix clang format


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

https://reviews.llvm.org/D124244

Files:
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/lib/StaticAnalyzer/Checkers/StoreToImmutableChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/cert/ModelConstQualifiedReturnChecker.cpp
  clang/test/Analysis/analyzer-enabled-checkers.c
  clang/test/Analysis/cert/env30-c.cpp
  clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c

Index: clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
===
--- clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
+++ clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
@@ -32,6 +32,7 @@
 // CHECK-NEXT: core.NullDereference
 // CHECK-NEXT: core.StackAddrEscapeBase
 // CHECK-NEXT: core.StackAddressEscape
+// CHECK-NEXT: core.StoreToImmutable
 // CHECK-NEXT: core.UndefinedBinaryOperatorResult
 // CHECK-NEXT: core.VLASize
 // CHECK-NEXT: core.builtin.BuiltinFunctions
Index: clang/test/Analysis/cert/env30-c.cpp
===
--- /dev/null
+++ clang/test/Analysis/cert/env30-c.cpp
@@ -0,0 +1,213 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:  -analyzer-checker=core.StoreToImmutable,alpha.security.cert.env.ModelConstQualifiedReturn \
+// RUN:  -analyzer-output=text -verify -Wno-unused %s
+
+#include "../Inputs/system-header-simulator.h"
+char *getenv(const char *name);
+char *setlocale(int category, const char *locale);
+char *strerror(int errnum);
+int setenv(const char *name, const char *value, int overwrite);
+void free(void *memblock);
+void *malloc(size_t size);
+char *strdup(const char *s);
+
+typedef struct {
+} tm;
+char *asctime(const tm *timeptr);
+
+int strcmp(const char *, const char *);
+void non_const_parameter_function(char *e);
+void const_parameter_function(const char *);
+
+void getenv_test1() {
+  char *p = getenv("VAR");
+  // expected-note@-1{{return value of 'getenv' should be treated as const-qualified}}
+  *p = 'A';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToImmutable]}}
+  // expected-note@-2{{modifying immutable memory}}
+}
+
+void getenv_test2() {
+  char *p;
+
+  p = getenv("VAR");
+  non_const_parameter_function(p); // FIXME: Maybe we should warn for these.
+}
+
+void getenv_test3() {
+  char *p;
+  p = getenv("VAR");
+  const_parameter_function(p); // no-warning
+}
+
+void modify(char *p) {
+  *p = 'A';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToImmutable]}}
+  // expected-note@-2{{modifying immutable memory}}
+}
+
+void getenv_test4() {
+  char *p = getenv("VAR");
+  // expected-note@-1{{return value of 'getenv' should be treated as const-qualified}}
+  char *pp = p;
+  modify(pp); // Writing to immutable region within the call.
+  // expected-note@-1{{Calling 'modify'}}
+}
+
+void does_not_modify(char *p) {
+  *p;
+}
+
+void getenv_test5() {
+  char *p = getenv("VAR");
+  does_not_modify(p); // no-warning
+}
+
+void getenv_test6() {
+  static char *array[] = {0};
+
+  if (!array[0]) {
+// expected-note@-1{{Taking true branch}}
+array[0] = getenv("TEMPDIR");
+// expected-note@-1{{return value of 'getenv' should be treated as const-qualified}}
+  }
+
+  *array[0] = 'A';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToImmutable]}}
+  // expected-note@-2{{modifying immutable memory}}
+}
+
+void getenv_test7() {
+  char *p = getenv("VAR");
+  // expected-note@-1{{return value of 'getenv' should be treated as const-qualified}}
+  if (!p)
+// expected-note@-1{{Assuming 'p' is non-null}}
+// expected-note@-2{{Taking false branch}}
+return;
+  p[0] = '\0';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToImmutable]}}
+  // expected-note@-2{{modifying immutable memory}}
+}
+
+void setlocale_test() {
+  char *p = setlocale(0, "VAR");
+  // expected-note@-1{{return value of 'setlocale' should be treated as const-qualified}}
+  *p = 'A';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToImmutable]}}
+  // expected-note@-2{{modifying immutable memory}}
+}
+
+void strerror_test() {
+  char *p = strerror(0);
+  // expected-note@-1{{return value of 'strerror' should be treated as const-qualified}}
+  *p = 'A';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToImmutable]}}
+  // expected-note@-2{{modifying immutable memory}}
+}
+
+void asctime_test() {
+  const tm *t;
+  char *p = asctime(t);
+  // expected-note@-1{{return value of 'asctime' should be treated as const-qualified}}
+
+  *p = 'A';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToImmutable]}}
+  // 

[PATCH] D124240: [clangd][NFC] Reduce memory usage while building dex

2022-04-22 Thread Kadir Cetinkaya 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 rG2efccf5166f4: [clangd][NFC] Reduce memory usage while 
building dex (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124240

Files:
  clang-tools-extra/clangd/index/dex/Dex.cpp


Index: clang-tools-extra/clangd/index/dex/Dex.cpp
===
--- clang-tools-extra/clangd/index/dex/Dex.cpp
+++ clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -13,14 +13,19 @@
 #include "URI.h"
 #include "index/Index.h"
 #include "index/dex/Iterator.h"
+#include "index/dex/Token.h"
 #include "index/dex/Trigram.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include 
 #include 
+#include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -76,23 +81,38 @@
   }
 
   // Assemble the final compressed posting lists for the added symbols.
-  llvm::DenseMap build() {
+  llvm::DenseMap build() && {
 llvm::DenseMap Result(/*InitialReserve=*/
   TrigramDocs.size() +
   RestrictedCCDocs.size() +
   TypeDocs.size() +
   ScopeDocs.size() +
   ProximityDocs.size());
-for (const auto  : TrigramDocs)
+// Tear down intermediate structs as we go to reduce memory usage.
+// Since we're trying to get rid of underlying allocations, clearing the
+// containers is not enough.
+auto CreatePostingList =
+[](Token::Kind TK, llvm::StringMap> ) {
+  for (auto  : Docs) {
+Result.try_emplace(Token(TK, E.first()), E.second);
+E.second = {};
+  }
+  Docs = {};
+};
+CreatePostingList(Token::Kind::Type, TypeDocs);
+CreatePostingList(Token::Kind::Scope, ScopeDocs);
+CreatePostingList(Token::Kind::ProximityURI, ProximityDocs);
+
+// TrigramDocs are stored in a DenseMap and RestrictedCCDocs is not even a
+// map, treat them specially.
+for (auto  : TrigramDocs) {
   Result.try_emplace(Token(Token::Kind::Trigram, E.first.str()), E.second);
-for (const auto  : TypeDocs)
-  Result.try_emplace(Token(Token::Kind::Type, E.first()), E.second);
-for (const auto  : ScopeDocs)
-  Result.try_emplace(Token(Token::Kind::Scope, E.first()), E.second);
-for (const auto  : ProximityDocs)
-  Result.try_emplace(Token(Token::Kind::ProximityURI, E.first()), 
E.second);
+  E.second = {};
+}
+TrigramDocs = llvm::DenseMap>{};
 if (!RestrictedCCDocs.empty())
-  Result.try_emplace(RestrictedForCodeCompletion, RestrictedCCDocs);
+  Result.try_emplace(RestrictedForCodeCompletion,
+ std::move(RestrictedCCDocs));
 return Result;
   }
 };
@@ -125,7 +145,7 @@
   IndexBuilder Builder;
   for (DocID SymbolRank = 0; SymbolRank < Symbols.size(); ++SymbolRank)
 Builder.add(*Symbols[SymbolRank], SymbolRank);
-  InvertedIndex = Builder.build();
+  InvertedIndex = std::move(Builder).build();
 }
 
 std::unique_ptr Dex::iterator(const Token ) const {


Index: clang-tools-extra/clangd/index/dex/Dex.cpp
===
--- clang-tools-extra/clangd/index/dex/Dex.cpp
+++ clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -13,14 +13,19 @@
 #include "URI.h"
 #include "index/Index.h"
 #include "index/dex/Iterator.h"
+#include "index/dex/Token.h"
 #include "index/dex/Trigram.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include 
 #include 
+#include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -76,23 +81,38 @@
   }
 
   // Assemble the final compressed posting lists for the added symbols.
-  llvm::DenseMap build() {
+  llvm::DenseMap build() && {
 llvm::DenseMap Result(/*InitialReserve=*/
   TrigramDocs.size() +
   RestrictedCCDocs.size() +
   TypeDocs.size() +
   ScopeDocs.size() +
   ProximityDocs.size());
-for (const auto  : TrigramDocs)
+// Tear down intermediate structs as we go to reduce memory usage.
+// Since we're trying to get rid of underlying allocations, clearing the
+// containers is not enough.
+auto CreatePostingList =

[PATCH] D124240: [clangd][NFC] Reduce memory usage while building dex

2022-04-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 424489.
kadircet marked 2 inline comments as done.
kadircet added a comment.

Copy-assign to empty containers rather than clear.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124240

Files:
  clang-tools-extra/clangd/index/dex/Dex.cpp


Index: clang-tools-extra/clangd/index/dex/Dex.cpp
===
--- clang-tools-extra/clangd/index/dex/Dex.cpp
+++ clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -13,14 +13,19 @@
 #include "URI.h"
 #include "index/Index.h"
 #include "index/dex/Iterator.h"
+#include "index/dex/Token.h"
 #include "index/dex/Trigram.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include 
 #include 
+#include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -76,23 +81,38 @@
   }
 
   // Assemble the final compressed posting lists for the added symbols.
-  llvm::DenseMap build() {
+  llvm::DenseMap build() && {
 llvm::DenseMap Result(/*InitialReserve=*/
   TrigramDocs.size() +
   RestrictedCCDocs.size() +
   TypeDocs.size() +
   ScopeDocs.size() +
   ProximityDocs.size());
-for (const auto  : TrigramDocs)
+// Tear down intermediate structs as we go to reduce memory usage.
+// Since we're trying to get rid of underlying allocations, clearing the
+// containers is not enough.
+auto CreatePostingList =
+[](Token::Kind TK, llvm::StringMap> ) {
+  for (auto  : Docs) {
+Result.try_emplace(Token(TK, E.first()), E.second);
+E.second = {};
+  }
+  Docs = {};
+};
+CreatePostingList(Token::Kind::Type, TypeDocs);
+CreatePostingList(Token::Kind::Scope, ScopeDocs);
+CreatePostingList(Token::Kind::ProximityURI, ProximityDocs);
+
+// TrigramDocs are stored in a DenseMap and RestrictedCCDocs is not even a
+// map, treat them specially.
+for (auto  : TrigramDocs) {
   Result.try_emplace(Token(Token::Kind::Trigram, E.first.str()), E.second);
-for (const auto  : TypeDocs)
-  Result.try_emplace(Token(Token::Kind::Type, E.first()), E.second);
-for (const auto  : ScopeDocs)
-  Result.try_emplace(Token(Token::Kind::Scope, E.first()), E.second);
-for (const auto  : ProximityDocs)
-  Result.try_emplace(Token(Token::Kind::ProximityURI, E.first()), 
E.second);
+  E.second = {};
+}
+TrigramDocs = llvm::DenseMap>{};
 if (!RestrictedCCDocs.empty())
-  Result.try_emplace(RestrictedForCodeCompletion, RestrictedCCDocs);
+  Result.try_emplace(RestrictedForCodeCompletion,
+ std::move(RestrictedCCDocs));
 return Result;
   }
 };
@@ -125,7 +145,7 @@
   IndexBuilder Builder;
   for (DocID SymbolRank = 0; SymbolRank < Symbols.size(); ++SymbolRank)
 Builder.add(*Symbols[SymbolRank], SymbolRank);
-  InvertedIndex = Builder.build();
+  InvertedIndex = std::move(Builder).build();
 }
 
 std::unique_ptr Dex::iterator(const Token ) const {


Index: clang-tools-extra/clangd/index/dex/Dex.cpp
===
--- clang-tools-extra/clangd/index/dex/Dex.cpp
+++ clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -13,14 +13,19 @@
 #include "URI.h"
 #include "index/Index.h"
 #include "index/dex/Iterator.h"
+#include "index/dex/Token.h"
 #include "index/dex/Trigram.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include 
 #include 
+#include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -76,23 +81,38 @@
   }
 
   // Assemble the final compressed posting lists for the added symbols.
-  llvm::DenseMap build() {
+  llvm::DenseMap build() && {
 llvm::DenseMap Result(/*InitialReserve=*/
   TrigramDocs.size() +
   RestrictedCCDocs.size() +
   TypeDocs.size() +
   ScopeDocs.size() +
   ProximityDocs.size());
-for (const auto  : TrigramDocs)
+// Tear down intermediate structs as we go to reduce memory usage.
+// Since we're trying to get rid of underlying allocations, clearing the
+// containers is not enough.
+auto CreatePostingList =
+[](Token::Kind TK, llvm::StringMap> ) {
+  for (auto  : 

  1   2   >