[libunwind] e83eb23 - [libunwind] Fix a -Wextra-semi warning

2023-09-29 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2023-09-29T15:10:05-07:00
New Revision: e83eb23a2cff061adba41aae5d7304674c87c306

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

LOG: [libunwind] Fix a -Wextra-semi warning

Added: 


Modified: 
libunwind/src/FrameHeaderCache.hpp

Removed: 




diff  --git a/libunwind/src/FrameHeaderCache.hpp 
b/libunwind/src/FrameHeaderCache.hpp
index e1754cb6e1e676a..296064d8e2e6759 100644
--- a/libunwind/src/FrameHeaderCache.hpp
+++ b/libunwind/src/FrameHeaderCache.hpp
@@ -31,8 +31,8 @@
 
 class _LIBUNWIND_HIDDEN FrameHeaderCache {
   struct CacheEntry {
-uintptr_t LowPC() { return Info.dso_base; };
-uintptr_t HighPC() { return Info.dso_base + Info.text_segment_length; };
+uintptr_t LowPC() { return Info.dso_base; }
+uintptr_t HighPC() { return Info.dso_base + Info.text_segment_length; }
 UnwindInfoSections Info;
 CacheEntry *Next;
   };



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


[libunwind] b29b6cc - Revert "[libunwind] Relax a REQUIRES on a test that passes on FreeBSD"

2023-09-26 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2023-09-26T07:15:39-07:00
New Revision: b29b6ccc4e5abb301a8bab037069f0a9b097b247

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

LOG: Revert "[libunwind] Relax a REQUIRES on a test that passes on FreeBSD"

While it worked for me locally, it appears to be failing on the
FreeBSD 13 buildbot.

This reverts commit ab7896231e176e52801702b7221bcac2f4ffbd59.

Added: 


Modified: 
libunwind/test/forceunwind.pass.cpp

Removed: 




diff  --git a/libunwind/test/forceunwind.pass.cpp 
b/libunwind/test/forceunwind.pass.cpp
index 265b2ec6a49a469..8c26551b6d0b678 100644
--- a/libunwind/test/forceunwind.pass.cpp
+++ b/libunwind/test/forceunwind.pass.cpp
@@ -7,7 +7,7 @@
 //
 
//===--===//
 
-// REQUIRES: linux || freebsd
+// REQUIRES: linux
 
 // TODO: Figure out why this fails with Memory Sanitizer.
 // XFAIL: msan



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


[libunwind] f958381 - [libunwind] Clarify comment added in #67205

2023-09-25 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2023-09-25T15:04:23-07:00
New Revision: f9583815e7e9bd5d57ef27232e6cbbc426e03824

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

LOG: [libunwind] Clarify comment added in #67205

See https://github.com/llvm/llvm-project/pull/67205#issuecomment-1734443684

Added: 


Modified: 
libunwind/test/configs/llvm-libunwind-merged.cfg.in
libunwind/test/configs/llvm-libunwind-shared.cfg.in
libunwind/test/configs/llvm-libunwind-static.cfg.in

Removed: 




diff  --git a/libunwind/test/configs/llvm-libunwind-merged.cfg.in 
b/libunwind/test/configs/llvm-libunwind-merged.cfg.in
index 624caec987e15b2..38b79840c9fe282 100644
--- a/libunwind/test/configs/llvm-libunwind-merged.cfg.in
+++ b/libunwind/test/configs/llvm-libunwind-merged.cfg.in
@@ -11,7 +11,7 @@ link_flags = []
 if @LIBUNWIND_ENABLE_CET@:
 compile_flags.append('-fcf-protection=full')
 
-# On ELF platforms, add -Wl,--export-dynamic if supported by the linker.
+# On ELF platforms, link tests with -Wl,--export-dynamic if supported by the 
linker.
 if len('@CMAKE_EXE_EXPORTS_CXX_FLAG@'):
 link_flags.append('@CMAKE_EXE_EXPORTS_CXX_FLAG@')
 

diff  --git a/libunwind/test/configs/llvm-libunwind-shared.cfg.in 
b/libunwind/test/configs/llvm-libunwind-shared.cfg.in
index bd7a153ac6d1d54..13896aeb13bc4a9 100644
--- a/libunwind/test/configs/llvm-libunwind-shared.cfg.in
+++ b/libunwind/test/configs/llvm-libunwind-shared.cfg.in
@@ -10,7 +10,7 @@ link_flags = []
 if @LIBUNWIND_ENABLE_CET@:
 compile_flags.append('-fcf-protection=full')
 
-# On ELF platforms, add -Wl,--export-dynamic if supported by the linker.
+# On ELF platforms, link tests with -Wl,--export-dynamic if supported by the 
linker.
 if len('@CMAKE_EXE_EXPORTS_CXX_FLAG@'):
 link_flags.append('@CMAKE_EXE_EXPORTS_CXX_FLAG@')
 

diff  --git a/libunwind/test/configs/llvm-libunwind-static.cfg.in 
b/libunwind/test/configs/llvm-libunwind-static.cfg.in
index 5956c32cc625b2b..50b64dc665a5af5 100644
--- a/libunwind/test/configs/llvm-libunwind-static.cfg.in
+++ b/libunwind/test/configs/llvm-libunwind-static.cfg.in
@@ -13,7 +13,7 @@ if @LIBUNWIND_ENABLE_THREADS@:
 if @LIBUNWIND_ENABLE_CET@:
 compile_flags.append('-fcf-protection=full')
 
-# On ELF platforms, add -Wl,--export-dynamic if supported by the linker.
+# On ELF platforms, link tests with -Wl,--export-dynamic if supported by the 
linker.
 if len('@CMAKE_EXE_EXPORTS_CXX_FLAG@'):
 link_flags.append('@CMAKE_EXE_EXPORTS_CXX_FLAG@')
 



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


[libunwind] ab78962 - [libunwind] Relax a REQUIRES on a test that passes on FreeBSD

2023-09-22 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2023-09-22T16:16:16-07:00
New Revision: ab7896231e176e52801702b7221bcac2f4ffbd59

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

LOG: [libunwind] Relax a REQUIRES on a test that passes on FreeBSD

Added: 


Modified: 
libunwind/test/forceunwind.pass.cpp

Removed: 




diff  --git a/libunwind/test/forceunwind.pass.cpp 
b/libunwind/test/forceunwind.pass.cpp
index 8c26551b6d0b678..265b2ec6a49a469 100644
--- a/libunwind/test/forceunwind.pass.cpp
+++ b/libunwind/test/forceunwind.pass.cpp
@@ -7,7 +7,7 @@
 //
 
//===--===//
 
-// REQUIRES: linux
+// REQUIRES: linux || freebsd
 
 // TODO: Figure out why this fails with Memory Sanitizer.
 // XFAIL: msan



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


[clang] c4c2352 - [ASTContext] Avoid duplicating address space map. NFCI

2022-12-16 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2022-12-16T11:28:19Z
New Revision: c4c23527d6c919bfd781fae0f7a82b9271b6429e

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

LOG: [ASTContext] Avoid duplicating address space map. NFCI

ASTContext was holding onto a pointer to the Clang->LLVM address space map
which is stored inside TargetInfo. Instead of doing this, we can forward to
TargetInfo instead. This change will allow us to eventually remove
getTargetAddressSpace() from ASTContext and only have this information in
TargetInfo.

Reviewed By: rjmccall

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

Added: 


Modified: 
clang/include/clang/AST/ASTContext.h
clang/lib/AST/ASTContext.cpp
clang/lib/Basic/TargetInfo.cpp

Removed: 




diff  --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 64cdd63db009f..f45c84406d2a2 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -613,9 +613,6 @@ class ASTContext : public RefCountedBase {
   std::unique_ptr ABI;
   CXXABI *createCXXABI(const TargetInfo &T);
 
-  /// The logical -> physical address space map.
-  const LangASMap *AddrSpaceMap = nullptr;
-
   /// Address space map mangling must be used with language specific
   /// address spaces (e.g. OpenCL/CUDA)
   bool AddrSpaceMapMangling;

diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 8887789555afb..c2491f872a58e 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -930,39 +930,6 @@ ParentMapContext &ASTContext::getParentMapContext() {
   return *ParentMapCtx.get();
 }
 
-static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
-   const LangOptions &LOpts) {
-  if (LOpts.FakeAddressSpaceMap) {
-// The fake address space map must have a distinct entry for each
-// language-specific address space.
-static const unsigned FakeAddrSpaceMap[] = {
-0,  // Default
-1,  // opencl_global
-3,  // opencl_local
-2,  // opencl_constant
-0,  // opencl_private
-4,  // opencl_generic
-5,  // opencl_global_device
-6,  // opencl_global_host
-7,  // cuda_device
-8,  // cuda_constant
-9,  // cuda_shared
-1,  // sycl_global
-5,  // sycl_global_device
-6,  // sycl_global_host
-3,  // sycl_local
-0,  // sycl_private
-10, // ptr32_sptr
-11, // ptr32_uptr
-12, // ptr64
-13, // hlsl_groupshared
-};
-return &FakeAddrSpaceMap;
-  } else {
-return &T.getAddressSpaceMap();
-  }
-}
-
 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
   const LangOptions &LangOpts) {
   switch (LangOpts.getAddressSpaceMapMangling()) {
@@ -1293,7 +1260,6 @@ void ASTContext::InitBuiltinTypes(const TargetInfo 
&Target,
   this->AuxTarget = AuxTarget;
 
   ABI.reset(createCXXABI(Target));
-  AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
   AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
 
   // C99 6.2.5p19.
@@ -12244,10 +12210,7 @@ uint64_t 
ASTContext::getTargetNullPointerValue(QualType QT) const {
 }
 
 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
-  if (isTargetAddressSpace(AS))
-return toTargetAddressSpace(AS);
-  else
-return (*AddrSpaceMap)[(unsigned)AS];
+  return getTargetInfo().getTargetAddressSpace(AS);
 }
 
 bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {

diff  --git a/clang/lib/Basic/TargetInfo.cpp b/clang/lib/Basic/TargetInfo.cpp
index f735f58c7b8c2..45e2f4a7a5dad 100644
--- a/clang/lib/Basic/TargetInfo.cpp
+++ b/clang/lib/Basic/TargetInfo.cpp
@@ -24,6 +24,30 @@
 using namespace clang;
 
 static const LangASMap DefaultAddrSpaceMap = {0};
+// The fake address space map must have a distinct entry for each
+// language-specific address space.
+static const LangASMap FakeAddrSpaceMap = {
+0,  // Default
+1,  // opencl_global
+3,  // opencl_local
+2,  // opencl_constant
+0,  // opencl_private
+4,  // opencl_generic
+5,  // opencl_global_device
+6,  // opencl_global_host
+7,  // cuda_device
+8,  // cuda_constant
+9,  // cuda_shared
+1,  // sycl_global
+5,  // sycl_global_device
+6,  // sycl_global_host
+3,  // sycl_local
+0,  // sycl_private
+10, // ptr32_sptr
+11, // ptr32_uptr
+12, // ptr64
+13, // hlsl_groupshared
+};
 
 // TargetInfo Constructor.
 TargetInfo::TargetInfo(const llvm::Triple &T) : Triple(T) {
@@ -487,6 +511,9 @@ void TargetInfo::adjust(DiagnosticsEngine &Diags, 
LangOptions &Opts) {
 
   if (Opts.MaxBitIntWidth)
 MaxBitIntWidth = Opt

[clang] 5131f44 - Simplify clang/test/CodeGen/annotations-global.c CHECK lines

2022-12-08 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2022-12-08T20:44:40Z
New Revision: 5131f444ee7045d58f72fc99e2ac69792e8b7158

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

LOG: Simplify clang/test/CodeGen/annotations-global.c CHECK lines

There is no need to run FileCheck 5 times, we can use CHECK-DAG instead.

Added: 


Modified: 
clang/test/CodeGen/annotations-global.c

Removed: 




diff  --git a/clang/test/CodeGen/annotations-global.c 
b/clang/test/CodeGen/annotations-global.c
index 49791094a76d..d6e6f7de8a95 100644
--- a/clang/test/CodeGen/annotations-global.c
+++ b/clang/test/CodeGen/annotations-global.c
@@ -1,10 +1,4 @@
-// RUN: %clang_cc1 %s -emit-llvm -o -
-// RUN: %clang_cc1 %s -emit-llvm -o %t1
-// RUN: FileCheck --check-prefix=FOO %s < %t1
-// RUN: FileCheck --check-prefix=A %s < %t1
-// RUN: FileCheck --check-prefix=BAR %s < %t1
-// RUN: FileCheck --check-prefix=FOOS %s < %t1
-// RUN: FileCheck --check-prefix=ADDRSPACE %s < %t1
+// RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s 
--implicit-check-not='section "llvm.metadata"'
 // RUN: %clang_cc1 %s -triple r600 -emit-llvm -o - | FileCheck %s 
--check-prefix AS1-GLOBALS
 // END.
 
@@ -19,34 +13,36 @@ void __attribute((annotate("ann_a_0"))) 
__attribute((annotate("ann_a_1"))) a(cha
 
 __attribute((address_space(1))) __attribute__((annotate("addrspace1_ann"))) 
char addrspace1_var;
 
-// FOOS: target triple
-// FOOS: private unnamed_addr constant [7 x i8] c"sfoo_{{.}}\00", section 
"llvm.metadata"
-// FOOS: private unnamed_addr constant [7 x i8] c"sfoo_{{.}}\00", section 
"llvm.metadata"
-// FOOS-NOT: sfoo_
-// FOOS: @llvm.global.annotations = appending global [11 x { ptr, ptr, ptr, 
i32, ptr }] {{.*}}ptr @sfoo{{.*}}ptr @sfoo{{.*}}, section "llvm.metadata"
-
-// FOO: target triple
-// FOO: private unnamed_addr constant [6 x i8] c"foo_{{.}}\00", section 
"llvm.metadata"
-// FOO: private unnamed_addr constant [6 x i8] c"foo_{{.}}\00", section 
"llvm.metadata"
-// FOO-NOT: foo_
-// FOO: @llvm.global.annotations = appending global [11 x { ptr, ptr, ptr, 
i32, ptr }] {{.*}}ptr @foo{{.*}}ptr @foo{{.*}}, section "llvm.metadata"
-
-// A: target triple
-// A: private unnamed_addr constant [8 x i8] c"ann_a_{{.}}\00", section 
"llvm.metadata"
-// A: private unnamed_addr constant [8 x i8] c"ann_a_{{.}}\00", section 
"llvm.metadata"
-// A: private unnamed_addr constant [8 x i8] c"ann_a_{{.}}\00", section 
"llvm.metadata"
-// A: private unnamed_addr constant [8 x i8] c"ann_a_{{.}}\00", section 
"llvm.metadata"
-// A-NOT: ann_a_
-// A: @llvm.global.annotations = appending global [11 x { ptr, ptr, ptr, i32, 
ptr }] {{.*}}ptr @a{{.*}}ptr @a{{.*}}ptr @a{{.*}}ptr @a{{.*}}, section 
"llvm.metadata"
-
-// BAR: target triple
-// BAR: private unnamed_addr constant [6 x i8] c"bar_{{.}}\00", section 
"llvm.metadata"
-// BAR: private unnamed_addr constant [6 x i8] c"bar_{{.}}\00", section 
"llvm.metadata"
-// BAR-NOT: bar_
-// BAR: @llvm.global.annotations = appending global [11 x { ptr, ptr, ptr, 
i32, ptr }] {{.*}}ptr @a.bar{{.*}}ptr @a.bar{{.*}}, section "llvm.metadata"
-
-// ADDRSPACE: target triple
-// ADDRSPACE: @llvm.global.annotations = appending global {{.*}} addrspacecast 
(ptr addrspace(1) @addrspace1_var to ptr), {{.*}}
+// CHECK: target triple
+// CHECK-DAG: private unnamed_addr constant [7 x i8] c"sfoo_0\00", section 
"llvm.metadata"
+// CHECK-DAG: private unnamed_addr constant [7 x i8] c"sfoo_1\00", section 
"llvm.metadata"
+
+// CHECK-DAG: private unnamed_addr constant [6 x i8] c"foo_0\00", section 
"llvm.metadata"
+// CHECK-DAG: private unnamed_addr constant [6 x i8] c"foo_1\00", section 
"llvm.metadata"
+
+// CHECK-DAG: private unnamed_addr constant [8 x i8] c"ann_a_0\00", section 
"llvm.metadata"
+// CHECK-DAG: private unnamed_addr constant [8 x i8] c"ann_a_1\00", section 
"llvm.metadata"
+// CHECK-DAG: private unnamed_addr constant [8 x i8] c"ann_a_2\00", section 
"llvm.metadata"
+// CHECK-DAG: private unnamed_addr constant [8 x i8] c"ann_a_3\00", section 
"llvm.metadata"
+
+// CHECK-DAG: private unnamed_addr constant [6 x i8] c"bar_0\00", section 
"llvm.metadata"
+// CHECK-DAG: private unnamed_addr constant [6 x i8] c"bar_1\00", section 
"llvm.metadata"
+
+// CHECK-DAG: private unnamed_addr constant [15 x i8] c"addrspace1_ann\00", 
section "llvm.metadata"
+
+// CHECK: @llvm.global.annotations = appending global [11 x { ptr, ptr, ptr, 
i32, ptr }] [{
+// CHECK-SAME: { ptr @a.bar,
+// CHECK-SAME: { ptr @a.bar,
+// CHECK-SAME: { ptr @a,
+// CHECK-SAME: { ptr @a,
+// CHECK-SAME: { ptr @a,
+// CHECK-SAME: { ptr @a,
+// CHECK-SAME: { ptr @sfoo,
+// CHECK-SAME: { ptr @sfoo,
+// CHECK-SAME: { ptr @foo,
+// CHECK-SAME: { ptr @foo,
+// CHECK-SAME: { ptr addrspacecast (ptr addrspace(1) @addrspace1_var to ptr),
+// CHECK-SAME: }], section "llvm.met

[clang] 121a89f - Fix annotations-field.c CHECK lines being ignored

2022-12-08 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2022-12-08T20:44:40Z
New Revision: 121a89fc2aedf48ca4aee43288b67e27b71e72ed

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

LOG: Fix annotations-field.c CHECK lines being ignored

Pointed out by @jrtc27 in https://reviews.llvm.org/D138722.

Added: 


Modified: 
clang/test/CodeGen/annotations-field.c

Removed: 




diff  --git a/clang/test/CodeGen/annotations-field.c 
b/clang/test/CodeGen/annotations-field.c
index 2815c1dd849d1..e40b409ce272c 100644
--- a/clang/test/CodeGen/annotations-field.c
+++ b/clang/test/CodeGen/annotations-field.c
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -triple x86_64 -emit-llvm -o - %s | FileCheck %s 
'-D$MANGLE_AS=p0' '-D$CONST_AS=' --check-prefix=X86
-// RUN: %clang_cc1 -triple amdgcn -emit-llvm -o - %s | FileCheck %s 
'-D$MANGLE_AS=p4' '-D$CONST_AS= addrspace(4)' --check-prefix=AMDGPU
+// RUN: %clang_cc1 -triple x86_64 -emit-llvm -o - %s | FileCheck %s 
'-D$MANGLE_AS=p0' '-D$CONST_AS=' --check-prefixes=CHECK,X86
+// RUN: %clang_cc1 -triple amdgcn -emit-llvm -o - %s | FileCheck %s 
'-D$MANGLE_AS=p4' '-D$CONST_AS= addrspace(4)' --check-prefixes=CHECK,AMDGPU
 // END.
 
 // CHECK: private unnamed_addr[[$CONST_AS]] constant [8 x i8] 
c"v_ann_{{.}}\00", section "llvm.metadata"



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


[clang] 9114ac6 - Overload all llvm.annotation intrinsics for globals argument

2022-12-07 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2022-12-07T18:29:18Z
New Revision: 9114ac67a986400155b8b82013d09a9e4f48e534

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

LOG: Overload all llvm.annotation intrinsics for globals argument

The global constant arguments could be in a different address space
than the first argument, so we have to add another overloaded argument.
This patch was originally made for CHERI LLVM (where globals can be in
address space 200), but it also appears to be useful for in-tree targets
as can be seen from the test diffs.

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

Added: 


Modified: 
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/CodeGen/CodeGenFunction.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/CodeGen/CodeGenTypeCache.h
clang/test/CodeGen/annotations-field.c
clang/test/CodeGen/annotations-global.c
clang/test/CodeGen/annotations-loc.c
clang/test/CodeGen/annotations-var.c
clang/test/CodeGenCXX/attr-annotate.cpp
clang/test/CodeGenCXX/attr-annotate2.cpp
clang/test/CodeGenSYCL/field-annotate-addr-space.cpp
llvm/include/llvm/IR/Intrinsics.td
llvm/lib/IR/AutoUpgrade.cpp
llvm/test/Analysis/CostModel/X86/free-intrinsics.ll
llvm/test/Analysis/CostModel/free-intrinsics-datalayout.ll
llvm/test/Analysis/CostModel/free-intrinsics-no_info.ll
llvm/test/Analysis/ScalarEvolution/annotation-intrinsics.ll
llvm/test/Assembler/opaque-ptr-intrinsic-remangling.ll
llvm/test/Bitcode/upgrade-annotation.ll
llvm/test/Bitcode/upgrade-ptr-annotation.ll
llvm/test/Bitcode/upgrade-var-annotation.ll
llvm/test/Transforms/InstCombine/annotation-intrinsic.ll
llvm/test/Transforms/InstCombine/assume_inevitable.ll

Removed: 




diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 186a6f57bae7a..88ffe7552b907 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -4258,8 +4258,9 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
   }
   case Builtin::BI__builtin_annotation: {
 llvm::Value *AnnVal = EmitScalarExpr(E->getArg(0));
-llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::annotation,
-  AnnVal->getType());
+llvm::Function *F =
+CGM.getIntrinsic(llvm::Intrinsic::annotation,
+ {AnnVal->getType(), CGM.ConstGlobalsPtrTy});
 
 // Get the annotation string, go through casts. Sema requires this to be a
 // non-wide string literal, potentially casted, so the cast<> is safe.

diff  --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index e589b6ef8e959..a84f12938bc0c 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -2460,8 +2460,10 @@ llvm::Value 
*CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
  const AnnotateAttr *Attr) {
   SmallVector Args = {
   AnnotatedVal,
-  Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), 
Int8PtrTy),
-  Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
+  Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr),
+ConstGlobalsPtrTy),
+  Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location),
+ConstGlobalsPtrTy),
   CGM.EmitAnnotationLineNo(Location),
   };
   if (Attr)
@@ -2473,9 +2475,12 @@ void CodeGenFunction::EmitVarAnnotations(const VarDecl 
*D, llvm::Value *V) {
   assert(D->hasAttr() && "no annotate attribute");
   // FIXME We create a new bitcast for every annotation because that's what
   // llvm-gcc was doing.
+  unsigned AS = V->getType()->getPointerAddressSpace();
+  llvm::Type *I8PtrTy = Builder.getInt8PtrTy(AS);
   for (const auto *I : D->specific_attrs())
-EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
-   Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
+EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation,
+{I8PtrTy, CGM.ConstGlobalsPtrTy}),
+   Builder.CreateBitCast(V, I8PtrTy, V->getName()),
I->getAnnotation(), D->getLocation(), I);
 }
 
@@ -2488,8 +2493,8 @@ Address CodeGenFunction::EmitFieldAnnotations(const 
FieldDecl *D,
   unsigned AS = PTy ? PTy->getAddressSpace() : 0;
   llvm::PointerType *IntrinTy =
   llvm::PointerType::getWithSamePointeeType(CGM.Int8PtrTy, AS);
-  llvm::Function *F =
-  CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, IntrinTy);
+  llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
+

[clang] f3a17d0 - [clang] Avoid duplicating ProgramAddressSpace in TargetInfo. NFCI

2022-12-01 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2022-12-01T20:40:58Z
New Revision: f3a17d059509c133d8d90d305c0b40bdcbfc1fef

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

LOG: [clang] Avoid duplicating ProgramAddressSpace in TargetInfo. NFCI

This value was added to clang/Basic in D111566, but is only used during
codegen, where we can use the LLVM IR DataLayout instead. I noticed this
because the downstream CHERI targets would have to also set this value
for AArch64/RISC-V/MIPS. Instead of duplicating more information between
LLVM IR and Clang, this patch moves getTargetAddressSpace(QualType T) to
CodeGenTypes, where we can consult the DataLayout.

Reviewed By: rjmccall

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

Added: 


Modified: 
clang/include/clang/AST/ASTContext.h
clang/include/clang/Basic/TargetInfo.h
clang/lib/AST/ASTContext.cpp
clang/lib/Basic/TargetInfo.cpp
clang/lib/Basic/Targets/AVR.h
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CGDebugInfo.cpp
clang/lib/CodeGen/CGDeclCXX.cpp
clang/lib/CodeGen/CGExpr.cpp
clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/CodeGen/CodeGenTypes.cpp
clang/lib/CodeGen/CodeGenTypes.h

Removed: 




diff  --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 6f695f096857f..d7f538c136daf 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2810,8 +2810,6 @@ class ASTContext : public RefCountedBase {
   /// long double and double on AArch64 will return 0).
   int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const;
 
-  unsigned getTargetAddressSpace(QualType T) const;
-
   unsigned getTargetAddressSpace(LangAS AS) const;
 
   LangAS getLangASForBuiltinAddressSpace(unsigned AS) const;

diff  --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 38fd0f6405dfc..f010c559dc3e4 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -232,7 +232,6 @@ class TargetInfo : public virtual TransferrableTargetInfo,
   unsigned char RegParmMax, SSERegParmMax;
   TargetCXXABI TheCXXABI;
   const LangASMap *AddrSpaceMap;
-  unsigned ProgramAddrSpace;
 
   mutable StringRef PlatformName;
   mutable VersionTuple PlatformMinVersion;
@@ -822,9 +821,6 @@ class TargetInfo : public virtual TransferrableTargetInfo,
 return getTypeWidth(IntMaxType);
   }
 
-  /// Return the address space for functions for the given target.
-  unsigned getProgramAddressSpace() const { return ProgramAddrSpace; }
-
   // Return the size of unwind_word for this target.
   virtual unsigned getUnwindWordWidth() const {
 return getPointerWidth(LangAS::Default);

diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 464a386b09c3c..3c5d47fd964f3 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -12227,16 +12227,6 @@ uint64_t 
ASTContext::getTargetNullPointerValue(QualType QT) const {
   return getTargetInfo().getNullPointerValue(AS);
 }
 
-unsigned ASTContext::getTargetAddressSpace(QualType T) const {
-  // Return the address space for the type. If the type is a
-  // function type without an address space qualifier, the
-  // program address space is used. Otherwise, the target picks
-  // the best address space based on the type information
-  return T->isFunctionType() && !T.hasAddressSpace()
- ? getTargetInfo().getProgramAddressSpace()
- : getTargetAddressSpace(T.getAddressSpace());
-}
-
 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
   if (isTargetAddressSpace(AS))
 return toTargetAddressSpace(AS);

diff  --git a/clang/lib/Basic/TargetInfo.cpp b/clang/lib/Basic/TargetInfo.cpp
index 8def4be51016b..f735f58c7b8c2 100644
--- a/clang/lib/Basic/TargetInfo.cpp
+++ b/clang/lib/Basic/TargetInfo.cpp
@@ -155,8 +155,6 @@ TargetInfo::TargetInfo(const llvm::Triple &T) : Triple(T) {
   MaxOpenCLWorkGroupSize = 1024;
 
   MaxBitIntWidth.reset();
-
-  ProgramAddrSpace = 0;
 }
 
 // Out of line virtual dtor for TargetInfo.

diff  --git a/clang/lib/Basic/Targets/AVR.h b/clang/lib/Basic/Targets/AVR.h
index 272afdfc03884..8b42144999751 100644
--- a/clang/lib/Basic/Targets/AVR.h
+++ b/clang/lib/Basic/Targets/AVR.h
@@ -55,7 +55,6 @@ class LLVM_LIBRARY_VISIBILITY AVRTargetInfo : public 
TargetInfo {
 Int16Type = SignedInt;
 Char32Type = UnsignedLong;
 SigAtomicType = SignedChar;
-ProgramAddrSpace = 1;
 resetDataLayout("e-P1-p:16:8-i8:8-i16:8-i32:8-i64:8-f32:8-f64:8-n8-a:8");
   }
 

diff  --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index be788ad0d8687..0f410a8daae66 100644
--- a/clang/lib/CodeGen/CGCall.

[clang] a602f76 - [clang][TargetInfo] Use LangAS for getPointer{Width,Align}()

2022-11-30 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2022-11-30T20:24:01Z
New Revision: a602f76a2406cc3edd6b297ede3583b26513a34c

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

LOG: [clang][TargetInfo] Use LangAS for getPointer{Width,Align}()

Mixing LLVM and Clang address spaces can result in subtle bugs, and there
is no need for this hook to use the LLVM IR level address spaces.
Most of this change is just replacing zero with LangAS::Default,
but it also allows us to remove a few calls to getTargetAddressSpace().

This also removes a stale comment+workaround in
CGDebugInfo::CreatePointerLikeType(): ASTContext::getTypeSize() does
return the expected size for ReferenceType (and handles address spaces).

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

Added: 


Modified: 
clang/include/clang/Basic/TargetInfo.h
clang/lib/AST/ASTContext.cpp
clang/lib/AST/ItaniumCXXABI.cpp
clang/lib/AST/Mangle.cpp
clang/lib/AST/MicrosoftCXXABI.cpp
clang/lib/AST/MicrosoftMangle.cpp
clang/lib/AST/RecordLayoutBuilder.cpp
clang/lib/AST/VTableBuilder.cpp
clang/lib/Basic/Targets/AMDGPU.cpp
clang/lib/Basic/Targets/AMDGPU.h
clang/lib/Basic/Targets/Mips.cpp
clang/lib/Basic/Targets/NVPTX.cpp
clang/lib/Basic/Targets/X86.h
clang/lib/CodeGen/CGBlocks.cpp
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CGDebugInfo.cpp
clang/lib/CodeGen/CGExprAgg.cpp
clang/lib/CodeGen/CGObjCGNU.cpp
clang/lib/CodeGen/CGObjCMac.cpp
clang/lib/CodeGen/CGVTables.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/CodeGen/ItaniumCXXABI.cpp
clang/lib/CodeGen/MicrosoftCXXABI.cpp
clang/lib/CodeGen/PatternInit.cpp
clang/lib/CodeGen/SwiftCallingConv.cpp
clang/lib/CodeGen/TargetInfo.cpp
clang/lib/Frontend/InitPreprocessor.cpp
clang/lib/Sema/SemaChecking.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaType.cpp
clang/lib/StaticAnalyzer/Checkers/ObjCContainersASTChecker.cpp
clang/unittests/CodeGen/TestCompiler.h

Removed: 




diff  --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 0ebe67abe3a69..38fd0f6405dfc 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -357,10 +357,11 @@ class TargetInfo : public virtual TransferrableTargetInfo,
   IntType getUIntMaxType() const {
 return getCorrespondingUnsignedType(IntMaxType);
   }
-  IntType getPtrDiffType(unsigned AddrSpace) const {
-return AddrSpace == 0 ? PtrDiffType : getPtrDiffTypeV(AddrSpace);
+  IntType getPtrDiffType(LangAS AddrSpace) const {
+return AddrSpace == LangAS::Default ? PtrDiffType
+: getPtrDiffTypeV(AddrSpace);
   }
-  IntType getUnsignedPtrDiffType(unsigned AddrSpace) const {
+  IntType getUnsignedPtrDiffType(LangAS AddrSpace) const {
 return getCorrespondingUnsignedType(getPtrDiffType(AddrSpace));
   }
   IntType getIntPtrType() const { return IntPtrType; }
@@ -438,11 +439,13 @@ class TargetInfo : public virtual TransferrableTargetInfo,
 
   /// Return the width of pointers on this target, for the
   /// specified address space.
-  uint64_t getPointerWidth(unsigned AddrSpace) const {
-return AddrSpace == 0 ? PointerWidth : getPointerWidthV(AddrSpace);
+  uint64_t getPointerWidth(LangAS AddrSpace) const {
+return AddrSpace == LangAS::Default ? PointerWidth
+: getPointerWidthV(AddrSpace);
   }
-  uint64_t getPointerAlign(unsigned AddrSpace) const {
-return AddrSpace == 0 ? PointerAlign : getPointerAlignV(AddrSpace);
+  uint64_t getPointerAlign(LangAS AddrSpace) const {
+return AddrSpace == LangAS::Default ? PointerAlign
+: getPointerAlignV(AddrSpace);
   }
 
   /// Return the maximum width of pointers on this target.
@@ -604,7 +607,8 @@ class TargetInfo : public virtual TransferrableTargetInfo,
 
   /// Determine whether the __int128 type is supported on this target.
   virtual bool hasInt128Type() const {
-return (getPointerWidth(0) >= 64) || getTargetOpts().ForceEnableInt128;
+return (getPointerWidth(LangAS::Default) >= 64) ||
+   getTargetOpts().ForceEnableInt128;
   } // FIXME
 
   /// Determine whether the _BitInt type is supported on this target. This
@@ -822,7 +826,9 @@ class TargetInfo : public virtual TransferrableTargetInfo,
   unsigned getProgramAddressSpace() const { return ProgramAddrSpace; }
 
   // Return the size of unwind_word for this target.
-  virtual unsigned getUnwindWordWidth() const { return getPointerWidth(0); }
+  virtual unsigned getUnwindWordWidth() const {
+return getPointerWidth(LangAS::Default);
+  }
 
   ///

[clang] 54ad4d2 - Drop redundant pipe to opt -instnamer in clang tests

2022-11-25 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2022-11-25T11:34:55Z
New Revision: 54ad4d2dd1526c53c3647eee26f8ecc2ff63f30c

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

LOG: Drop redundant pipe to opt -instnamer in clang tests

This used to be required, but the difference between asserts/!asserts
builds no longer exists for %clang_cc1 (only for %clang), so they pass
just fine without this flag.

Added: 


Modified: 
clang/test/CodeGen/X86/avx512-kconstraints-att_inline_asm.c
clang/test/CodeGen/catch-undef-behavior.c
clang/test/CodeGen/exceptions-seh-leave.c
clang/test/CodeGen/fp-atomic-ops.c
clang/test/CodeGenCXX/catch-undef-behavior.cpp
clang/test/CodeGenCXX/for-range-temporaries.cpp
clang/test/CodeGenOpenCL/atomic-ops.cl
clang/test/CodeGenOpenCL/convergent.cl

Removed: 




diff  --git a/clang/test/CodeGen/X86/avx512-kconstraints-att_inline_asm.c 
b/clang/test/CodeGen/X86/avx512-kconstraints-att_inline_asm.c
index be7be25d84af5..b4939bfc2ca83 100644
--- a/clang/test/CodeGen/X86/avx512-kconstraints-att_inline_asm.c
+++ b/clang/test/CodeGen/X86/avx512-kconstraints-att_inline_asm.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 %s -O0 -ffreestanding -triple=x86_64-apple-darwin 
-target-cpu skylake-avx512 -emit-llvm -o - -Wall -Werror | opt 
-passes=instnamer -S | FileCheck %s
+// RUN: %clang_cc1 %s -O0 -ffreestanding -triple=x86_64-apple-darwin 
-target-cpu skylake-avx512 -emit-llvm -o - -Wall -Werror | FileCheck %s
 // This test checks validity of att\gcc style inline assmebly for avx512 k and 
Yk constraints.
 // Also checks mask register allows flexible type (size <= 64 bit)
 

diff  --git a/clang/test/CodeGen/catch-undef-behavior.c 
b/clang/test/CodeGen/catch-undef-behavior.c
index c2035b030f0a2..9f511d54f458c 100644
--- a/clang/test/CodeGen/catch-undef-behavior.c
+++ b/clang/test/CodeGen/catch-undef-behavior.c
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -no-opaque-pointers 
-fsanitize=alignment,null,object-size,shift-base,shift-exponent,return,signed-integer-overflow,vla-bound,float-cast-overflow,integer-divide-by-zero,bool,returns-nonnull-attribute,nonnull-attribute
 
-fsanitize-recover=alignment,null,object-size,shift-base,shift-exponent,signed-integer-overflow,vla-bound,float-cast-overflow,integer-divide-by-zero,bool,returns-nonnull-attribute,nonnull-attribute
 -emit-llvm %s -o - -triple x86_64-linux-gnu | opt -passes=instnamer -S | 
FileCheck %s --check-prefix=CHECK-COMMON --check-prefix=CHECK-UBSAN
-// RUN: %clang_cc1 -no-opaque-pointers 
-fsanitize-trap=alignment,null,object-size,shift-base,shift-exponent,return,signed-integer-overflow,vla-bound,float-cast-overflow,integer-divide-by-zero,bool,returns-nonnull-attribute,nonnull-attribute
 
-fsanitize-recover=alignment,null,object-size,shift-base,shift-exponent,signed-integer-overflow,vla-bound,float-cast-overflow,integer-divide-by-zero,bool,returns-nonnull-attribute,nonnull-attribute
 
-fsanitize=alignment,null,object-size,shift-base,shift-exponent,return,signed-integer-overflow,vla-bound,float-cast-overflow,integer-divide-by-zero,bool,returns-nonnull-attribute,nonnull-attribute
 
-fsanitize-recover=alignment,null,object-size,shift-base,shift-exponent,signed-integer-overflow,vla-bound,float-cast-overflow,integer-divide-by-zero,bool,returns-nonnull-attribute,nonnull-attribute
 -emit-llvm %s -o - -triple x86_64-linux-gnu | opt -passes=instnamer -S | 
FileCheck %s --check-prefix=CHECK-COMMON --check-prefix=CHECK-TRAP
+// RUN: %clang_cc1 -no-opaque-pointers 
-fsanitize=alignment,null,object-size,shift-base,shift-exponent,return,signed-integer-overflow,vla-bound,float-cast-overflow,integer-divide-by-zero,bool,returns-nonnull-attribute,nonnull-attribute
 
-fsanitize-recover=alignment,null,object-size,shift-base,shift-exponent,signed-integer-overflow,vla-bound,float-cast-overflow,integer-divide-by-zero,bool,returns-nonnull-attribute,nonnull-attribute
 -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s 
--check-prefix=CHECK-COMMON --check-prefix=CHECK-UBSAN
+// RUN: %clang_cc1 -no-opaque-pointers 
-fsanitize-trap=alignment,null,object-size,shift-base,shift-exponent,return,signed-integer-overflow,vla-bound,float-cast-overflow,integer-divide-by-zero,bool,returns-nonnull-attribute,nonnull-attribute
 
-fsanitize-recover=alignment,null,object-size,shift-base,shift-exponent,signed-integer-overflow,vla-bound,float-cast-overflow,integer-divide-by-zero,bool,returns-nonnull-attribute,nonnull-attribute
 
-fsanitize=alignment,null,object-size,shift-base,shift-exponent,return,signed-integer-overflow,vla-bound,float-cast-overflow,integer-divide-by-zero,bool,returns-nonnull-attribute,nonnull-attribute
 
-fsanitize-recover=alignment,null,object-size,shift-base,shift-exponent,signed-integer-overflow,vla-bound,float-cast-overflow,integer-div

[clang] 64f5fed - [ASTContext][NFC] Remove getTargetAddressSpace(Qualifiers Q)

2022-11-23 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2022-11-23T09:04:42Z
New Revision: 64f5fedb59e82a79c0c669c3d6591ca9eadb82fb

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

LOG: [ASTContext][NFC] Remove getTargetAddressSpace(Qualifiers Q)

This simply calls getTargetAddressSpace(Q.getAddressSpace()) and there
are only two callers, so adjust those caller instead.

Added: 


Modified: 
clang/include/clang/AST/ASTContext.h
clang/lib/AST/ASTContext.cpp
clang/lib/CodeGen/CodeGenTypes.cpp

Removed: 




diff  --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 2a21f2d1f37ee..6f695f096857f 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2812,8 +2812,6 @@ class ASTContext : public RefCountedBase {
 
   unsigned getTargetAddressSpace(QualType T) const;
 
-  unsigned getTargetAddressSpace(Qualifiers Q) const;
-
   unsigned getTargetAddressSpace(LangAS AS) const;
 
   LangAS getLangASForBuiltinAddressSpace(unsigned AS) const;

diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index b9f9bec39317a..e887f44b3ca0b 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -12234,11 +12234,7 @@ unsigned ASTContext::getTargetAddressSpace(QualType T) 
const {
   // the best address space based on the type information
   return T->isFunctionType() && !T.hasAddressSpace()
  ? getTargetInfo().getProgramAddressSpace()
- : getTargetAddressSpace(T.getQualifiers());
-}
-
-unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const {
-  return getTargetAddressSpace(Q.getAddressSpace());
+ : getTargetAddressSpace(T.getAddressSpace());
 }
 
 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {

diff  --git a/clang/lib/CodeGen/CodeGenTypes.cpp 
b/clang/lib/CodeGen/CodeGenTypes.cpp
index 05956c2c1ec69..3869285e0b2cb 100644
--- a/clang/lib/CodeGen/CodeGenTypes.cpp
+++ b/clang/lib/CodeGen/CodeGenTypes.cpp
@@ -772,10 +772,10 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) {
 // Block pointers lower to function type. For function type,
 // getTargetAddressSpace() returns default address space for
 // function pointer i.e. program address space. Therefore, for block
-// pointers, it is important to pass qualifiers when calling
-// getTargetAddressSpace(), to ensure that we get the address space
-// for data pointers and not function pointers.
-unsigned AS = Context.getTargetAddressSpace(FTy.getQualifiers());
+// pointers, it is important to pass the pointee AST address space when
+// calling getTargetAddressSpace(), to ensure that we get the LLVM IR
+// address space for data pointers and not function pointers.
+unsigned AS = Context.getTargetAddressSpace(FTy.getAddressSpace());
 ResultType = llvm::PointerType::get(PointeeType, AS);
 break;
   }



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


[clang] 0745b0c - Fix incorrect cast in VisitSYCLUniqueStableNameExpr

2022-11-19 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2022-11-19T11:43:17Z
New Revision: 0745b0c0354a0c8e1fefb68a3876d15db6c2e27a

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

LOG: Fix incorrect cast in VisitSYCLUniqueStableNameExpr

Clang language-level address spaces and LLVM pointer address spaces are
not the same thing (even though they will both have a numeric value of
zero in many cases). LangAS is a enum class to avoid implicit conversions,
but eba69b59d1a30dead07da2c279c8ecfd2b62ba9f avoided the compiler error by
adding a `static_cast<>`. While touching this code, simplify it by using
CreatePointerBitCastOrAddrSpaceCast() which is already a no-op if the types
match.

This changes the code generation for spir64 to place the globals in
the sycl_global addreds space, which maps to `addrspace(1)`.

Reviewed By: bader

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

Added: 


Modified: 
clang/lib/CodeGen/CGExprScalar.cpp
clang/test/CodeGenSYCL/unique_stable_name.cpp
clang/test/CodeGenSYCL/unique_stable_name_windows_diff.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 7b1337b1be68c..a5f14de42c8ed 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -1630,21 +1630,14 @@ Value *ScalarExprEmitter::VisitExpr(Expr *E) {
 Value *
 ScalarExprEmitter::VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E) {
   ASTContext &Context = CGF.getContext();
-  llvm::Optional GlobalAS =
-  Context.getTargetInfo().getConstantAddressSpace();
+  unsigned AddrSpace =
+  Context.getTargetAddressSpace(CGF.CGM.GetGlobalConstantAddressSpace());
   llvm::Constant *GlobalConstStr = Builder.CreateGlobalStringPtr(
-  E->ComputeName(Context), "__usn_str",
-  static_cast(GlobalAS.value_or(LangAS::Default)));
+  E->ComputeName(Context), "__usn_str", AddrSpace);
 
-  unsigned ExprAS = Context.getTargetAddressSpace(E->getType());
-
-  if (GlobalConstStr->getType()->getPointerAddressSpace() == ExprAS)
-return GlobalConstStr;
-
-  llvm::PointerType *PtrTy = 
cast(GlobalConstStr->getType());
-  llvm::PointerType *NewPtrTy =
-  llvm::PointerType::getWithSamePointeeType(PtrTy, ExprAS);
-  return Builder.CreateAddrSpaceCast(GlobalConstStr, NewPtrTy, 
"usn_addr_cast");
+  llvm::Type *ExprTy = ConvertType(E->getType());
+  return Builder.CreatePointerBitCastOrAddrSpaceCast(GlobalConstStr, ExprTy,
+ "usn_addr_cast");
 }
 
 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {

diff  --git a/clang/test/CodeGenSYCL/unique_stable_name.cpp 
b/clang/test/CodeGenSYCL/unique_stable_name.cpp
index d346d3ab407f5..b4e16f4ab1457 100644
--- a/clang/test/CodeGenSYCL/unique_stable_name.cpp
+++ b/clang/test/CodeGenSYCL/unique_stable_name.cpp
@@ -1,22 +1,22 @@
 // RUN: %clang_cc1 -no-opaque-pointers -triple 
spir64-unknown-unknown-sycldevice -fsycl-is-device -disable-llvm-passes 
-emit-llvm %s -o - | FileCheck %s
-// CHECK: @[[LAMBDA_KERNEL3:[^\w]+]] = private unnamed_addr constant 
[[LAMBDA_K3_SIZE:\[[0-9]+ x i8\]]] c"_ZTSZ4mainEUlPZ4mainEUlvE_E_\00"
-// CHECK: @[[INT1:[^\w]+]] = private unnamed_addr constant [[INT_SIZE:\[[0-9]+ 
x i8\]]] c"_ZTSi\00"
-// CHECK: @[[STRING:[^\w]+]] = private unnamed_addr constant 
[[STRING_SIZE:\[[0-9]+ x i8\]]] c"_ZTSAppL_ZZ4mainE1jE_i\00",
-// CHECK: @[[INT2:[^\w]+]] = private unnamed_addr constant [[INT_SIZE]] 
c"_ZTSi\00"
-// CHECK: @[[LAMBDA_X:[^\w]+]] = private unnamed_addr constant 
[[LAMBDA_X_SIZE:\[[0-9]+ x i8\]]] c"_ZTSZZ4mainENKUlvE0_clEvEUlvE_\00"
-// CHECK: @[[MACRO_X:[^\w]+]] = private unnamed_addr constant 
[[MACRO_SIZE:\[[0-9]+ x i8\]]] c"_ZTSZZ4mainENKUlvE0_clEvEUlvE0_\00"
-// CHECK: @[[MACRO_Y:[^\w]+]] =  private unnamed_addr constant [[MACRO_SIZE]] 
c"_ZTSZZ4mainENKUlvE0_clEvEUlvE1_\00"
-// CHECK: @{{.*}} = private unnamed_addr constant [32 x i8] 
c"_ZTSZZ4mainENKUlvE0_clEvEUlvE2_\00", align 1
-// CHECK: @{{.*}} = private unnamed_addr constant [32 x i8] 
c"_ZTSZZ4mainENKUlvE0_clEvEUlvE3_\00", align 1
-// CHECK: @[[MACRO_MACRO_X:[^\w]+]] = private unnamed_addr constant 
[[MACRO_MACRO_SIZE:\[[0-9]+ x i8\]]] c"_ZTSZZ4mainENKUlvE0_clEvEUlvE4_\00"
-// CHECK: @[[MACRO_MACRO_Y:[^\w]+]] = private unnamed_addr constant 
[[MACRO_MACRO_SIZE]] c"_ZTSZZ4mainENKUlvE0_clEvEUlvE5_\00"
-// CHECK: @[[INT3:[^\w]+]] = private unnamed_addr constant [[INT_SIZE]] 
c"_ZTSi\00"
-// CHECK: @[[LAMBDA:[^\w]+]] = private unnamed_addr constant 
[[LAMBDA_SIZE:\[[0-9]+ x i8\]]] c"_ZTSZZ4mainENKUlvE0_clEvEUlvE_\00"
-// CHECK: @[[LAMBDA_IN_DEP_INT:[^\w]+]] = private unnamed_addr constant 
[[DEP_INT_SIZE:\[[0-9]+ x i8\]]] 
c"_ZTSZ28lambda_in_dependent_functionIiEvvEUlvE_\00",
-// CHECK: @[[LAMBDA_IN_DEP_X:[^\w]+]] = p

[clang] 00b1f7a - Use TI.hasBuiltinAtomic() when setting ATOMIC_*_LOCK_FREE values. NFCI

2022-11-15 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2022-11-15T12:42:19Z
New Revision: 00b1f7a6ab2aecd2309e2faebde18a11309c6181

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

LOG: Use TI.hasBuiltinAtomic() when setting ATOMIC_*_LOCK_FREE values. NFCI

I noticed that the values for __{CLANG,GCC}_ATOMIC_POINTER_LOCK_FREE were
incorrectly set to 1 instead of two in downstream CHERI targets because
pointers are handled specially there. While fixing this downstream, I
noticed that the existing code could be refactored to use
TargetInfo::hasBuiltinAtomic instead of repeating the almost identical
logic. In theory there could be a difference here since hasBuiltinAtomic() also
returns true for types less than 1 char in size, but since
InitializePredefinedMacros() never passes such a value this change should
not introduce any functional changes.

Reviewed By: rprichard, efriedma

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

Added: 


Modified: 
clang/lib/Frontend/InitPreprocessor.cpp

Removed: 




diff  --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 8e0a42c644799..bdff0bd04f290 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -299,12 +299,12 @@ static void DefineFastIntType(unsigned TypeWidth, bool 
IsSigned,
 
 /// Get the value the ATOMIC_*_LOCK_FREE macro should have for a type with
 /// the specified properties.
-static const char *getLockFreeValue(unsigned TypeWidth, unsigned InlineWidth) {
+static const char *getLockFreeValue(unsigned TypeWidth, const TargetInfo &TI) {
   // Fully-aligned, power-of-2 sizes no larger than the inline
   // width will be inlined as lock-free operations.
   // Note: we do not need to check alignment since _Atomic(T) is always
   // appropriately-aligned in clang.
-  if ((TypeWidth & (TypeWidth - 1)) == 0 && TypeWidth <= InlineWidth)
+  if (TI.hasBuiltinAtomic(TypeWidth, TypeWidth))
 return "2"; // "always lock free"
   // We cannot be certain what operations the lib calls might be
   // able to implement as lock-free on future processors.
@@ -1150,11 +1150,9 @@ static void InitializePredefinedMacros(const TargetInfo 
&TI,
 
   auto addLockFreeMacros = [&](const llvm::Twine &Prefix) {
 // Used by libc++ and libstdc++ to implement ATOMIC__LOCK_FREE.
-unsigned InlineWidthBits = TI.getMaxAtomicInlineWidth();
 #define DEFINE_LOCK_FREE_MACRO(TYPE, Type) 
\
   Builder.defineMacro(Prefix + #TYPE "_LOCK_FREE", 
\
-  getLockFreeValue(TI.get##Type##Width(),  
\
-   InlineWidthBits));
+  getLockFreeValue(TI.get##Type##Width(), TI));
 DEFINE_LOCK_FREE_MACRO(BOOL, Bool);
 DEFINE_LOCK_FREE_MACRO(CHAR, Char);
 if (LangOpts.Char8)
@@ -1167,8 +1165,7 @@ static void InitializePredefinedMacros(const TargetInfo 
&TI,
 DEFINE_LOCK_FREE_MACRO(LONG, Long);
 DEFINE_LOCK_FREE_MACRO(LLONG, LongLong);
 Builder.defineMacro(Prefix + "POINTER_LOCK_FREE",
-getLockFreeValue(TI.getPointerWidth(0),
- InlineWidthBits));
+getLockFreeValue(TI.getPointerWidth(0), TI));
 #undef DEFINE_LOCK_FREE_MACRO
   };
   addLockFreeMacros("__CLANG_ATOMIC_");



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


[libunwind] 8df257a - [libunwind] Ensure test/libunwind_01.pass is not completely inlined

2022-06-20 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2022-06-20T09:05:49Z
New Revision: 8df257a6d0b0b32e05e89874eff4c8ddd2a2a2a9

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

LOG: [libunwind] Ensure test/libunwind_01.pass is not completely inlined

By adding noinline and calling fprintf before returning we ensure that
every function will have a distinct call frame and that the return address
will always be saved instead of saving the target in main as the result.

Before this change all backtraces were always backtrace -> main -> _start,
i.e. always exactly three entries. This happenend because all calls were
inlined in main() and the test just happenend to pass because there is at
least _start before main.

I found this while fixing some bugs in libunwind for CHERI and noticed that
the test was passing even though the code was completely broken.

Obtained from: https://github.com/CTSRD-CHERI/llvm-project

Reviewed By: #libunwind, ldionne, MaskRay

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

Added: 


Modified: 
libunwind/test/libunwind_01.pass.cpp

Removed: 




diff  --git a/libunwind/test/libunwind_01.pass.cpp 
b/libunwind/test/libunwind_01.pass.cpp
index bbfaffd153cc2..4661ac9df8219 100644
--- a/libunwind/test/libunwind_01.pass.cpp
+++ b/libunwind/test/libunwind_01.pass.cpp
@@ -15,6 +15,7 @@
 
 #include 
 #include 
+#include 
 #include 
 
 void backtrace(int lower_bound) {
@@ -24,9 +25,17 @@ void backtrace(int lower_bound) {
   unw_cursor_t cursor;
   unw_init_local(&cursor, &context);
 
+  char buffer[1024];
+  unw_word_t offset = 0;
+
   int n = 0;
   do {
-++n;
+n++;
+if (unw_get_proc_name(&cursor, buffer, sizeof(buffer), &offset) == 0) {
+  fprintf(stderr, "Frame %d: %s+%p\n", n, buffer, (void*)offset);
+} else {
+  fprintf(stderr, "Frame %d: Could not get name for cursor\n", n);
+}
 if (n > 100) {
   abort();
 }
@@ -37,18 +46,24 @@ void backtrace(int lower_bound) {
   }
 }
 
-void test1(int i) {
+__attribute__((noinline)) void test1(int i) {
+  fprintf(stderr, "starting %s\n", __func__);
   backtrace(i);
+  fprintf(stderr, "finished %s\n", __func__); // ensure return address is saved
 }
 
-void test2(int i, int j) {
+__attribute__((noinline)) void test2(int i, int j) {
+  fprintf(stderr, "starting %s\n", __func__);
   backtrace(i);
   test1(j);
+  fprintf(stderr, "finished %s\n", __func__); // ensure return address is saved
 }
 
-void test3(int i, int j, int k) {
+__attribute__((noinline)) void test3(int i, int j, int k) {
+  fprintf(stderr, "starting %s\n", __func__);
   backtrace(i);
   test2(j, k);
+  fprintf(stderr, "finished %s\n", __func__); // ensure return address is saved
 }
 
 void test_no_info() {
@@ -142,9 +157,9 @@ void test_fpreg_get_set() {}
 #endif
 
 int main(int, char**) {
-  test1(1);
-  test2(1, 2);
-  test3(1, 2, 3);
+  test1(3);
+  test2(3, 4);
+  test3(3, 4, 5);
   test_no_info();
   test_reg_names();
   test_reg_get_set();



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


[clang] a181819 - [NFC][clang] Add a CHECK lines to tests checking offsetof-like expressions

2021-09-28 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2021-09-28T17:57:36+01:00
New Revision: a18181931f991b04caea297e723db415756f09a0

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

LOG: [NFC][clang] Add a CHECK lines to tests checking offsetof-like expressions

I am looking at constant-folding changes that could affect these tests, so
check that it emits the expected global value instead of just checking
that it doesn't crash.

Added: 


Modified: 
clang/test/CodeGen/2005-01-02-ConstantInits.c
clang/test/CodeGenCXX/2005-01-03-StaticInitializers.cpp
clang/test/CodeGenCXX/2008-05-07-CrazyOffsetOf.cpp

Removed: 




diff  --git a/clang/test/CodeGen/2005-01-02-ConstantInits.c 
b/clang/test/CodeGen/2005-01-02-ConstantInits.c
index d85f5198650d..fca10041dec8 100644
--- a/clang/test/CodeGen/2005-01-02-ConstantInits.c
+++ b/clang/test/CodeGen/2005-01-02-ConstantInits.c
@@ -1,10 +1,24 @@
-// RUN: %clang_cc1 %s -emit-llvm -o -
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --function-signature --check-globals --global-value-regex "@.+"
+// RUN: %clang_cc1 -triple=x86_64-unknown-linux %s -emit-llvm -o - | FileCheck 
%s
 
 // This tests all kinds of hard cases with initializers and
 // array subscripts.  This corresponds to PR487.
 
 struct X { int a[2]; };
 
+//.
+// CHECK: @test.i23 = internal global i32 4, align 4
+// CHECK: @i = global i32 4, align 4
+// CHECK: @Arr = global [100 x i32] zeroinitializer, align 16
+// CHECK: @foo2.X = internal global i32* bitcast (i8* getelementptr (i8, i8* 
bitcast ([100 x i32]* @Arr to i8*), i64 196) to i32*), align 8
+// CHECK: @foo2.i23 = internal global i32 0, align 4
+//.
+// CHECK-LABEL: define {{[^@]+}}@test
+// CHECK-SAME: () #[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = load i32, i32* @test.i23, align 4
+// CHECK-NEXT:ret i32 [[TMP0]]
+//
 int test() {
   static int i23 = (int) &(((struct X *)0)->a[1]);
   return i23;
@@ -14,11 +28,40 @@ int i = (int) &( ((struct X *)0) -> a[1]);
 
 int Arr[100];
 
+// CHECK-LABEL: define {{[^@]+}}@foo
+// CHECK-SAME: (i32 [[I:%.*]]) #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[I_ADDR:%.*]] = alloca i32, align 4
+// CHECK-NEXT:store i32 [[I]], i32* [[I_ADDR]], align 4
+// CHECK-NEXT:[[CALL:%.*]] = call i32 (i32*, ...) bitcast (i32 (...)* @bar 
to i32 (i32*, ...)*)(i32* getelementptr inbounds ([100 x i32], [100 x i32]* 
@Arr, i64 0, i64 49))
+// CHECK-NEXT:[[TMP0:%.*]] = load i32, i32* [[I_ADDR]], align 4
+// CHECK-NEXT:[[IDXPROM:%.*]] = sext i32 [[TMP0]] to i64
+// CHECK-NEXT:[[ARRAYIDX:%.*]] = getelementptr inbounds [100 x i32], [100 
x i32]* @Arr, i64 0, i64 [[IDXPROM]]
+// CHECK-NEXT:[[CALL1:%.*]] = call i32 (i32*, ...) bitcast (i32 (...)* 
@bar to i32 (i32*, ...)*)(i32* [[ARRAYIDX]])
+// CHECK-NEXT:[[ADD:%.*]] = add nsw i32 [[CALL]], [[CALL1]]
+// CHECK-NEXT:ret i32 [[ADD]]
+//
 int foo(int i) { return bar(&Arr[49])+bar(&Arr[i]); }
-int foo2(int i) { 
+// CHECK-LABEL: define {{[^@]+}}@foo2
+// CHECK-SAME: (i32 [[I:%.*]]) #[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[I_ADDR:%.*]] = alloca i32, align 4
+// CHECK-NEXT:[[P:%.*]] = alloca i32*, align 8
+// CHECK-NEXT:store i32 [[I]], i32* [[I_ADDR]], align 4
+// CHECK-NEXT:store i32* getelementptr inbounds ([100 x i32], [100 x i32]* 
@Arr, i64 0, i64 0), i32** [[P]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = load i32*, i32** [[P]], align 8
+// CHECK-NEXT:[[INCDEC_PTR:%.*]] = getelementptr inbounds i32, i32* 
[[TMP0]], i32 1
+// CHECK-NEXT:store i32* [[INCDEC_PTR]], i32** [[P]], align 8
+// CHECK-NEXT:[[TMP1:%.*]] = load i32, i32* [[I_ADDR]], align 4
+// CHECK-NEXT:[[IDX_EXT:%.*]] = sext i32 [[TMP1]] to i64
+// CHECK-NEXT:[[ADD_PTR:%.*]] = getelementptr inbounds i32, i32* 
getelementptr inbounds ([100 x i32], [100 x i32]* @Arr, i64 0, i64 0), i64 
[[IDX_EXT]]
+// CHECK-NEXT:[[CALL:%.*]] = call i32 (i32*, ...) bitcast (i32 (...)* @bar 
to i32 (i32*, ...)*)(i32* [[ADD_PTR]])
+// CHECK-NEXT:ret i32 [[CALL]]
+//
+int foo2(int i) {
   static const int *X = &Arr[49];
static int i23 = (int) &( ((struct X *)0) -> a[0]);
   int *P = Arr;
   ++P;
   return bar(Arr+i);
-}
+}
\ No newline at end of file

diff  --git a/clang/test/CodeGenCXX/2005-01-03-StaticInitializers.cpp 
b/clang/test/CodeGenCXX/2005-01-03-StaticInitializers.cpp
index 1c9d1202afb2..b8078d88a3f7 100644
--- a/clang/test/CodeGenCXX/2005-01-03-StaticInitializers.cpp
+++ b/clang/test/CodeGenCXX/2005-01-03-StaticInitializers.cpp
@@ -1,9 +1,9 @@
-// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s
-// REQUIRES: LP64
+// RUN: %clang_cc1 -triple=x86_64-linux-gnu -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple=i386-linux-gnu -emit-llvm 

[clang] 90179f2 - [NFC] Add a comment to member-function-pointer-calls.cpp

2021-09-28 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2021-09-28T17:57:36+01:00
New Revision: 90179f2323ac4ca0ed28ee94b9a61b565c1b61b6

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

LOG: [NFC] Add a comment to member-function-pointer-calls.cpp

Looking at this test I did not see why MinGW was using a different command
line until I looked at the git history. Add a comment explaining what this
RUN line is actually testing. Also add two more RUN lines to show that
indirectly passed member pointers don't inhibit the optimization.

Added: 


Modified: 
clang/test/CodeGenCXX/member-function-pointer-calls.cpp

Removed: 




diff  --git a/clang/test/CodeGenCXX/member-function-pointer-calls.cpp 
b/clang/test/CodeGenCXX/member-function-pointer-calls.cpp
index f2e485bf15a55..24d70b3309cd5 100644
--- a/clang/test/CodeGenCXX/member-function-pointer-calls.cpp
+++ b/clang/test/CodeGenCXX/member-function-pointer-calls.cpp
@@ -1,6 +1,10 @@
 // RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -O3 
-fno-experimental-new-pass-manager  -o - | FileCheck %s
 // RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -O3 
-fexperimental-new-pass-manager  -o - | FileCheck %s
+/// Check that we pass the member pointers indirectly for MinGW64
 // RUN: %clang_cc1 %s -triple=x86_64-windows-gnu -emit-llvm -o - | FileCheck 
%s -check-prefix MINGW64
+/// We should be able to optimize calls via the indirectly passed member 
pointers
+// RUN: %clang_cc1 %s -triple=x86_64-windows-gnu -emit-llvm -O3 
-fno-experimental-new-pass-manager  -o - | FileCheck %s
+// RUN: %clang_cc1 %s -triple=x86_64-windows-gnu -emit-llvm -O3 
-fexperimental-new-pass-manager  -o - | FileCheck %s
 struct A {
   virtual int vf1() { return 1; }
   virtual int vf2() { return 2; }



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


[clang] d5631d4 - Drop REQUIRES: arm-registered-target from an IR-only test

2021-09-28 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2021-09-28T17:57:36+01:00
New Revision: d5631d49d070116ba2e23baad1ecf5f4cc08e6d1

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

LOG: Drop REQUIRES: arm-registered-target from an IR-only test

This works just fine even if the Arm backend is not built.

Added: 


Modified: 
clang/test/CodeGen/struct-init.c

Removed: 




diff  --git a/clang/test/CodeGen/struct-init.c 
b/clang/test/CodeGen/struct-init.c
index 30834acec736..cc88769801ef 100644
--- a/clang/test/CodeGen/struct-init.c
+++ b/clang/test/CodeGen/struct-init.c
@@ -1,5 +1,4 @@
-// REQUIRES: arm-registered-target
-// RUN: %clang_cc1 -S -triple armv7-apple-darwin -target-feature +neon %s 
-emit-llvm -o - | FileCheck %s
+// RUN: %clang_cc1 -triple armv7-apple-darwin -target-feature +neon %s 
-emit-llvm -o - | FileCheck %s
 
 typedef struct _zend_ini_entry zend_ini_entry;
 struct _zend_ini_entry {



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


[clang] 6d7b3d6 - Fix CLANG_ENABLE_STATIC_ANALYZER=OFF building all analyzer source

2021-09-20 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2021-09-20T12:55:56+01:00
New Revision: 6d7b3d6b3a8dbd62650b6c3dae1fe904a8ae9048

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

LOG: Fix CLANG_ENABLE_STATIC_ANALYZER=OFF building all analyzer source

Since https://reviews.llvm.org/D87118, the StaticAnalyzer directory is
added unconditionally. In theory this should not cause the static analyzer
sources to be built unless they are referenced by another target. However,
the clang-cpp target (defined in clang/tools/clang-shlib) uses the
CLANG_STATIC_LIBS global property to determine which libraries need to
be included. To solve this issue, this patch avoids adding libraries to
that property if EXCLUDE_FROM_ALL is set.

In case something like this comes up again: `cmake --graphviz=targets.dot`
is quite useful to see why a target is included as part of `ninja all`.

Reviewed By: thakis

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

Added: 


Modified: 
clang/cmake/modules/AddClang.cmake
clang/lib/StaticAnalyzer/CMakeLists.txt
llvm/cmake/modules/AddLLVM.cmake

Removed: 




diff  --git a/clang/cmake/modules/AddClang.cmake 
b/clang/cmake/modules/AddClang.cmake
index 5752f4277444..c2d46b743b85 100644
--- a/clang/cmake/modules/AddClang.cmake
+++ b/clang/cmake/modules/AddClang.cmake
@@ -100,7 +100,12 @@ macro(add_clang_library name)
   # The Xcode generator doesn't handle object libraries correctly.
   list(APPEND LIBTYPE OBJECT)
 endif()
-set_property(GLOBAL APPEND PROPERTY CLANG_STATIC_LIBS ${name})
+if (NOT EXCLUDE_FROM_ALL)
+  # Only include libraries that don't have EXCLUDE_FROM_ALL set. This
+  # ensure that the clang static analyzer libraries are not compiled
+  # as part of clang-shlib if CLANG_ENABLE_STATIC_ANALYZER=OFF.
+  set_property(GLOBAL APPEND PROPERTY CLANG_STATIC_LIBS ${name})
+endif()
   endif()
   llvm_add_library(${name} ${LIBTYPE} ${ARG_UNPARSED_ARGUMENTS} ${srcs})
 
@@ -110,8 +115,11 @@ macro(add_clang_library name)
   endif()
 
   foreach(lib ${libs})
-if(TARGET ${lib})
+   if(TARGET ${lib})
   target_link_libraries(${lib} INTERFACE ${LLVM_COMMON_LIBS})
+  if (EXCLUDE_FROM_ALL)
+continue()
+  endif()
 
   if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY OR ARG_INSTALL_WITH_TOOLCHAIN)
 get_target_export_arg(${name} Clang export_to_clangtargets UMBRELLA 
clang-libraries)

diff  --git a/clang/lib/StaticAnalyzer/CMakeLists.txt 
b/clang/lib/StaticAnalyzer/CMakeLists.txt
index 3d1509254f52..a610252e1de7 100644
--- a/clang/lib/StaticAnalyzer/CMakeLists.txt
+++ b/clang/lib/StaticAnalyzer/CMakeLists.txt
@@ -1,3 +1,10 @@
+# These directories can significantly impact build time, only build
+# them if anything depends on the clangStaticAnalyzer* libraries.
+if(NOT CLANG_ENABLE_STATIC_ANALYZER)
+  set_property(DIRECTORY PROPERTY EXCLUDE_FROM_ALL ON)
+  set(EXCLUDE_FROM_ALL ON)
+endif()
+
 add_subdirectory(Core)
 add_subdirectory(Checkers)
 add_subdirectory(Frontend)

diff  --git a/llvm/cmake/modules/AddLLVM.cmake 
b/llvm/cmake/modules/AddLLVM.cmake
index c5a9e0209f13..dca1c2af45bb 100644
--- a/llvm/cmake/modules/AddLLVM.cmake
+++ b/llvm/cmake/modules/AddLLVM.cmake
@@ -429,10 +429,13 @@ endfunction(set_windows_version_resource_properties)
 #  This is used to specify that this is a component library of
 #  LLVM which means that the source resides in llvm/lib/ and it is a
 #  candidate for inclusion into libLLVM.so.
+#   EXCLUDE_FROM_ALL
+#  Do not build this library as part of the default target, only
+#  if explicitly requested or when linked against.
 #   )
 function(llvm_add_library name)
   cmake_parse_arguments(ARG
-
"MODULE;SHARED;STATIC;OBJECT;DISABLE_LLVM_LINK_LLVM_DYLIB;SONAME;NO_INSTALL_RPATH;COMPONENT_LIB"
+
"MODULE;SHARED;STATIC;OBJECT;DISABLE_LLVM_LINK_LLVM_DYLIB;SONAME;NO_INSTALL_RPATH;COMPONENT_LIB;EXCLUDE_FROM_ALL"
 "OUTPUT_NAME;PLUGIN_TOOL;ENTITLEMENTS;BUNDLE_PATH"
 "ADDITIONAL_HEADERS;DEPENDS;LINK_COMPONENTS;LINK_LIBS;OBJLIBS"
 ${ARGN})
@@ -535,6 +538,9 @@ function(llvm_add_library name)
 
 # FIXME: Add name_static to anywhere in TARGET ${name}'s PROPERTY.
 set(ARG_STATIC)
+if(ARG_EXCLUDE_FROM_ALL OR EXCLUDE_FROM_ALL)
+  set_target_properties(${name_static} PROPERTIES EXCLUDE_FROM_ALL ON)
+endif()
   endif()
 
   if(ARG_MODULE)
@@ -546,6 +552,10 @@ function(llvm_add_library name)
 add_library(${name} STATIC ${ALL_FILES})
   endif()
 
+  if(ARG_EXCLUDE_FROM_ALL OR EXCLUDE_FROM_ALL)
+set_target_properties(${name} PROPERTIES EXCLUDE_FROM_ALL ON)
+  endif()
+
   if(ARG_COMPONENT_LIB)
 set_target_properties(${name} PROPERTIES LLVM_COMPONENT TRUE)
 set_property(GLOBAL APPEND PROPERTY LLVM_COMPONENT_LIBS ${name})



___

[clang] 7cab90a - Fix __attribute__((annotate("")) with non-zero globals AS

2021-08-26 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2021-08-26T10:09:40+01:00
New Revision: 7cab90a7b1c47780bbf7cfbfda4a1cbab24f0e5b

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

LOG: Fix __attribute__((annotate("")) with non-zero globals AS

The existing code attempting to bitcast from a value in the default globals AS
to i8 addrspace(0)* was triggering an assertion failure in our downstream fork.
I found this while compiling poppler for CHERI-RISC-V (we use AS200 for all
globals). The test case uses AMDGPU since that is one of the in-tree targets
with a non-zero default globals address space.
The new test previously triggered a "Invalid constantexpr bitcast!" assertion
and now correctly generates code with addrspace(1) pointers.

Reviewed By: rjmccall

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

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/CodeGen/CodeGenTypeCache.h
clang/test/CodeGen/annotations-global.c

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 87a15dbeb1b7f..664acefd1815c 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -130,8 +130,9 @@ CodeGenModule::CodeGenModule(ASTContext &C, const 
HeaderSearchOptions &HSO,
 C.getTargetInfo().getMaxPointerWidth());
   Int8PtrTy = Int8Ty->getPointerTo(0);
   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
-  AllocaInt8PtrTy = Int8Ty->getPointerTo(
-  M.getDataLayout().getAllocaAddrSpace());
+  const llvm::DataLayout &DL = M.getDataLayout();
+  AllocaInt8PtrTy = Int8Ty->getPointerTo(DL.getAllocaAddrSpace());
+  GlobalsInt8PtrTy = Int8Ty->getPointerTo(DL.getDefaultGlobalsAddressSpace());
   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
 
   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
@@ -2532,7 +2533,7 @@ llvm::Constant 
*CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
   ArrayRef Exprs = {Attr->args_begin(), Attr->args_size()};
   if (Exprs.empty())
-return llvm::ConstantPointerNull::get(Int8PtrTy);
+return llvm::ConstantPointerNull::get(GlobalsInt8PtrTy);
 
   llvm::FoldingSetNodeID ID;
   for (Expr *E : Exprs) {
@@ -2556,7 +2557,7 @@ llvm::Constant *CodeGenModule::EmitAnnotationArgs(const 
AnnotateAttr *Attr) {
   ".args");
   GV->setSection(AnnotationSection);
   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
-  auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, Int8PtrTy);
+  auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, GlobalsInt8PtrTy);
 
   Lookup = Bitcasted;
   return Bitcasted;
@@ -2571,17 +2572,19 @@ llvm::Constant 
*CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  *LineNoCst = EmitAnnotationLineNo(L),
  *Args = EmitAnnotationArgs(AA);
 
-  llvm::Constant *ASZeroGV = GV;
-  if (GV->getAddressSpace() != 0) {
-ASZeroGV = llvm::ConstantExpr::getAddrSpaceCast(
-   GV, GV->getValueType()->getPointerTo(0));
+  llvm::Constant *GVInGlobalsAS = GV;
+  if (GV->getAddressSpace() !=
+  getDataLayout().getDefaultGlobalsAddressSpace()) {
+GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
+GV, GV->getValueType()->getPointerTo(
+getDataLayout().getDefaultGlobalsAddressSpace()));
   }
 
   // Create the ConstantStruct for the global annotation.
   llvm::Constant *Fields[] = {
-  llvm::ConstantExpr::getBitCast(ASZeroGV, Int8PtrTy),
-  llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
-  llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
+  llvm::ConstantExpr::getBitCast(GVInGlobalsAS, GlobalsInt8PtrTy),
+  llvm::ConstantExpr::getBitCast(AnnoGV, GlobalsInt8PtrTy),
+  llvm::ConstantExpr::getBitCast(UnitGV, GlobalsInt8PtrTy),
   LineNoCst,
   Args,
   };

diff  --git a/clang/lib/CodeGen/CodeGenTypeCache.h 
b/clang/lib/CodeGen/CodeGenTypeCache.h
index f258234fb4d8f..577f88367a3a6 100644
--- a/clang/lib/CodeGen/CodeGenTypeCache.h
+++ b/clang/lib/CodeGen/CodeGenTypeCache.h
@@ -69,6 +69,12 @@ struct CodeGenTypeCache {
 llvm::PointerType *AllocaInt8PtrTy;
   };
 
+  /// void* in default globals address space
+  union {
+llvm::PointerType *GlobalsVoidPtrTy;
+llvm::PointerType *GlobalsInt8PtrTy;
+  };
+
   /// The size and alignment of the builtin C type 'int'.  This comes
   /// up enough in various ABI lowering tasks to be worth pre-computing.
   union {

diff  --git a/clang/test/CodeGen/annotations-global.c 
b/clang/test/CodeGen/annotations-global.c
index 5afec5b4eb72e..2a5c847fd9602 100644
--- a/clang/test/CodeGen/annotations-global.c
+++ b/clang/test/CodeGen/annotations-gl

[clang] bf66b0e - Fix LLVM_ENABLE_THREADS check from 26a92d5852b2c6bf77efd26f6c0194c913f40285

2021-08-26 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2021-08-26T10:09:39+01:00
New Revision: bf66b0eefcda20170eeb574670121159fcd755fa

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

LOG: Fix LLVM_ENABLE_THREADS check from 26a92d5852b2c6bf77efd26f6c0194c913f40285

We should be using #if instead of #ifdef here since LLVM_ENABLE_THREADS
is set using #cmakedefine01 so is always defined.

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang/include/clang/Basic/Stack.h

Removed: 




diff  --git a/clang/include/clang/Basic/Stack.h 
b/clang/include/clang/Basic/Stack.h
index 3418c3bad11bd..30ebd94aedd1f 100644
--- a/clang/include/clang/Basic/Stack.h
+++ b/clang/include/clang/Basic/Stack.h
@@ -39,7 +39,7 @@ namespace clang {
   /// is insufficient, calls Diag to emit a diagnostic before calling Fn.
   inline void runWithSufficientStackSpace(llvm::function_ref Diag,
   llvm::function_ref Fn) {
-#ifdef LLVM_ENABLE_THREADS
+#if LLVM_ENABLE_THREADS
 if (LLVM_UNLIKELY(isStackNearlyExhausted()))
   runWithSufficientStackSpaceSlow(Diag, Fn);
 else



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


[clang] 99eca1b - [Driver] Enable kernel address and memory sanitizers on FreeBSD

2021-04-15 Thread Alex Richardson via cfe-commits

Author: Mark Johnston
Date: 2021-04-15T17:49:00+01:00
New Revision: 99eca1bd9c7ac8de4caba0733c3079ff93b65deb

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

LOG: [Driver] Enable kernel address and memory sanitizers on FreeBSD

Test Plan: using kernel ASAN and MSAN implementations in FreeBSD

Reviewed By: emaste, dim, arichardson

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/FreeBSD.cpp
clang/test/Driver/fsanitize.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/FreeBSD.cpp 
b/clang/lib/Driver/ToolChains/FreeBSD.cpp
index c508af655ac2c..f8c6a81bf3bc0 100644
--- a/clang/lib/Driver/ToolChains/FreeBSD.cpp
+++ b/clang/lib/Driver/ToolChains/FreeBSD.cpp
@@ -467,6 +467,7 @@ bool FreeBSD::IsUnwindTablesDefault(const ArgList &Args) 
const { return true; }
 bool FreeBSD::isPIEDefault() const { return getSanitizerArgs().requiresPIE(); }
 
 SanitizerMask FreeBSD::getSupportedSanitizers() const {
+  const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64;
   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
   const bool IsMIPS64 = getTriple().isMIPS64();
@@ -485,8 +486,13 @@ SanitizerMask FreeBSD::getSupportedSanitizers() const {
 Res |= SanitizerKind::Fuzzer;
 Res |= SanitizerKind::FuzzerNoLink;
   }
-  if (IsX86_64)
+  if (IsAArch64 || IsX86_64) {
+Res |= SanitizerKind::KernelAddress;
+Res |= SanitizerKind::KernelMemory;
+  }
+  if (IsX86_64) {
 Res |= SanitizerKind::Memory;
+  }
   return Res;
 }
 

diff  --git a/clang/test/Driver/fsanitize.c b/clang/test/Driver/fsanitize.c
index 5686d58d8e2f2..7febfd02a1ad7 100644
--- a/clang/test/Driver/fsanitize.c
+++ b/clang/test/Driver/fsanitize.c
@@ -695,7 +695,13 @@
 // RUN: %clang -target x86_64-unknown-cloudabi -fsanitize=safe-stack %s -### 
2>&1 | FileCheck %s -check-prefix=SAFESTACK-CLOUDABI
 // SAFESTACK-CLOUDABI: "-fsanitize=safe-stack"
 
+// RUN: %clang -target x86_64--freebsd -fsanitize=kernel-address %s -### 2>&1 
| FileCheck %s -check-prefix=KERNEL-ADDRESS-FREEBSD
+// RUN: %clang -target aarch64--freebsd -fsanitize=kernel-address %s -### 2>&1 
| FileCheck %s -check-prefix=KERNEL-ADDRESS-FREEBSD
+// KERNEL-ADDRESS-FREEBSD: "-fsanitize=kernel-address"
 
+// RUN: %clang -target x86_64--freebsd -fsanitize=kernel-memory %s -### 2>&1 | 
FileCheck %s -check-prefix=KERNEL-MEMORY-FREEBSD
+// RUN: %clang -target aarch64--freebsd -fsanitize=kernel-memory %s -### 2>&1 
| FileCheck %s -check-prefix=KERNEL-MEMORY-FREEBSD
+// KERNEL-MEMORY-FREEBSD: "-fsanitize=kernel-memory"
 
 // * NetBSD; please keep ordered as in Sanitizers.def *
 



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


[clang] dc4abca - Handle alloc_size attribute on function pointers

2021-04-09 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2021-04-09T18:49:38+01:00
New Revision: dc4abca7662b74467c2b6bceb7e8b046ae04b8a0

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

LOG: Handle alloc_size attribute on function pointers

I have been trying to statically find and analyze all calls to heap
allocation functions to determine how many of them use sizes known at
compile time vs only at runtime. While doing so I saw that quite a few
projects use replaceable function pointers for heap allocation and noticed
that clang was not able to annotate functions pointers with alloc_size.
I have changed the Sema checks to allow alloc_size on all function pointers
and typedefs for function pointers now and added checks that these
attributes are propagated to the LLVM IR correctly.

With this patch we can also compute __builtin_object_size() for calls to
allocation function pointers with the alloc_size attribute.

Reviewed By: aaron.ballman, erik.pilkington
Differential Revision: https://reviews.llvm.org/D55212

Added: 
clang/test/CodeGen/alloc-size-fnptr.c

Modified: 
clang/include/clang/Basic/Attr.td
clang/lib/AST/ExprConstant.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/test/CodeGen/alloc-size.c
clang/test/Misc/pragma-attribute-supported-attributes-list.test
clang/test/Sema/alloc-size.c

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index d9c2422536d0c..400dfe84b7d98 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1308,7 +1308,7 @@ def EmptyBases : InheritableAttr, 
TargetSpecificAttr {
 
 def AllocSize : InheritableAttr {
   let Spellings = [GCC<"alloc_size">];
-  let Subjects = SubjectList<[Function]>;
+  let Subjects = SubjectList<[HasFunctionProto]>;
   let Args = [ParamIdxArgument<"ElemSizeParam">,
   ParamIdxArgument<"NumElemsParam", /*opt*/ 1>];
   let TemplateDependent = 1;

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index fe6573b8bd2c1..5a68b1c3cad17 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -108,8 +108,11 @@ namespace {
 
   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
-const FunctionDecl *Callee = CE->getDirectCallee();
-return Callee ? Callee->getAttr() : nullptr;
+if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
+  return DirectCallee->getAttr();
+if (const Decl *IndirectCallee = CE->getCalleeDecl())
+  return IndirectCallee->getAttr();
+return nullptr;
   }
 
   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an 
Expr.

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index dbc217640fd56..17d63bf1f1364 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -6831,6 +6831,16 @@ static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, 
Declarator &D,
   return true;
 }
 
+template 
+static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) 
{
+  const TypedefNameDecl *TND = TT->getDecl();
+  if (const auto *Attribute = TND->getAttr()) {
+AttrTy *Clone = Attribute->clone(S.Context);
+Clone->setInherited(true);
+D->addAttr(Clone);
+  }
+}
+
 NamedDecl *Sema::ActOnVariableDeclarator(
 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
@@ -7253,6 +7263,14 @@ NamedDecl *Sema::ActOnVariableDeclarator(
   // Handle attributes prior to checking for duplicates in MergeVarDecl
   ProcessDeclAttributes(S, NewVD, D);
 
+  // FIXME: This is probably the wrong location to be doing this and we should
+  // probably be doing this for more attributes (especially for function
+  // pointer attributes such as format, warn_unused_result, etc.). Ideally
+  // the code to copy attributes would be generated by TableGen.
+  if (R->isFunctionPointerType())
+if (const auto *TT = R->getAs())
+  copyAttrFromTypedefToDecl(*this, NewVD, TT);
+
   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
   getLangOpts().SYCLIsDevice) {
 if (EmitTLSUnsupportedError &&

diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 550fa503bf569..43ca644ed21ed 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -788,20 +788,20 @@ static void handleAssertExclusiveLockAttr(Sema &S, Decl 
*D,
 ///
 /// AttrArgNo is used to actually retrieve the argument, so it's base-0.
 template 
-static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
-const AttrInfo 

[clang] 51e09e1 - [AMDGPU] Set the default globals address space to 1

2020-11-20 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-11-20T15:46:53Z
New Revision: 51e09e1d5aa43296cf8baf26a74793fd86b0b0d2

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

LOG: [AMDGPU] Set the default globals address space to 1

This will ensure that passes that add new global variables will create them
in address space 1 once the passes have been updated to no longer default
to the implicit address space zero.
This also changes AutoUpgrade.cpp to add -G1 to the DataLayout if it wasn't
already to present to ensure bitcode backwards compatibility.

Reviewed by: arsenm

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

Added: 


Modified: 
clang/lib/Basic/Targets/AMDGPU.cpp
clang/lib/CodeGen/CGClass.cpp
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CGVTT.cpp
clang/lib/CodeGen/ItaniumCXXABI.cpp
clang/test/CodeGen/target-data.c
clang/test/CodeGenOpenCL/amdgpu-env-amdgcn.cl
llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
llvm/lib/IR/AutoUpgrade.cpp
llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp
llvm/unittests/Bitcode/DataLayoutUpgradeTest.cpp

Removed: 




diff  --git a/clang/lib/Basic/Targets/AMDGPU.cpp 
b/clang/lib/Basic/Targets/AMDGPU.cpp
index 9b88dff7c4af..91c1e83f61cb 100644
--- a/clang/lib/Basic/Targets/AMDGPU.cpp
+++ b/clang/lib/Basic/Targets/AMDGPU.cpp
@@ -31,12 +31,12 @@ namespace targets {
 
 static const char *const DataLayoutStringR600 =
 "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
-"-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5";
+"-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1";
 
 static const char *const DataLayoutStringAMDGCN =
 "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32"
 "-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
-"-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5"
+"-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1"
 "-ni:7";
 
 const LangASMap AMDGPUTargetInfo::AMDGPUDefIsGenMap = {

diff  --git a/clang/lib/CodeGen/CGClass.cpp b/clang/lib/CodeGen/CGClass.cpp
index c41650ad2b3b..5bd484eb1464 100644
--- a/clang/lib/CodeGen/CGClass.cpp
+++ b/clang/lib/CodeGen/CGClass.cpp
@@ -2508,12 +2508,16 @@ void CodeGenFunction::InitializeVTablePointer(const 
VPtr &Vptr) {
 
   // Finally, store the address point. Use the same LLVM types as the field to
   // support optimization.
+  unsigned GlobalsAS = CGM.getDataLayout().getDefaultGlobalsAddressSpace();
+  unsigned ProgAS = CGM.getDataLayout().getProgramAddressSpace();
   llvm::Type *VTablePtrTy =
   llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
-  ->getPointerTo()
-  ->getPointerTo();
-  VTableField = Builder.CreateBitCast(VTableField, 
VTablePtrTy->getPointerTo());
-  VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
+  ->getPointerTo(ProgAS)
+  ->getPointerTo(GlobalsAS);
+  VTableField = Builder.CreatePointerBitCastOrAddrSpaceCast(
+  VTableField, VTablePtrTy->getPointerTo(GlobalsAS));
+  VTableAddressPoint = Builder.CreatePointerBitCastOrAddrSpaceCast(
+  VTableAddressPoint, VTablePtrTy);
 
   llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, 
VTableField);
   TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTablePtrTy);

diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index ced45eca4ba6..84733369a4a1 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -3075,11 +3075,12 @@ void CGOpenMPRuntime::createOffloadEntry(
   llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
   Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
 
-  llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
-llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
-llvm::ConstantInt::get(CGM.SizeTy, Size),
-llvm::ConstantInt::get(CGM.Int32Ty, Flags),
-llvm::ConstantInt::get(CGM.Int32Ty, 0)};
+  llvm::Constant *Data[] = {
+  llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(ID, CGM.VoidPtrTy),
+  llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(Str, CGM.Int8PtrTy),
+  llvm::ConstantInt::get(CGM.SizeTy, Size),
+  llvm::ConstantInt::get(CGM.Int32Ty, Flags),
+  llvm::ConstantInt::get(CGM.Int32Ty, 0)};
   std::string EntryName = getName({"omp_offloading", "entry", ""});
   llvm::GlobalVariable *Entry = createGlobalStruct(
   CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data,

diff  --git a/clang/lib/CodeGen/CGVTT.cpp b/clang/lib/CodeGen/CGVTT.cpp
index e79f3f3dd8bc..564d9f354e64 100644
--- a/clang/lib/Cod

[clang] 906b9db - [clang-format] Improve BAS_DontAlign+AllowAllArgumentsOnNextLine=false

2020-11-02 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-11-02T17:52:37Z
New Revision: 906b9dbc9d7487ee923b6a516c36777a2be0ca35

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

LOG: [clang-format] Improve BAS_DontAlign+AllowAllArgumentsOnNextLine=false

TokenAnnotator::splitPenalty() was always returning 0 for opening parens if
AlignAfterOpenBracket was set to BAS_DontAlign, so the preferred point for
line breaking was always after the open paren (and was ignoring
PenaltyBreakBeforeFirstCallParameter). This change restricts the zero
penalty to the AllowAllArgumentsOnNextLine case. This results in improved
formatting for FreeBSD where we set AllowAllArgumentsOnNextLine: false
and a high value for PenaltyBreakBeforeFirstCallParameter to avoid breaking
after the open paren.

Before:
```
functionCall(
paramA, paramB, paramC);
void functionDecl(
int A, int B, int C)
```
After:
```
functionCall(paramA, paramB,
paramC);
void functionDecl(int A, int B,
int C)
```

Reviewed By: MyDeveloperDay

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 22dcd7521dbe..0fdcca867e3d 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2734,7 +2734,11 @@ unsigned TokenAnnotator::splitPenalty(const 
AnnotatedLine &Line,
   if (Left.is(TT_TemplateOpener))
 return 100;
   if (Left.opensScope()) {
-if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
+// If we aren't aligning after opening parens/braces we can always break
+// here unless the style does not want us to place all arguments on the
+// next line.
+if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign &&
+(Left.ParameterCount <= 1 || Style.AllowAllArgumentsOnNextLine))
   return 0;
 if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle)
   return 19;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 0c08eb55be5f..3d4e3e445c78 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -4992,6 +4992,60 @@ TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
Style);
 }
 
+TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
+  // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
+  // and BAS_Align.
+  auto Style = getLLVMStyle();
+  Style.ColumnLimit = 35;
+  StringRef Input = "functionCall(paramA, paramB, paramC);\n"
+"void functionDecl(int A, int B, int C);";
+  Style.AllowAllArgumentsOnNextLine = false;
+  Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
+  EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
+  "paramC);\n"
+  "void functionDecl(int A, int B,\n"
+  "int C);"),
+format(Input, Style));
+  Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
+  EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
+  " paramC);\n"
+  "void functionDecl(int A, int B,\n"
+  "  int C);"),
+format(Input, Style));
+  // However, BAS_AlwaysBreak should take precedence over
+  // AllowAllArgumentsOnNextLine.
+  Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
+  EXPECT_EQ(StringRef("functionCall(\n"
+  "paramA, paramB, paramC);\n"
+  "void functionDecl(\n"
+  "int A, int B, int C);"),
+format(Input, Style));
+
+  // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
+  // first argument.
+  Style.AllowAllArgumentsOnNextLine = true;
+  Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
+  EXPECT_EQ(StringRef("functionCall(\n"
+  "paramA, paramB, paramC);\n"
+  "void functionDecl(\n"
+  "int A, int B, int C);"),
+format(Input, Style));
+  // It wouldn't fit on one line with aligned parameters so this setting
+  // doesn't change anything for BAS_Align.
+  Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
+  EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
+  " paramC);\n"
+  "void functionDecl(int A, int B,\n"
+  "  int C);"),
+format(Input, Style));
+  Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
+  EXPECT_EQ(StringRef("functionCall(\n"
+  "paramA, paramB, paramC);\n"

[clang] 75a1790 - Fix use-after-scope introduced in 850325348ae82cd5e26ea9edfd04219d0fbe7828

2020-10-27 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-10-27T14:26:23Z
New Revision: 75a1790f4bf052b0a615ed0270a7b4b1c4c88818

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

LOG: Fix use-after-scope introduced in 850325348ae82cd5e26ea9edfd04219d0fbe7828

Added: 


Modified: 
clang/unittests/Format/MacroExpanderTest.cpp
clang/unittests/Format/TestLexer.h
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/MacroExpanderTest.cpp 
b/clang/unittests/Format/MacroExpanderTest.cpp
index 20e1dba0d49a0..b2cd5112b820f 100644
--- a/clang/unittests/Format/MacroExpanderTest.cpp
+++ b/clang/unittests/Format/MacroExpanderTest.cpp
@@ -11,6 +11,7 @@ namespace {
 
 class MacroExpanderTest : public ::testing::Test {
 public:
+  MacroExpanderTest() : Lex(Allocator, Buffers) {}
   std::unique_ptr
   create(const std::vector &MacroDefinitions) {
 return std::make_unique(MacroDefinitions,
@@ -64,7 +65,9 @@ class MacroExpanderTest : public ::testing::Test {
   << Context << " in " << text(Tokens) << " at " << File << ":" << 
Line;
 }
   }
-
+protected:
+  llvm::SpecificBumpPtrAllocator Allocator;
+  std::vector> Buffers;
   TestLexer Lex;
 };
 

diff  --git a/clang/unittests/Format/TestLexer.h 
b/clang/unittests/Format/TestLexer.h
index 2f2b754fcbbb7..0945e9e66c6fd 100644
--- a/clang/unittests/Format/TestLexer.h
+++ b/clang/unittests/Format/TestLexer.h
@@ -59,12 +59,15 @@ inline std::string text(llvm::ArrayRef 
Tokens) {
 
 class TestLexer : public UnwrappedLineConsumer {
 public:
-  TestLexer(FormatStyle Style = getLLVMStyle())
-  : Style(Style), SourceMgr("test.cpp", ""),
-IdentTable(getFormattingLangOpts(Style)) {}
+  TestLexer(llvm::SpecificBumpPtrAllocator &Allocator,
+std::vector> &Buffers,
+FormatStyle Style = getLLVMStyle())
+  : Allocator(Allocator), Buffers(Buffers), Style(Style),
+SourceMgr("test.cpp", ""), IdentTable(getFormattingLangOpts(Style)) {}
 
   TokenList lex(llvm::StringRef Code) {
-auto Result = getNewLexer(Code).lex();
+FormatTokenLexer Lex = getNewLexer(Code);
+ArrayRef Result = Lex.lex();
 return TokenList(Result.begin(), Result.end());
   }
 
@@ -77,6 +80,7 @@ class TestLexer : public UnwrappedLineConsumer {
 for (auto &Line : UnwrappedLines) {
   AnnotatedLine Annotated(Line);
   Annotator.annotate(Annotated);
+  Annotator.calculateFormattingInformation(Annotated);
 }
 UnwrappedLines.clear();
 return TokenList(Tokens.begin(), Tokens.end());
@@ -99,18 +103,16 @@ class TestLexer : public UnwrappedLineConsumer {
 llvm::MemoryBuffer::getMemBufferCopy(Code, ""));
 clang::FileID FID =
 SourceMgr.get().createFileID(Buffers.back()->getMemBufferRef());
-FormatTokenLexer Lex(SourceMgr.get(), FID, 0, Style, Encoding, Allocator,
- IdentTable);
 return FormatTokenLexer(SourceMgr.get(), FID, 0, Style, Encoding, 
Allocator,
 IdentTable);
   }
 
 public:
+  llvm::SpecificBumpPtrAllocator& Allocator;
+  std::vector>& Buffers;
   FormatStyle Style;
   encoding::Encoding Encoding = encoding::Encoding_UTF8;
-  std::vector> Buffers;
   clang::SourceManagerForFile SourceMgr;
-  llvm::SpecificBumpPtrAllocator Allocator;
   IdentifierTable IdentTable;
   SmallVector UnwrappedLines;
 };

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 12a985217d973..e87270d638652 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -20,8 +20,10 @@ class TokenAnnotatorTest : public ::testing::Test {
 protected:
   TokenList annotate(llvm::StringRef Code,
  const FormatStyle &Style = getLLVMStyle()) {
-return TestLexer(Style).annotate(Code);
+return TestLexer(Allocator, Buffers, Style).annotate(Code);
   }
+  llvm::SpecificBumpPtrAllocator Allocator;
+  std::vector> Buffers;
 };
 
 #define EXPECT_TOKEN_KIND(FormatTok, Kind) 
\



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


[clang] 8503253 - [clang-format] Fix misformatted macro definitions after D86959

2020-10-27 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-10-27T12:16:46Z
New Revision: 850325348ae82cd5e26ea9edfd04219d0fbe7828

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

LOG: [clang-format] Fix misformatted macro definitions after D86959

After D86959 the code `#define lambda [](const decltype(x) &ptr) {}`
was formatted as `#define lambda [](const decltype(x) & ptr) {}` due to
now parsing the '&' token as a BinaryOperator. The problem was caused by
the condition `Line.InPPDirective && (!Left->Previous || 
!Left->Previous->is(tok::identifier))) {`
being matched and therefore not performing the checks for "previous token
is one of decltype/_Atomic/etc.". This patch moves those checks after the
existing if/else chain to ensure the left-parent token classification is
always run after checking whether the contents of the parens is an
expression or not.

This change also introduces a new TokenAnnotatorTest that checks the
token kind and Role of Tokens after analyzing them. This is used to check
for TT_PointerOrReference, in addition to indirectly testing this based
on the resulting formatting.

Reviewed By: MyDeveloperDay

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

Added: 
clang/unittests/Format/TokenAnnotatorTest.cpp

Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/CMakeLists.txt
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/TestLexer.h

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 66a8cacbb4af..22dcd7521dbe 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -256,16 +256,6 @@ class AnnotatingParser {
 } else if (Contexts[Contexts.size() - 2].CaretFound) {
   // This is the parameter list of an ObjC block.
   Contexts.back().IsExpression = false;
-} else if (PrevNonComment && PrevNonComment->is(tok::kw___attribute)) {
-  Left->setType(TT_AttributeParen);
-} else if (PrevNonComment &&
-   PrevNonComment->isOneOf(TT_TypenameMacro, tok::kw_decltype,
-   tok::kw_typeof, tok::kw__Atomic,
-   tok::kw___underlying_type)) {
-  Left->setType(TT_TypeDeclarationParen);
-  // decltype() and typeof() usually contain expressions.
-  if (PrevNonComment->isOneOf(tok::kw_decltype, tok::kw_typeof))
-Contexts.back().IsExpression = true;
 } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
   // The first argument to a foreach macro is a declaration.
   Contexts.back().IsForEachMacro = true;
@@ -279,6 +269,21 @@ class AnnotatingParser {
   Contexts.back().IsExpression = !IsForOrCatch;
 }
 
+// Infer the role of the l_paren based on the previous token if we haven't
+// detected one one yet.
+if (PrevNonComment && Left->is(TT_Unknown)) {
+  if (PrevNonComment->is(tok::kw___attribute)) {
+Left->setType(TT_AttributeParen);
+  } else if (PrevNonComment->isOneOf(TT_TypenameMacro, tok::kw_decltype,
+ tok::kw_typeof, tok::kw__Atomic,
+ tok::kw___underlying_type)) {
+Left->setType(TT_TypeDeclarationParen);
+// decltype() and typeof() usually contain expressions.
+if (PrevNonComment->isOneOf(tok::kw_decltype, tok::kw_typeof))
+  Contexts.back().IsExpression = true;
+  }
+}
+
 if (StartsObjCMethodExpr) {
   Contexts.back().ColonIsObjCMethodExpr = true;
   Left->setType(TT_ObjCMethodExpr);

diff  --git a/clang/unittests/Format/CMakeLists.txt 
b/clang/unittests/Format/CMakeLists.txt
index 472e6eec40af..281ebc2d411c 100644
--- a/clang/unittests/Format/CMakeLists.txt
+++ b/clang/unittests/Format/CMakeLists.txt
@@ -21,6 +21,7 @@ add_clang_unittest(FormatTests
   SortImportsTestJava.cpp
   SortIncludesTest.cpp
   UsingDeclarationsSorterTest.cpp
+  TokenAnnotatorTest.cpp
   )
 
 clang_target_link_libraries(FormatTests

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index be9c84332265..0c08eb55be5f 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8197,6 +8197,12 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyFormat("void f() { MACRO(A * B); }");
   verifyFormat("void f() { MACRO(A & B); }");
 
+  // This lambda was mis-formatted after D88956 (treating it as a binop):
+  verifyFormat("auto x = [](const decltype(x) &ptr) {};");
+  verifyFormat("auto x = [](const decltype(x) *ptr) {};");
+  verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
+  verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
+
   verifyFormat("DatumHandle 

[clang] 66a3b90 - [clang-format] Drop clangFrontend dependency for FormatTests

2020-10-20 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-10-20T10:13:28+01:00
New Revision: 66a3b9073ac116f0ee39baf625c733abe18140e5

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

LOG: [clang-format] Drop clangFrontend dependency for FormatTests

This allows building the clang-format unit tests in only 657 ninja steps
rather than 1257 which allows for much faster incremental builds after a
git pull.

Reviewed By: MyDeveloperDay
Differential Revision: https://reviews.llvm.org/D89709

Added: 


Modified: 
clang/unittests/Format/CMakeLists.txt
clang/unittests/Format/CleanupTest.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/FormatTestComments.cpp
clang/unittests/Format/FormatTestObjC.cpp
clang/unittests/Format/FormatTestRawStrings.cpp
clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
clang/unittests/Tooling/RewriterTestContext.h

Removed: 




diff  --git a/clang/unittests/Format/CMakeLists.txt 
b/clang/unittests/Format/CMakeLists.txt
index d0cc2cae179f..472e6eec40af 100644
--- a/clang/unittests/Format/CMakeLists.txt
+++ b/clang/unittests/Format/CMakeLists.txt
@@ -27,7 +27,6 @@ clang_target_link_libraries(FormatTests
   PRIVATE
   clangBasic
   clangFormat
-  clangFrontend
   clangRewrite
   clangToolingCore
   )

diff  --git a/clang/unittests/Format/CleanupTest.cpp 
b/clang/unittests/Format/CleanupTest.cpp
index 9649b981d558..dc149b502bc5 100644
--- a/clang/unittests/Format/CleanupTest.cpp
+++ b/clang/unittests/Format/CleanupTest.cpp
@@ -9,7 +9,6 @@
 #include "clang/Format/Format.h"
 
 #include "../Tooling/ReplacementTest.h"
-#include "../Tooling/RewriterTestContext.h"
 #include "clang/Tooling/Core/Replacement.h"
 
 #include "gtest/gtest.h"

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 1bdd7062fbb8..be9c84332265 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -11,7 +11,6 @@
 #include "../Tooling/ReplacementTest.h"
 #include "FormatTestUtils.h"
 
-#include "clang/Frontend/TextDiagnosticPrinter.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "gtest/gtest.h"

diff  --git a/clang/unittests/Format/FormatTestComments.cpp 
b/clang/unittests/Format/FormatTestComments.cpp
index 34d6b62b26c8..95afb17114a2 100644
--- a/clang/unittests/Format/FormatTestComments.cpp
+++ b/clang/unittests/Format/FormatTestComments.cpp
@@ -11,7 +11,6 @@
 #include "../Tooling/ReplacementTest.h"
 #include "FormatTestUtils.h"
 
-#include "clang/Frontend/TextDiagnosticPrinter.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "gtest/gtest.h"

diff  --git a/clang/unittests/Format/FormatTestObjC.cpp 
b/clang/unittests/Format/FormatTestObjC.cpp
index 21b8d4701271..a34a0832286b 100644
--- a/clang/unittests/Format/FormatTestObjC.cpp
+++ b/clang/unittests/Format/FormatTestObjC.cpp
@@ -11,7 +11,6 @@
 #include "../Tooling/ReplacementTest.h"
 #include "FormatTestUtils.h"
 
-#include "clang/Frontend/TextDiagnosticPrinter.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "gtest/gtest.h"

diff  --git a/clang/unittests/Format/FormatTestRawStrings.cpp 
b/clang/unittests/Format/FormatTestRawStrings.cpp
index 31490355468e..6310fe510fd3 100644
--- a/clang/unittests/Format/FormatTestRawStrings.cpp
+++ b/clang/unittests/Format/FormatTestRawStrings.cpp
@@ -11,7 +11,6 @@
 #include "../Tooling/ReplacementTest.h"
 #include "FormatTestUtils.h"
 
-#include "clang/Frontend/TextDiagnosticPrinter.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "gtest/gtest.h"

diff  --git a/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp 
b/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
index 463afa67e8b0..3340e02f4a1c 100644
--- a/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
+++ b/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
@@ -8,7 +8,6 @@
 
 #include "clang/Format/Format.h"
 
-#include "clang/Frontend/TextDiagnosticPrinter.h"
 #include "llvm/Support/Debug.h"
 #include "gtest/gtest.h"
 

diff  --git a/clang/unittests/Tooling/RewriterTestContext.h 
b/clang/unittests/Tooling/RewriterTestContext.h
index 99f7a11dca98..ae2d2baa0fdc 100644
--- a/clang/unittests/Tooling/RewriterTestContext.h
+++ b/clang/unittests/Tooling/RewriterTestContext.h
@@ -18,7 +18,6 @@
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceManager.h"
-#include "clang/Frontend/TextDiagnosticPrinter.h"
 #include "clang/Rewrite/Core/Rewriter.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
@@ -26,6 +25,22 @@
 
 namespace clang {
 
+/// \brief A very simple diagnostic consumer that prints to stderr 

[clang] a221475 - Move clang/Tooling/Core/Lookup.h to clang/Tooling/Refactoring/Lookup.h

2020-10-20 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-10-20T10:13:28+01:00
New Revision: a2214757e2ca445112f19395493a78e820389655

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

LOG: Move clang/Tooling/Core/Lookup.h to clang/Tooling/Refactoring/Lookup.h

This allows removing the clangAST dependency from libclangToolingCore and
therefore allows clang-format to be built without depending on clangAST.
Before 1166 files had to be compiled for clang-format, now only 796.

Reviewed By: bkramer

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

Added: 
clang/include/clang/Tooling/Refactoring/Lookup.h
clang/lib/Tooling/Refactoring/Lookup.cpp

Modified: 
clang/lib/Format/FormatInternal.h
clang/lib/Tooling/Core/CMakeLists.txt
clang/lib/Tooling/Refactoring/CMakeLists.txt
clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
clang/unittests/Tooling/LookupTest.cpp

Removed: 
clang/include/clang/Tooling/Core/Lookup.h
clang/lib/Tooling/Core/Lookup.cpp



diff  --git a/clang/include/clang/Tooling/Core/Lookup.h 
b/clang/include/clang/Tooling/Refactoring/Lookup.h
similarity index 93%
rename from clang/include/clang/Tooling/Core/Lookup.h
rename to clang/include/clang/Tooling/Refactoring/Lookup.h
index 02b561c14f29..448bc422c4e7 100644
--- a/clang/include/clang/Tooling/Core/Lookup.h
+++ b/clang/include/clang/Tooling/Refactoring/Lookup.h
@@ -10,8 +10,8 @@
 //
 
//===--===//
 
-#ifndef LLVM_CLANG_TOOLING_CORE_LOOKUP_H
-#define LLVM_CLANG_TOOLING_CORE_LOOKUP_H
+#ifndef LLVM_CLANG_TOOLING_REFACTOR_LOOKUP_H
+#define LLVM_CLANG_TOOLING_REFACTOR_LOOKUP_H
 
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
@@ -47,4 +47,4 @@ std::string replaceNestedName(const NestedNameSpecifier *Use,
 } // end namespace tooling
 } // end namespace clang
 
-#endif // LLVM_CLANG_TOOLING_CORE_LOOKUP_H
+#endif // LLVM_CLANG_TOOLING_REFACTOR_LOOKUP_H

diff  --git a/clang/lib/Format/FormatInternal.h 
b/clang/lib/Format/FormatInternal.h
index 3aa616da23d8..9043ce32e9e3 100644
--- a/clang/lib/Format/FormatInternal.h
+++ b/clang/lib/Format/FormatInternal.h
@@ -16,7 +16,6 @@
 #define LLVM_CLANG_LIB_FORMAT_FORMATINTERNAL_H
 
 #include "BreakableToken.h"
-#include "clang/Tooling/Core/Lookup.h"
 #include 
 
 namespace clang {

diff  --git a/clang/lib/Tooling/Core/CMakeLists.txt 
b/clang/lib/Tooling/Core/CMakeLists.txt
index f7f423c52228..e523ca45301e 100644
--- a/clang/lib/Tooling/Core/CMakeLists.txt
+++ b/clang/lib/Tooling/Core/CMakeLists.txt
@@ -2,11 +2,9 @@ set(LLVM_LINK_COMPONENTS support)
 
 add_clang_library(clangToolingCore
   Diagnostic.cpp
-  Lookup.cpp
   Replacement.cpp
 
   LINK_LIBS
-  clangAST
   clangBasic
   clangLex
   clangRewrite

diff  --git a/clang/lib/Tooling/Refactoring/CMakeLists.txt 
b/clang/lib/Tooling/Refactoring/CMakeLists.txt
index 0565de224bbc..d3077be8810a 100644
--- a/clang/lib/Tooling/Refactoring/CMakeLists.txt
+++ b/clang/lib/Tooling/Refactoring/CMakeLists.txt
@@ -6,6 +6,7 @@ add_clang_library(clangToolingRefactoring
   AtomicChange.cpp
   Extract/Extract.cpp
   Extract/SourceExtraction.cpp
+  Lookup.cpp
   RefactoringActions.cpp
   Rename/RenamingAction.cpp
   Rename/SymbolOccurrences.cpp

diff  --git a/clang/lib/Tooling/Core/Lookup.cpp 
b/clang/lib/Tooling/Refactoring/Lookup.cpp
similarity index 99%
rename from clang/lib/Tooling/Core/Lookup.cpp
rename to clang/lib/Tooling/Refactoring/Lookup.cpp
index 712724a268fb..9468d4d032a7 100644
--- a/clang/lib/Tooling/Core/Lookup.cpp
+++ b/clang/lib/Tooling/Refactoring/Lookup.cpp
@@ -10,7 +10,7 @@
 //
 
//===--===//
 
-#include "clang/Tooling/Core/Lookup.h"
+#include "clang/Tooling/Refactoring/Lookup.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"

diff  --git a/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp 
b/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
index dfc319dd0639..6a08c7fd5247 100644
--- a/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
+++ b/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
@@ -21,7 +21,7 @@
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Lex/Lexer.h"
-#include "clang/Tooling/Core/Lookup.h"
+#include "clang/Tooling/Refactoring/Lookup.h"
 #include "clang/Tooling/Refactoring/RecursiveSymbolVisitor.h"
 #include "clang/Tooling/Refactoring/Rename/SymbolName.h"
 #include "clang/Tooling/Refactoring/Rename/USRFinder.h"

diff  --git a/clang/unittests/Tooling/LookupTest.cpp 
b/clang/unittests/Tooling/LookupTest.cpp
index 372cbbf62b7a..05494cb42d90 100644
--- a/clang/unittests/Tooling/LookupTest.cpp
+++ b/clang/unittests/Tooling/LookupTest.cpp
@@ -6

[clang] 9e27f38 - [clang-format] Add a SpaceAroundPointerQualifiers style option

2020-10-18 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-10-18T18:17:50+01:00
New Revision: 9e27f38354e850346f5f4e895e44ad3346546d9c

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

LOG: [clang-format] Add a SpaceAroundPointerQualifiers style option

Some projects (e.g. FreeBSD) align pointers to the right but expect a
space between the '*' and any pointer qualifiers such as const. To handle
these cases this patch adds a new config option SpaceAroundPointerQualifiers
that can be used to configure whether spaces need to be added before/after
pointer qualifiers.

PointerAlignment = Right
SpaceAroundPointerQualifiers = Default/After:
void *const *x = NULL;
SpaceAroundPointerQualifiers = Before/Both
void * const *x = NULL;

PointerAlignment = Left
SpaceAroundPointerQualifiers = Default/Before:
void* const* x = NULL;
SpaceAroundPointerQualifiers = After/Both
void* const * x = NULL;

PointerAlignment = Middle
SpaceAroundPointerQualifiers = Default/Before/After/Both:
void * const * x = NULL;

Reviewed By: MyDeveloperDay

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 0c3ed9f4ab84..ccc59cd6fc19 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -2463,6 +2463,46 @@ the configuration (without a prefix: ``Auto``).
  true:  false:
  template  void foo(); vs. template void foo();
 
+**SpaceAroundPointerQualifiers** (``SpaceAroundPointerQualifiersStyle``)
+  Defines in which cases to put a space before or after pointer qualifiers
+
+  Possible values:
+
+  * ``SAPQ_Default`` (in configuration: ``Default``)
+Don't ensure spaces around pointer qualifiers and use PointerAlignment
+instead.
+
+.. code-block:: c++
+
+   PointerAlignment: Left PointerAlignment: Right
+   void* const* x = NULL; vs. void *const *x = NULL;
+
+  * ``SAPQ_Before`` (in configuration: ``Before``)
+Ensure that there is a space before pointer qualifiers.
+
+.. code-block:: c++
+
+   PointerAlignment: Left PointerAlignment: Right
+   void* const* x = NULL; vs. void * const *x = NULL;
+
+  * ``SAPQ_After`` (in configuration: ``After``)
+Ensure that there is a space after pointer qualifiers.
+
+.. code-block:: c++
+
+   PointerAlignment: Left PointerAlignment: Right
+   void* const * x = NULL; vs. void *const *x = NULL;
+
+  * ``SAPQ_Both`` (in configuration: ``Both``)
+Ensure that there is a space both before and after pointer qualifiers.
+
+.. code-block:: c++
+
+   PointerAlignment: Left PointerAlignment: Right
+   void* const * x = NULL; vs. void * const *x = NULL;
+
+
+
 **SpaceBeforeAssignmentOperators** (``bool``)
   If ``false``, spaces will be removed before assignment operators.
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 40d5184f4d0d..587e588525df 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -2078,6 +2078,38 @@ struct FormatStyle {
   /// \endcode
   bool SpaceAfterTemplateKeyword;
 
+  /// Different ways to put a space before opening parentheses.
+  enum SpaceAroundPointerQualifiersStyle {
+/// Don't ensure spaces around pointer qualifiers and use PointerAlignment
+/// instead.
+/// \code
+///PointerAlignment: Left PointerAlignment: Right
+///void* const* x = NULL; vs. void *const *x = NULL;
+/// \endcode
+SAPQ_Default,
+/// Ensure that there is a space before pointer qualifiers.
+/// \code
+///PointerAlignment: Left PointerAlignment: Right
+///void* const* x = NULL; vs. void * const *x = NULL;
+/// \endcode
+SAPQ_Before,
+/// Ensure that there is a space after pointer qualifiers.
+/// \code
+///PointerAlignment: Left PointerAlignment: Right
+///void* const * x = NULL; vs. void *const *x = NULL;
+/// \endcode
+SAPQ_After,
+/// Ensure that there is a space both before and after pointer qualifiers.
+/// \code
+///PointerAlignment: Left PointerAlignment: Right
+///void* const * x = NULL; vs. void * const *x = NULL;
+/// \endcode
+SAPQ_Both,
+  };
+
+  ///  Defines in which cases to put a space

[clang] 0a3c82e - [clang-format][NFC] Store FormatToken::Type as an enum instead of bitfield

2020-10-07 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-10-07T17:17:40+01:00
New Revision: 0a3c82e85b73e51e830b57844b2f5b98cb59afd1

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

LOG: [clang-format][NFC] Store FormatToken::Type as an enum instead of bitfield

This improves the debugging experience since LLDB will print the enumerator
name instead of a decimal number. This changes TokenType to have uint8_t
as the underlying type and moves it after the remaining bitfields to avoid
increasing the size of FormatToken.

Reviewed By: MyDeveloperDay

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

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/UnwrappedLineParser.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index c6af71a768a1a..9cc65bb11b54e 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -118,7 +118,7 @@ namespace format {
 
 /// Determines the semantic type of a syntactic token, e.g. whether "<" is a
 /// template opener or binary operator.
-enum TokenType {
+enum TokenType : uint8_t {
 #define TYPE(X) TT_##X,
   LIST_TOKEN_TYPES
 #undef TYPE
@@ -211,8 +211,8 @@ struct FormatToken {
 ClosesTemplateDeclaration(false), StartsBinaryExpression(false),
 EndsBinaryExpression(false), PartOfMultiVariableDeclStmt(false),
 ContinuesLineCommentSection(false), Finalized(false),
-BlockKind(BK_Unknown), Type(TT_Unknown), Decision(FD_Unformatted),
-PackingKind(PPK_Inconclusive) {}
+BlockKind(BK_Unknown), Decision(FD_Unformatted),
+PackingKind(PPK_Inconclusive), Type(TT_Unknown) {}
 
   /// The \c Token.
   Token Tok;
@@ -297,18 +297,6 @@ struct FormatToken {
 assert(getBlockKind() == BBK && "BraceBlockKind overflow!");
   }
 
-private:
-  unsigned Type : 8;
-
-public:
-  /// Returns the token's type, e.g. whether "<" is a template opener or
-  /// binary operator.
-  TokenType getType() const { return static_cast(Type); }
-  void setType(TokenType T) {
-Type = T;
-assert(getType() == T && "TokenType overflow!");
-  }
-
 private:
   /// Stores the formatting decision for the token once it was made.
   unsigned Decision : 2;
@@ -335,6 +323,15 @@ struct FormatToken {
 assert(getPackingKind() == K && "ParameterPackingKind overflow!");
   }
 
+private:
+  TokenType Type;
+
+public:
+  /// Returns the token's type, e.g. whether "<" is a template opener or
+  /// binary operator.
+  TokenType getType() const { return Type; }
+  void setType(TokenType T) { Type = T; }
+
   /// The number of newlines immediately before the \c Token.
   ///
   /// This can be used to determine what the user wrote in the original code

diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index b599168b48e17..7075a6fe33f76 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2753,7 +2753,7 @@ LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const 
UnwrappedLine &Line,
 E = Line.Tokens.end();
I != E; ++I) {
 llvm::dbgs() << I->Tok->Tok.getName() << "["
- << "T=" << I->Tok->getType()
+ << "T=" << (unsigned)I->Tok->getType()
  << ", OC=" << I->Tok->OriginalColumn << "] ";
   }
   for (std::list::const_iterator I = Line.Tokens.begin(),



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


[clang] ff6e444 - [clang-format][tests] Fix MacroExpander lexer not parsing C++ keywords

2020-10-07 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-10-07T17:17:41+01:00
New Revision: ff6e4441b93953efb2c52995e79e211a49ffac06

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

LOG: [clang-format][tests] Fix MacroExpander lexer not parsing C++ keywords

While debugging a different clang-format failure, I tried to reuse the
MacroExpander lexer, but was surprised to see that it marks all C++
keywords (e.g. const, decltype) as being of type identifier. After stepping
through the ::format() code, I noticed that the difference between these
two is that the identifier table was not being initialized based on the
FormatStyle, so only basic tokens such as tok::semi, tok::plus, etc. were
being handled.

Reviewed By: klimek

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

Added: 


Modified: 
clang/unittests/Format/MacroExpanderTest.cpp
clang/unittests/Format/TestLexer.h

Removed: 




diff  --git a/clang/unittests/Format/MacroExpanderTest.cpp 
b/clang/unittests/Format/MacroExpanderTest.cpp
index 59c67f29bedde..20e1dba0d49a0 100644
--- a/clang/unittests/Format/MacroExpanderTest.cpp
+++ b/clang/unittests/Format/MacroExpanderTest.cpp
@@ -182,6 +182,22 @@ TEST_F(MacroExpanderTest, SingleExpansion) {
   EXPECT_ATTRIBUTES(Result, Attributes);
 }
 
+TEST_F(MacroExpanderTest, UnderstandsCppTokens) {
+  auto Macros = create({"A(T,name)=T name = 0;"});
+  auto *A = Lex.id("A");
+  auto Args = lexArgs({"const int", "x"});
+  auto Result = uneof(Macros->expand(A, Args));
+  std::vector Attributes = {
+  {tok::kw_const, MR_ExpandedArg, 1, 0, {A}},
+  {tok::kw_int, MR_ExpandedArg, 0, 0, {A}},
+  {tok::identifier, MR_ExpandedArg, 0, 0, {A}},
+  {tok::equal, MR_Hidden, 0, 0, {A}},
+  {tok::numeric_constant, MR_Hidden, 0, 0, {A}},
+  {tok::semi, MR_Hidden, 0, 1, {A}},
+  };
+  EXPECT_ATTRIBUTES(Result, Attributes);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang

diff  --git a/clang/unittests/Format/TestLexer.h 
b/clang/unittests/Format/TestLexer.h
index 8c5eb2b029fb3..2b56f10dd3793 100644
--- a/clang/unittests/Format/TestLexer.h
+++ b/clang/unittests/Format/TestLexer.h
@@ -55,7 +55,9 @@ inline std::string text(llvm::ArrayRef Tokens) 
{
 
 class TestLexer {
 public:
-  TestLexer() : SourceMgr("test.cpp", "") {}
+  TestLexer(FormatStyle Style = getLLVMStyle())
+  : Style(Style), SourceMgr("test.cpp", ""),
+IdentTable(getFormattingLangOpts(Style)) {}
 
   TokenList lex(llvm::StringRef Code) {
 Buffers.push_back(
@@ -74,7 +76,7 @@ class TestLexer {
 return Result[0];
   }
 
-  FormatStyle Style = getLLVMStyle();
+  FormatStyle Style;
   encoding::Encoding Encoding = encoding::Encoding_UTF8;
   std::vector> Buffers;
   clang::SourceManagerForFile SourceMgr;



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


[clang] 8aa3b8d - [clang-format] Handle typename macros inside cast expressions

2020-09-07 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-07T10:09:17+01:00
New Revision: 8aa3b8da5db2ae73bf536b630915eb9f0ddc15cb

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

LOG: [clang-format] Handle typename macros inside cast expressions

Before: x = (STACK_OF(uint64_t)) & a;
After:  x = (STACK_OF(uint64_t))&a;

Reviewed By: MyDeveloperDay

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

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 795c26889629..a9aeef5e9e52 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -102,6 +102,7 @@ namespace format {
   TYPE(TrailingReturnArrow)
\
   TYPE(TrailingUnaryOperator)  
\
   TYPE(TypenameMacro)  
\
+  TYPE(TypenameMacroParen) 
\
   TYPE(UnaryOperator)  
\
   TYPE(UntouchableMacroFunc)   
\
   TYPE(CSharpStringLiteral)
\

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index fc6a226dc4a1..097843bdca84 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -244,6 +244,8 @@ class AnnotatingParser {
   Contexts.back().IsExpression = false;
 } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
   Left->setType(TT_AttributeParen);
+} else if (Left->Previous && Left->Previous->is(TT_TypenameMacro)) {
+  Left->setType(TT_TypenameMacroParen);
 } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
   // The first argument to a foreach macro is a declaration.
   Contexts.back().IsForEachMacro = true;
@@ -335,6 +337,8 @@ class AnnotatingParser {
 
 if (Left->is(TT_AttributeParen))
   CurrentToken->setType(TT_AttributeParen);
+if (Left->is(TT_TypenameMacroParen))
+  CurrentToken->setType(TT_TypenameMacroParen);
 if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
   CurrentToken->setType(TT_JavaAnnotation);
 if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
@@ -1855,9 +1859,11 @@ class AnnotatingParser {
   }
   return T && T->is(TT_PointerOrReference);
 };
-bool ParensAreType = !Tok.Previous || Tok.Previous->is(TT_TemplateCloser) 
||
- Tok.Previous->isSimpleTypeSpecifier() ||
- IsQualifiedPointerOrReference(Tok.Previous);
+bool ParensAreType =
+!Tok.Previous ||
+Tok.Previous->isOneOf(TT_TemplateCloser, TT_TypenameMacroParen) ||
+Tok.Previous->isSimpleTypeSpecifier() ||
+IsQualifiedPointerOrReference(Tok.Previous);
 bool ParensCouldEndDecl =
 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
 if (ParensAreType && !ParensCouldEndDecl)

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index f224ab03271d..be68da6f2ef6 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -16557,6 +16557,8 @@ TEST_F(FormatTest, TypenameMacros) {
   Macros.PointerAlignment = FormatStyle::PAS_Left;
   verifyFormat("STACK_OF(int)* a;", Macros);
   verifyFormat("STACK_OF(int*)* a;", Macros);
+  verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
+  verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
 }
 
 TEST_F(FormatTest, AmbersandInLamda) {



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


[clang] 9a22eba - [clang-format] Parse __underlying_type(T) as a type

2020-09-07 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-07T10:09:18+01:00
New Revision: 9a22eba15091ea849fa78c09ac4c9f7260071790

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

LOG: [clang-format] Parse __underlying_type(T) as a type

Before: MACRO(__underlying_type(A) * a);
After:  MACRO(__underlying_type(A) *a);

Reviewed By: MyDeveloperDay

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

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 8253bf18fc66..76ef99e72d58 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -528,6 +528,7 @@ struct FormatToken {
 case tok::kw_static_assert:
 case tok::kw__Atomic:
 case tok::kw___attribute:
+case tok::kw___underlying_type:
   return true;
 default:
   return false;

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 0239dbd63d94..4867f9e3d6c1 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -247,7 +247,8 @@ class AnnotatingParser {
   Left->setType(TT_AttributeParen);
 } else if (PrevNonComment &&
PrevNonComment->isOneOf(TT_TypenameMacro, tok::kw_decltype,
-   tok::kw_typeof, tok::kw__Atomic)) {
+   tok::kw_typeof, tok::kw__Atomic,
+   tok::kw___underlying_type)) {
   Left->setType(TT_TypeDeclarationParen);
   // decltype() and typeof() usually contain expressions.
   if (PrevNonComment->isOneOf(tok::kw_decltype, tok::kw_typeof))

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index a5943847882f..b1d46a27ef43 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -169,6 +169,7 @@ TEST_F(FormatTest, NestedNameSpecifiers) {
   verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
   verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
   verifyFormat("static constexpr bool Bar = typeof(bar())::value;");
+  verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;");
   verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;");
   verifyFormat("bool a = 2 < ::SomeFunction();");
   verifyFormat("ALWAYS_INLINE ::std::string getName();");
@@ -7908,6 +7909,7 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyFormat("[](const decltype(*a) &value) {}");
   verifyFormat("[](const typeof(*a) &value) {}");
   verifyFormat("[](const _Atomic(a *) &value) {}");
+  verifyFormat("[](const __underlying_type(a) &value) {}");
   verifyFormat("decltype(a * b) F();");
   verifyFormat("typeof(a * b) F();");
   verifyFormat("#define MACRO() [](A *a) { return 1; }");
@@ -7977,6 +7979,7 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
+  verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
@@ -8075,6 +8078,7 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyFormat("decltype(*::std::declval()) void F();");
   verifyFormat("typeof(*::std::declval()) void F();");
   verifyFormat("_Atomic(*::std::declval()) void F();");
+  verifyFormat("__underlying_type(*::std::declval()) void F();");
   verifyFormat(
   "template ::value &&\n"
@@ -8101,6 +8105,7 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
   verifyIndependentOfContext("MACRO(decltype(A) *a);");
   verifyIndependentOfContext("MACRO(typeof(A) *a);");
+  verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
   verifyIndependentOfContext("MACRO(A *const a);");
   verifyIndependentOfContext("MACRO(A *restrict a);");
   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
@@ -8655,6 +8660,8 @@ TEST_F(FormatTest, BreaksLongDeclarations) {
"LooongFunctionDefinition() 
{}");
   verifyFormat("_Atomic(LongName)\n"
"LooongFunctionDefinition() 
{}");
+  verifyFormat("__underlying_type(LooongName)\n"
+   "LooongFunctionDefinition() 
{}");
   verifyFormat

[clang] cd01eec - [clang-format] Check that */& after typename macros are pointers/references

2020-09-07 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-07T10:09:18+01:00
New Revision: cd01eec14bc045a8616604cadf94dba025090ba5

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

LOG: [clang-format] Check that */& after typename macros are pointers/references

Reviewed By: MyDeveloperDay

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

Added: 


Modified: 
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index be68da6f2ef6..978c22c6ee69 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8041,6 +8041,14 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("vector v;");
+  FormatStyle TypeMacros = getLLVMStyle();
+  TypeMacros.TypenameMacros = {"LIST"};
+  verifyFormat("vector v;", TypeMacros);
+  verifyFormat("vector v;", TypeMacros);
+  verifyFormat("vector v;", TypeMacros);
+  verifyFormat("vector v;", TypeMacros);
+  verifyFormat("vector v;", TypeMacros); // multiplication
+
   FormatStyle CustomQualifier = getLLVMStyle();
   // Add indentifers that should not be parsed as a qualifier by default.
   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
@@ -8105,6 +8113,9 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   // a type declaration:
   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
+  // Also check that TypenameMacros prevents parsing it as multiplication:
+  verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
+  verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
 
   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
   verifyFormat("void f() { f(float{1}, a * a); }");
@@ -16553,12 +16564,15 @@ TEST_F(FormatTest, TypenameMacros) {
   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
+  verifyFormat("vector x;", Macros);
+  verifyFormat("vector f(LIST(uint64_t) *arg);", 
Macros);
 
   Macros.PointerAlignment = FormatStyle::PAS_Left;
   verifyFormat("STACK_OF(int)* a;", Macros);
   verifyFormat("STACK_OF(int*)* a;", Macros);
   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
+  verifyFormat("vector x;", Macros);
 }
 
 TEST_F(FormatTest, AmbersandInLamda) {



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


[clang] 05147d3 - [clang-format] Correctly parse function declarations with TypenameMacros

2020-09-07 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-07T10:09:18+01:00
New Revision: 05147d33091720e2df929d6fea3b0fd2a657ac61

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

LOG: [clang-format] Correctly parse function declarations with TypenameMacros

When using the always break after return type setting:
Before:
SomeType funcdecl(LIST(uint64_t));
After:
SomeType
funcdecl(LIST(uint64_t));"

Reviewed By: MyDeveloperDay

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 4867f9e3d6c1..5dd6a7a9da40 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2400,6 +2400,8 @@ static bool isFunctionDeclarationName(const FormatToken 
&Current,
 return true;
   for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
Tok = Tok->Next) {
+if (Tok->is(TT_TypeDeclarationParen))
+  return true;
 if (Tok->isOneOf(tok::l_paren, TT_TemplateOpener) && Tok->MatchingParen) {
   Tok = Tok->MatchingParen;
   continue;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index b1d46a27ef43..b198efa4af9e 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -6681,9 +6681,12 @@ TEST_F(FormatTest, ReturnTypeBreakingStyle) {
Style);
 
   // All declarations and definitions should have the return type moved to its
-  // own
-  // line.
+  // own line.
   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
+  Style.TypenameMacros = {"LIST"};
+  verifyFormat("SomeType\n"
+   "funcdecl(LIST(uint64_t));",
+   Style);
   verifyFormat("class E {\n"
"  int\n"
"  f() {\n"



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


[clang] 56fa7d1 - [clang-format] Fix formatting of _Atomic() qualifier

2020-09-07 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-07T10:09:18+01:00
New Revision: 56fa7d1dc6a8d23111ff84171036f333cf9cddf2

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

LOG: [clang-format] Fix formatting of _Atomic() qualifier

Before: _Atomic(uint64_t) * a;
After: _Atomic(uint64_t) *a;

This treats _Atomic the same as the the TypenameMacros and decltype. It
also allows some cleanup by removing checks whether the token before a
paren is kw_decltype and instead checking for TT_TypeDeclarationParen.
While touching this code also extend the decltype test cases to also check
for typeof() and _Atomic(T).

Reviewed By: MyDeveloperDay

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

Added: 


Modified: 
clang/lib/Format/FormatToken.cpp
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.cpp 
b/clang/lib/Format/FormatToken.cpp
index 4bc865b043fd..8e4994f4c0d5 100644
--- a/clang/lib/Format/FormatToken.cpp
+++ b/clang/lib/Format/FormatToken.cpp
@@ -62,6 +62,7 @@ bool FormatToken::isSimpleTypeSpecifier() const {
   case tok::kw_char32_t:
   case tok::kw_typeof:
   case tok::kw_decltype:
+  case tok::kw__Atomic:
 return true;
   default:
 return false;

diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index a9aeef5e9e52..8253bf18fc66 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -101,8 +101,8 @@ namespace format {
   TYPE(TrailingAnnotation) 
\
   TYPE(TrailingReturnArrow)
\
   TYPE(TrailingUnaryOperator)  
\
+  TYPE(TypeDeclarationParen)   
\
   TYPE(TypenameMacro)  
\
-  TYPE(TypenameMacroParen) 
\
   TYPE(UnaryOperator)  
\
   TYPE(UntouchableMacroFunc)   
\
   TYPE(CSharpStringLiteral)
\
@@ -526,6 +526,7 @@ struct FormatToken {
 case tok::kw_decltype:
 case tok::kw_noexcept:
 case tok::kw_static_assert:
+case tok::kw__Atomic:
 case tok::kw___attribute:
   return true;
 default:

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 097843bdca84..0239dbd63d94 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -185,6 +185,8 @@ class AnnotatingParser {
 if (!CurrentToken)
   return false;
 FormatToken *Left = CurrentToken->Previous;
+FormatToken *PrevNonComment =
+Left ? Left->getPreviousNonComment() : nullptr;
 Left->ParentBracket = Contexts.back().ContextKind;
 ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
 
@@ -216,9 +218,8 @@ class AnnotatingParser {
   // export type X = (...);
   Contexts.back().IsExpression = false;
 } else if (Left->Previous &&
-   (Left->Previous->isOneOf(tok::kw_static_assert, 
tok::kw_decltype,
-tok::kw_while, tok::l_paren,
-tok::comma) ||
+   (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_while,
+tok::l_paren, tok::comma) ||
 Left->Previous->isIf() ||
 Left->Previous->is(TT_BinaryOperator))) {
   // static_assert, if and while usually contain expressions.
@@ -242,10 +243,15 @@ class AnnotatingParser {
 } else if (Contexts[Contexts.size() - 2].CaretFound) {
   // This is the parameter list of an ObjC block.
   Contexts.back().IsExpression = false;
-} else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
+} else if (PrevNonComment && PrevNonComment->is(tok::kw___attribute)) {
   Left->setType(TT_AttributeParen);
-} else if (Left->Previous && Left->Previous->is(TT_TypenameMacro)) {
-  Left->setType(TT_TypenameMacroParen);
+} else if (PrevNonComment &&
+   PrevNonComment->isOneOf(TT_TypenameMacro, tok::kw_decltype,
+   tok::kw_typeof, tok::kw__Atomic)) {
+  Left->setType(TT_TypeDeclarationParen);
+  // decltype() and typeof() usually contain expressions.
+  if (PrevNonComment->isOneOf(tok::kw_decltype, tok::kw_typeof))
+Contexts.back().IsExpression = true;
 } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
   // The fi

[clang] e7bd058 - [clang-format] Allow configuring list of macros that map to attributes

2020-09-07 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-07T10:09:17+01:00
New Revision: e7bd058c7e2cb2c675a4b78ec770ea725bff8c64

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

LOG: [clang-format] Allow configuring list of macros that map to attributes

This adds a `AttributeMacros` configuration option that causes certain
identifiers to be parsed like a __attribute__((foo)) annotation.
This is motivated by our CHERI C/C++ fork which adds a __capability
qualifier for pointer/reference. Without this change clang-format parses
many type declarations as multiplications/bitwise-and instead.
I initially considered adding "__capability" as a new clang-format keyword,
but having a list of macros that should be treated as attributes is more
flexible since it can be used e.g. for static analyzer annotations or other 
language
extensions.

Example: std::vector -> std::vector

Depends on D86775 (to apply cleanly)

Reviewed By: MyDeveloperDay, jrtc27

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/lib/Format/FormatToken.h
clang/lib/Format/FormatTokenLexer.cpp
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index c35718b51248..72a25032151f 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -758,7 +758,24 @@ the configuration (without a prefix: ``Auto``).
  int b) {
}
 
+**AttributeMacros** (``std::vector``)
+  A vector of strings that should be interpreted as attributes/qualifiers
+  instead of identifiers. This can be useful for language extensions or
+  static analyzer annotations:
 
+  .. code-block:: c++
+
+x = (char *__capability)&y;
+int function(void) __ununsed;
+void only_writes_to_buffer(char *__output buffer);
+
+  In the .clang-format configuration file, this can be configured like:
+
+  .. code-block:: yaml
+
+AttributeMacros: ['__capability', '__output', '__ununsed']
+
+  For example: __capability.
 
 **BinPackArguments** (``bool``)
   If ``false``, a function call's arguments will either be all on the

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 269eab971a2c..6bb828d60071 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -583,6 +583,24 @@ struct FormatStyle {
   /// The template declaration breaking style to use.
   BreakTemplateDeclarationsStyle AlwaysBreakTemplateDeclarations;
 
+  /// A vector of strings that should be interpreted as attributes/qualifiers
+  /// instead of identifiers. This can be useful for language extensions or
+  /// static analyzer annotations.
+  ///
+  /// For example:
+  /// \code
+  ///   x = (char *__capability)&y;
+  ///   int function(void) __ununsed;
+  ///   void only_writes_to_buffer(char *__output buffer);
+  /// \endcode
+  ///
+  /// In the .clang-format configuration file, this can be configured like:
+  /// \code{.yaml}
+  ///   AttributeMacros: ['__capability', '__output', '__ununsed']
+  /// \endcode
+  ///
+  std::vector AttributeMacros;
+
   /// If ``false``, a function call's arguments will either be all on the
   /// same line or will have one line each.
   /// \code
@@ -2351,6 +2369,7 @@ struct FormatStyle {
R.AlwaysBreakBeforeMultilineStrings &&
AlwaysBreakTemplateDeclarations ==
R.AlwaysBreakTemplateDeclarations &&
+   AttributeMacros == R.AttributeMacros &&
BinPackArguments == R.BinPackArguments &&
BinPackParameters == R.BinPackParameters &&
BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&

diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index fe11cba9bfdf..5dda2bda06b5 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -475,6 +475,7 @@ template <> struct MappingTraits {
Style.AlwaysBreakBeforeMultilineStrings);
 IO.mapOptional("AlwaysBreakTemplateDeclarations",
Style.AlwaysBreakTemplateDeclarations);
+IO.mapOptional("AttributeMacros", Style.AttributeMacros);
 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
 IO.mapOptional("BraceWrapping", Style.BraceWrapping);
@@ -842,6 +843,7 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind 
Language) {
   LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
   LLVMStyle.AlwaysBreakBeforeMultilineStrings = false

[clang] e0ff5a8 - [clang-format] Add a test showing the current config file list parsing

2020-09-04 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-04T16:57:46+01:00
New Revision: e0ff5a8410ea58ba3d2e75791789a28ce976a7e7

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

LOG: [clang-format] Add a test showing the current config file list parsing

Currently clang-format starts overriding the default values at index 0
(keeping the existing values) instead of appending or replacing all values.
This patch simply checks the current (IMO surprising) behaviour and does
not attempt to change it.

Reviewed By: MyDeveloperDay

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

Added: 
clang/test/Format/dump-config-list-override.cpp

Modified: 


Removed: 




diff  --git a/clang/test/Format/dump-config-list-override.cpp 
b/clang/test/Format/dump-config-list-override.cpp
new file mode 100644
index ..df4c6ad1333e
--- /dev/null
+++ b/clang/test/Format/dump-config-list-override.cpp
@@ -0,0 +1,24 @@
+/// Check that the ForEachMacros, etc. config entries replace default values 
instead of appending
+/// FIXME: clang-format currently start overriding at index 0 (keeping the 
remaining
+/// values) instead of either appending or completely replacing the values.
+/// This behaviour is highly confusing. For now this test documents the 
current state.
+// RUN: clang-format -style="{BasedOnStyle: LLVM}" -dump-config %s | \
+// RUN:   FileCheck %s --check-prefixes=CHECK,DEFAULT
+// RUN: clang-format -style="{BasedOnStyle: LLVM, ForEachMacros: 
['OVERRIDE_FOREACH']}" -dump-config %s | \
+// RUN:   FileCheck %s --check-prefixes=CHECK,OVERRIDE,FIXME-SHOULD-NOT-BE
+// RUN: clang-format -style="{BasedOnStyle: LLVM, ForEachMacros: ['M1', 'M2', 
'M3', 'M4']}" -dump-config %s | \
+// RUN:   FileCheck %s --check-prefixes=CHECK,MORE-ENTRIES-THAN-DEFAULT
+
+
+// CHECK-LABEL:   ForEachMacros:
+// DEFAULT-NEXT:  {{^  }}- foreach
+// DEFAULT-NEXT:  {{^  }}- Q_FOREACH
+// DEFAULT-NEXT:  {{^  }}- BOOST_FOREACH
+// OVERRIDE-NEXT: {{^  }}- OVERRIDE_FOREACH
+// FIXME-SHOULD-NOT-BE-NEXT:  {{^  }}- Q_FOREACH
+// FIXME-SHOULD-NOT-BE-NEXT:  {{^  }}- BOOST_FOREACH
+// MORE-ENTRIES-THAN-DEFAULT-NEXT: {{^  }}- M1
+// MORE-ENTRIES-THAN-DEFAULT-NEXT: {{^  }}- M2
+// MORE-ENTRIES-THAN-DEFAULT-NEXT: {{^  }}- M3
+// MORE-ENTRIES-THAN-DEFAULT-NEXT: {{^  }}- M4
+// CHECK-NEXT:{{^[F-Z]}}



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


[clang] 2108bce - FormatTest: Provide real line number in failure messages

2020-09-04 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-04T16:57:46+01:00
New Revision: 2108bceceb5e6eca361aaa6b10441d83bd9edc1b

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

LOG: FormatTest: Provide real line number in failure messages

Currently a test failure always reports a line number inside verifyFormat()
which is not very helpful to see which test failed. With this change we now
emit the line number where the verify function was called. When using an
IDE such as CLion, the output now includes a clickable link that points to
the call site.

Reviewed By: MyDeveloperDay

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

Added: 


Modified: 
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 716fe2bf50ae..a2d694947990 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -20,6 +20,7 @@
 
 using clang::tooling::ReplacementTest;
 using clang::tooling::toReplacements;
+using testing::internal::ScopedTrace;
 
 namespace clang {
 namespace format {
@@ -65,8 +66,10 @@ class FormatTest : public ::testing::Test {
 return getStyleWithColumns(getGoogleStyle(), ColumnLimit);
   }
 
-  void verifyFormat(llvm::StringRef Expected, llvm::StringRef Code,
-const FormatStyle &Style = getLLVMStyle()) {
+  void _verifyFormat(const char *File, int Line, llvm::StringRef Expected,
+ llvm::StringRef Code,
+ const FormatStyle &Style = getLLVMStyle()) {
+ScopedTrace t(File, Line, ::testing::Message() << Code.str());
 EXPECT_EQ(Expected.str(), format(Expected, Style))
 << "Expected code is not stable";
 EXPECT_EQ(Expected.str(), format(Code, Style));
@@ -79,24 +82,24 @@ class FormatTest : public ::testing::Test {
 }
   }
 
-  void verifyFormat(llvm::StringRef Code,
-const FormatStyle &Style = getLLVMStyle()) {
-verifyFormat(Code, test::messUp(Code), Style);
+  void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
+ const FormatStyle &Style = getLLVMStyle()) {
+_verifyFormat(File, Line, Code, test::messUp(Code), Style);
   }
 
-  void verifyIncompleteFormat(llvm::StringRef Code,
-  const FormatStyle &Style = getLLVMStyle()) {
+  void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef 
Code,
+   const FormatStyle &Style = getLLVMStyle()) {
+ScopedTrace t(File, Line, ::testing::Message() << Code.str());
 EXPECT_EQ(Code.str(),
   format(test::messUp(Code), Style, SC_ExpectIncomplete));
   }
 
-  void verifyGoogleFormat(llvm::StringRef Code) {
-verifyFormat(Code, getGoogleStyle());
-  }
-
-  void verifyIndependentOfContext(llvm::StringRef text) {
-verifyFormat(text);
-verifyFormat(llvm::Twine("void f() { " + text + " }").str());
+  void _verifyIndependentOfContext(const char *File, int Line,
+   llvm::StringRef Text,
+   const FormatStyle &Style = getLLVMStyle()) {
+_verifyFormat(File, Line, Text, Style);
+_verifyFormat(File, Line, llvm::Twine("void f() { " + Text + " }").str(),
+  Style);
   }
 
   /// \brief Verify that clang-format does not crash on the given input.
@@ -108,6 +111,13 @@ class FormatTest : public ::testing::Test {
   int ReplacementCount;
 };
 
+#define verifyIndependentOfContext(...)
\
+  _verifyIndependentOfContext(__FILE__, __LINE__, __VA_ARGS__)
+#define verifyIncompleteFormat(...)
\
+  _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__)
+#define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__)
+#define verifyGoogleFormat(Code) verifyFormat(Code, getGoogleStyle())
+
 TEST_F(FormatTest, MessUp) {
   EXPECT_EQ("1 2 3", test::messUp("1 2 3"));
   EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n"));



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


[clang] 8c810ac - [clang-format] Parse __ptr32/__ptr64 as a pointer qualifier

2020-09-04 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-04T16:56:21+01:00
New Revision: 8c810acc94ed462238242c04c75ab33fc96da6e8

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

LOG: [clang-format] Parse __ptr32/__ptr64 as a pointer qualifier

Before:
x = (foo *__ptr32) * v;
MACRO(A * __ptr32 a);
x = (foo *__ptr64) * v;
MACRO(A * __ptr64 a);

After:
x = (foo *__ptr32)*v;
MACRO(A *__ptr32 a);
x = (foo *__ptr64)*v;
MACRO(A *__ptr64 a);

Depends on D86721 (to apply cleanly)

Reviewed By: MyDeveloperDay

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

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index a54600a478a4..ad72a95062ab 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -442,7 +442,7 @@ struct FormatToken {
   bool canBePointerOrReferenceQualifier() const {
 return isOneOf(tok::kw_const, tok::kw_restrict, tok::kw_volatile,
tok::kw___attribute, tok::kw__Nonnull, tok::kw__Nullable,
-   tok::kw__Null_unspecified);
+   tok::kw__Null_unspecified, tok::kw___ptr32, 
tok::kw___ptr64);
   }
 
   /// Determine whether the token is a simple-type-specifier.

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 14c97784b738..716fe2bf50ae 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8028,6 +8028,8 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("foo();");
@@ -8070,6 +8072,8 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
+  verifyIndependentOfContext("MACRO(A *__ptr32 a);");
+  verifyIndependentOfContext("MACRO(A *__ptr64 a);");
   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
   verifyFormat("void f() { f(float{1}, a * a); }");
   // FIXME: Is there a way to make this work?
@@ -8141,6 +8145,8 @@ TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
   verifyFormat("x = (foo *_Nonnull)*v;");
   verifyFormat("x = (foo *[[clang::attr]])*v;");
   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
+  verifyFormat("x = (foo *__ptr32)*v;");
+  verifyFormat("x = (foo *__ptr64)*v;");
 
   // Check that we handle multiple trailing qualifiers and skip them all to
   // determine that the expression is a cast to a pointer type.
@@ -8149,7 +8155,7 @@ TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
   StringRef AllQualifiers =
   "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified 
"
-  "_Nonnull [[clang::attr]]";
+  "_Nonnull [[clang::attr]] __ptr32 __ptr64";
   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), 
LongPointerRight);
   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
 



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


[clang] d70e05c - [clang-format] Parse double-square attributes as pointer qualifiers

2020-09-02 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-02T18:35:21+01:00
New Revision: d70e05c9e36ada3ea6341764a3bc34de7de7d8dd

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

LOG: [clang-format] Parse double-square attributes as pointer qualifiers

Before: x = (foo *[[clang::attr]]) * v;
After:  x = (foo *[[clang::attr]])*v;

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index a9077500e041..f04f101f0459 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1840,6 +1840,12 @@ class AnnotatingParser {
 T = T->MatchingParen->Previous->Previous;
 continue;
   }
+} else if (T->is(TT_AttributeSquare)) {
+  // Handle `x = (foo *[[clang::foo]])&v;`:
+  if (T->MatchingParen && T->MatchingParen->Previous) {
+T = T->MatchingParen->Previous;
+continue;
+  }
 } else if (T->canBePointerOrReferenceQualifier()) {
   T = T->Previous;
   continue;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index f2978cdbed8d..14c97784b738 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8068,6 +8068,8 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
+  verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
+  verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
   verifyFormat("void f() { f(float{1}, a * a); }");
   // FIXME: Is there a way to make this work?
@@ -8137,14 +8139,17 @@ TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
   verifyFormat("x = (foo *_Nullable)*v;");
   verifyFormat("x = (foo *_Null_unspecified)*v;");
   verifyFormat("x = (foo *_Nonnull)*v;");
+  verifyFormat("x = (foo *[[clang::attr]])*v;");
+  verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
 
   // Check that we handle multiple trailing qualifiers and skip them all to
   // determine that the expression is a cast to a pointer type.
   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
-  StringRef AllQualifiers = "const volatile restrict __attribute__((foo)) "
-"_Nonnull _Null_unspecified _Nonnull";
+  StringRef AllQualifiers =
+  "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified 
"
+  "_Nonnull [[clang::attr]]";
   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), 
LongPointerRight);
   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
 



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


[clang] 37cdabd - [clang-format] Parse __attribute((foo)) as a pointer qualifier

2020-08-28 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-08-28T11:31:47+01:00
New Revision: 37cdabdb82e33e0d659c92a6cbb7049c31e0acbc

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

LOG: [clang-format] Parse __attribute((foo)) as a pointer qualifier

Before: void f() { MACRO(A * __attribute((foo)) a); }
After:  void f() { MACRO(A *__attribute((foo)) a); }

Also check that the __attribute__ alias is handled.

Reviewed By: MyDeveloperDay

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index dfcd92dcd3e0..e5c0a7cb033c 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1892,7 +1892,7 @@ class AnnotatingParser {
 if (!NextToken ||
 NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const,
tok::kw_restrict, tok::kw_volatile,
-   tok::kw_noexcept) ||
+   tok::kw___attribute, tok::kw_noexcept) ||
 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
   return TT_PointerOrReference;
 

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 95fdbec4b97b..1234462a47ec 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8059,6 +8059,8 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyIndependentOfContext("MACRO(A *volatile a);");
   verifyIndependentOfContext("MACRO(A *__volatile a);");
   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
+  verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
+  verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
   verifyFormat("void f() { f(float{1}, a * a); }");
   // FIXME: Is there a way to make this work?



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


[clang] 1908da2 - [clang-format] Parse volatile as a pointer qualifier

2020-08-28 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-08-28T11:31:47+01:00
New Revision: 1908da2658fc26154e4103a50faeeca804c7c57d

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

LOG: [clang-format] Parse volatile as a pointer qualifier

Before: void f() { MACRO(A * volatile a); }
After:  void f() { MACRO(A *volatile a); }

Also check that the __volatile and __volatile__ aliases are handled.

Reviewed By: JakeMerdichAMD

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 11acb597aa40..bcd0bf913ecb 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1891,7 +1891,7 @@ class AnnotatingParser {
 const FormatToken *NextToken = Tok.getNextNonComment();
 if (!NextToken ||
 NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const,
-   tok::kw_noexcept) ||
+   tok::kw_volatile, tok::kw_noexcept) ||
 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
   return TT_PointerOrReference;
 

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index dcd9da77a390..7ea00ff33ca0 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8053,6 +8053,9 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyIndependentOfContext("MACRO(auto *a);");
   verifyIndependentOfContext("MACRO(const A *a);");
   verifyIndependentOfContext("MACRO(A *const a);");
+  verifyIndependentOfContext("MACRO(A *volatile a);");
+  verifyIndependentOfContext("MACRO(A *__volatile a);");
+  verifyIndependentOfContext("MACRO(A *__volatile__ a);");
   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
   verifyFormat("void f() { f(float{1}, a * a); }");
   // FIXME: Is there a way to make this work?



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


[clang] d304360 - [clang-format] Parse nullability attributes as a pointer qualifier

2020-08-28 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-08-28T11:31:47+01:00
New Revision: d304360decefae3fa5c807a8cd0d7d4501a1cc4b

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

LOG: [clang-format] Parse nullability attributes as a pointer qualifier

Before:
void f() { MACRO(A * _Nonnull a); }
void f() { MACRO(A * _Nullable a); }
void f() { MACRO(A * _Null_unspecified a); }

After:
void f() { MACRO(A *_Nonnull a); }
void f() { MACRO(A *_Nullable a); }
void f() { MACRO(A *_Null_unspecified a); }

Reviewed By: JakeMerdichAMD

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index e5c0a7cb033c..3e25ef6b9774 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1890,9 +1890,10 @@ class AnnotatingParser {
 
 const FormatToken *NextToken = Tok.getNextNonComment();
 if (!NextToken ||
-NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const,
-   tok::kw_restrict, tok::kw_volatile,
-   tok::kw___attribute, tok::kw_noexcept) ||
+NextToken->isOneOf(
+tok::arrow, tok::equal, tok::kw_const, tok::kw_restrict,
+tok::kw_volatile, tok::kw___attribute, tok::kw__Nonnull,
+tok::kw__Nullable, tok::kw__Null_unspecified, tok::kw_noexcept) ||
 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
   return TT_PointerOrReference;
 

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 1234462a47ec..7e505c2401e9 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8025,6 +8025,10 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("foo();");
   verifyFormat("foo();");
@@ -8059,6 +8063,9 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyIndependentOfContext("MACRO(A *volatile a);");
   verifyIndependentOfContext("MACRO(A *__volatile a);");
   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
+  verifyIndependentOfContext("MACRO(A *_Nonnull a);");
+  verifyIndependentOfContext("MACRO(A *_Nullable a);");
+  verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");



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


[clang] 4f10369 - [clang-format] Parse restrict as a pointer qualifier

2020-08-28 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-08-28T11:31:47+01:00
New Revision: 4f103695646bb9e16609a276072781f5a933570d

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

LOG: [clang-format] Parse restrict as a pointer qualifier

Before: void f() { MACRO(A * restrict a); }
After:  void f() { MACRO(A *restrict a); }

Also check that the __restrict and __restrict__ aliases are handled.

Reviewed By: JakeMerdichAMD

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

Added: 


Modified: 
clang/lib/Format/Format.cpp
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 8c1d7c90e02a..fe11cba9bfdf 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -2739,6 +2739,7 @@ LangOptions getFormattingLangOpts(const FormatStyle 
&Style) {
   LangOpts.ObjC = 1;
   LangOpts.MicrosoftExt = 1;// To get kw___try, kw___finally.
   LangOpts.DeclSpecKeyword = 1; // To get __declspec.
+  LangOpts.C99 = 1; // To get kw_restrict for non-underscore-prefixed restrict.
   return LangOpts;
 }
 

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index bcd0bf913ecb..dfcd92dcd3e0 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1891,7 +1891,8 @@ class AnnotatingParser {
 const FormatToken *NextToken = Tok.getNextNonComment();
 if (!NextToken ||
 NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const,
-   tok::kw_volatile, tok::kw_noexcept) ||
+   tok::kw_restrict, tok::kw_volatile,
+   tok::kw_noexcept) ||
 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
   return TT_PointerOrReference;
 

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 7ea00ff33ca0..95fdbec4b97b 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8053,6 +8053,9 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyIndependentOfContext("MACRO(auto *a);");
   verifyIndependentOfContext("MACRO(const A *a);");
   verifyIndependentOfContext("MACRO(A *const a);");
+  verifyIndependentOfContext("MACRO(A *restrict a);");
+  verifyIndependentOfContext("MACRO(A *__restrict__ a);");
+  verifyIndependentOfContext("MACRO(A *__restrict a);");
   verifyIndependentOfContext("MACRO(A *volatile a);");
   verifyIndependentOfContext("MACRO(A *__volatile a);");
   verifyIndependentOfContext("MACRO(A *__volatile__ a);");



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


[clang] 96824ab - [clang-format] Detect pointer qualifiers in cast expressions

2020-08-28 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-08-28T11:31:47+01:00
New Revision: 96824abe7d80fc499032dab598968436132fcfb5

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

LOG: [clang-format] Detect pointer qualifiers in cast expressions

When guessing whether a closing paren is then end of a cast expression also
skip over pointer qualifiers while looking for TT_PointerOrReference.
This prevents some address-of and dereference operators from being parsed
as a binary operator.

Before:
x = (foo *const) * v;
x = (foo *const volatile restrict __attribute__((foo)) _Nonnull 
_Null_unspecified _Nonnull) & v;

After:
x = (foo *const)*v;
x = (foo *const volatile restrict __attribute__((foo)) _Nonnull 
_Null_unspecified _Nonnull)&v;

Reviewed By: MyDeveloperDay

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

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index ece1bf4b97f7..a54600a478a4 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -439,6 +439,12 @@ struct FormatToken {
(!ColonRequired || (Next && Next->is(tok::colon)));
   }
 
+  bool canBePointerOrReferenceQualifier() const {
+return isOneOf(tok::kw_const, tok::kw_restrict, tok::kw_volatile,
+   tok::kw___attribute, tok::kw__Nonnull, tok::kw__Nullable,
+   tok::kw__Null_unspecified);
+  }
+
   /// Determine whether the token is a simple-type-specifier.
   bool isSimpleTypeSpecifier() const;
 

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 3e25ef6b9774..a9077500e041 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1827,10 +1827,30 @@ class AnnotatingParser {
   return true;
 
 // Heuristically try to determine whether the parentheses contain a type.
-bool ParensAreType =
-!Tok.Previous ||
-Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
-Tok.Previous->isSimpleTypeSpecifier();
+auto IsQualifiedPointerOrReference = [](FormatToken *T) {
+  // This is used to handle cases such as x = (foo *const)&y;
+  assert(!T->isSimpleTypeSpecifier() && "Should have already been 
checked");
+  // Strip trailing qualifiers such as const or volatile when checking
+  // whether the parens could be a cast to a pointer/reference type.
+  while (T) {
+if (T->is(TT_AttributeParen)) {
+  // Handle `x = (foo *__attribute__((foo)))&v;`:
+  if (T->MatchingParen && T->MatchingParen->Previous &&
+  T->MatchingParen->Previous->is(tok::kw___attribute)) {
+T = T->MatchingParen->Previous->Previous;
+continue;
+  }
+} else if (T->canBePointerOrReferenceQualifier()) {
+  T = T->Previous;
+  continue;
+}
+break;
+  }
+  return T && T->is(TT_PointerOrReference);
+};
+bool ParensAreType = !Tok.Previous || Tok.Previous->is(TT_TemplateCloser) 
||
+ Tok.Previous->isSimpleTypeSpecifier() ||
+ IsQualifiedPointerOrReference(Tok.Previous);
 bool ParensCouldEndDecl =
 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
 if (ParensAreType && !ParensCouldEndDecl)
@@ -1890,10 +1910,8 @@ class AnnotatingParser {
 
 const FormatToken *NextToken = Tok.getNextNonComment();
 if (!NextToken ||
-NextToken->isOneOf(
-tok::arrow, tok::equal, tok::kw_const, tok::kw_restrict,
-tok::kw_volatile, tok::kw___attribute, tok::kw__Nonnull,
-tok::kw__Nullable, tok::kw__Null_unspecified, tok::kw_noexcept) ||
+NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_noexcept) ||
+NextToken->canBePointerOrReferenceQualifier() ||
 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
   return TT_PointerOrReference;
 

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 7e505c2401e9..f2978cdbed8d 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8127,6 +8127,33 @@ TEST_F(FormatTest, UnderstandsAttributes) {
AfterType);
 }
 
+TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
+  // Check that qualifiers on pointers don't break parsing of casts.
+  verifyFormat("x = (foo *const)*v;");
+  verifyFormat("x = (foo *volatile)*v;");
+  verifyFormat("x = (foo *restrict)*v;");
+  verifyFormat("x = (foo *__attribute__((foo)))*v;");
+  verifyFormat("x = (foo *_Nonnull)*v;");
+  verifyForm

[clang] e150d2c - [update_cc_test_checks.py] Add test for D84511

2020-08-06 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-08-06T09:15:56+01:00
New Revision: e150d2cab8688a2b3b7d395bfbbc152b08df9033

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

LOG: [update_cc_test_checks.py] Add test for D84511

Reviewed By: MaskRay

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

Added: 


Modified: 
clang/test/utils/update_cc_test_checks/basic-cplusplus.test
clang/test/utils/update_cc_test_checks/lit.local.cfg

Removed: 




diff  --git a/clang/test/utils/update_cc_test_checks/basic-cplusplus.test 
b/clang/test/utils/update_cc_test_checks/basic-cplusplus.test
index 10be017388c6..3557e18f5ac9 100644
--- a/clang/test/utils/update_cc_test_checks/basic-cplusplus.test
+++ b/clang/test/utils/update_cc_test_checks/basic-cplusplus.test
@@ -2,6 +2,9 @@
 
 # RUN: cp %S/Inputs/basic-cplusplus.cpp %t.cpp && %update_cc_test_checks %t.cpp
 # RUN: 
diff  -u %S/Inputs/basic-cplusplus.cpp.expected %t.cpp
+## Check that it also works with the --llvm-bin flag instead of --clang
+# RUN: cp %S/Inputs/basic-cplusplus.cpp %t.cpp && %update_cc_test_checks 
--clang='' --llvm-bin=%clang_tools_dir %t.cpp
+# RUN: 
diff  -u %S/Inputs/basic-cplusplus.cpp.expected %t.cpp
 ## Check that re-running update_cc_test_checks doesn't change the output
 # RUN: %update_cc_test_checks %t.cpp
 # RUN: 
diff  -u %S/Inputs/basic-cplusplus.cpp.expected %t.cpp

diff  --git a/clang/test/utils/update_cc_test_checks/lit.local.cfg 
b/clang/test/utils/update_cc_test_checks/lit.local.cfg
index 0250446423cb..3fef02881853 100644
--- a/clang/test/utils/update_cc_test_checks/lit.local.cfg
+++ b/clang/test/utils/update_cc_test_checks/lit.local.cfg
@@ -23,3 +23,5 @@ config.substitutions.append(
 ('%update_cc_test_checks', "%s %s %s" % (
 shell_quote(config.python_executable), shell_quote(script_path),
 extra_args)))
+config.substitutions.append(
+('%clang_tools_dir', shell_quote(config.clang_tools_dir)))



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


[clang] a80afc0 - [UpdateTestChecks] Add UTC_ARGS support for update_{llc,cc}_test_checks.py

2020-07-08 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-07-08T11:00:10+01:00
New Revision: a80afc032859ebe65af283f76b38a0f5921b683f

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

LOG: [UpdateTestChecks] Add UTC_ARGS support for update_{llc,cc}_test_checks.py

https://reviews.llvm.org/D69701 added support for on-the-fly argument
changes for update scripts. I recently wanted to keep some manual check
lines in a test generated by update_cc_test_checks.py in our CHERI fork, so
this commit adds support for UTC_ARGS in update_cc_test_checks.py. And since
I was refactoring the code to be in common.py, I also added it for
update_llc_test_checks.py.

Reviewed By: jdoerfert, MaskRay
Differential Revision: https://reviews.llvm.org/D78478

Added: 
clang/test/utils/update_cc_test_checks/Inputs/on_the_fly_arg_change.c

clang/test/utils/update_cc_test_checks/Inputs/on_the_fly_arg_change.c.expected
clang/test/utils/update_cc_test_checks/on_the_fly_arg_change.test

llvm/test/tools/UpdateTestChecks/update_llc_test_checks/Inputs/on_the_fly_arg_change.ll

llvm/test/tools/UpdateTestChecks/update_llc_test_checks/Inputs/on_the_fly_arg_change.ll.expected

llvm/test/tools/UpdateTestChecks/update_llc_test_checks/on_the_fly_arg_change.test

Modified: 

clang/test/utils/update_cc_test_checks/Inputs/mangled_names.c.funcsig.expected
clang/test/utils/update_cc_test_checks/mangled_names.test

llvm/test/tools/UpdateTestChecks/update_llc_test_checks/Inputs/basic.ll.expected
llvm/test/tools/UpdateTestChecks/update_llc_test_checks/basic.test
llvm/utils/update_cc_test_checks.py
llvm/utils/update_llc_test_checks.py

Removed: 




diff  --git 
a/clang/test/utils/update_cc_test_checks/Inputs/mangled_names.c.funcsig.expected
 
b/clang/test/utils/update_cc_test_checks/Inputs/mangled_names.c.funcsig.expected
index 005b2f242747..e76cf074bdb7 100644
--- 
a/clang/test/utils/update_cc_test_checks/Inputs/mangled_names.c.funcsig.expected
+++ 
b/clang/test/utils/update_cc_test_checks/Inputs/mangled_names.c.funcsig.expected
@@ -1,4 +1,4 @@
-// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --function-signature
 // Example input for update_cc_test_checks
 // RUN: %clang_cc1 -triple=x86_64-unknown-linux-gnu -emit-llvm -o - %s | 
FileCheck %s
 

diff  --git 
a/clang/test/utils/update_cc_test_checks/Inputs/on_the_fly_arg_change.c 
b/clang/test/utils/update_cc_test_checks/Inputs/on_the_fly_arg_change.c
new file mode 100644
index ..8956e6b52a21
--- /dev/null
+++ b/clang/test/utils/update_cc_test_checks/Inputs/on_the_fly_arg_change.c
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -triple=x86_64-unknown-linux-gnu -emit-llvm -o - %s | 
FileCheck %s
+
+int checks_please() {
+  return 1;
+}
+
+// UTC_ARGS: --disable
+
+int no_checks_please() {
+  // Manual CHECK line should be retained:
+  // CHECK: manual check line
+  return -1;
+}
+
+// UTC_ARGS: --enable
+
+
+int checks_again() {
+  return 2;
+}

diff  --git 
a/clang/test/utils/update_cc_test_checks/Inputs/on_the_fly_arg_change.c.expected
 
b/clang/test/utils/update_cc_test_checks/Inputs/on_the_fly_arg_change.c.expected
new file mode 100644
index ..cb7846c7b3d5
--- /dev/null
+++ 
b/clang/test/utils/update_cc_test_checks/Inputs/on_the_fly_arg_change.c.expected
@@ -0,0 +1,29 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -triple=x86_64-unknown-linux-gnu -emit-llvm -o - %s | 
FileCheck %s
+
+// CHECK-LABEL: @checks_please(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:ret i32 1
+//
+int checks_please() {
+  return 1;
+}
+
+// UTC_ARGS: --disable
+
+int no_checks_please() {
+  // Manual CHECK line should be retained:
+  // CHECK: manual check line
+  return -1;
+}
+
+// UTC_ARGS: --enable
+
+
+// CHECK-LABEL: @checks_again(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:ret i32 2
+//
+int checks_again() {
+  return 2;
+}

diff  --git a/clang/test/utils/update_cc_test_checks/mangled_names.test 
b/clang/test/utils/update_cc_test_checks/mangled_names.test
index 082ed74304f0..bc88c9b5a382 100644
--- a/clang/test/utils/update_cc_test_checks/mangled_names.test
+++ b/clang/test/utils/update_cc_test_checks/mangled_names.test
@@ -8,6 +8,11 @@
 ## Also try the --function-signature flag
 # RUN: %update_cc_test_checks %t.c --function-signature
 # RUN: 
diff  -u %t.c %S/Inputs/mangled_names.c.funcsig.expected
-## Verify that running without the --function-signature flag removes the 
-SAME: lines:
+## Running it again should implicitly add the function-signature flag due to 
UTC_ARGS:
 # RUN: %update_cc_test_checks %t.c
-# RUN: 
diff  -u %t.c %S/Inputs/mangled_names.c.expected
+# RUN: 
diff  -u %t.c %S/I

[clang] 2ace693 - Don't install clang-import-test

2020-06-24 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-06-24T12:24:43+01:00
New Revision: 2ace69339ffe3d3432b1fb930f51b490bb8856c8

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

LOG: Don't install clang-import-test

I have been trying to reduce the installed size of our CHERI toolchain and
noticed that this tool was being installed even with 
-DLLVM_INSTALL_TOOLCHAIN_ONLY=ON.
This appears to be a test binary that should not be installed.

Reviewed By: v.g.vassilev
Differential Revision: https://reviews.llvm.org/D82169

Added: 


Modified: 
clang/tools/clang-import-test/CMakeLists.txt

Removed: 




diff  --git a/clang/tools/clang-import-test/CMakeLists.txt 
b/clang/tools/clang-import-test/CMakeLists.txt
index 39a5c41c1512..4ccc2d752aac 100644
--- a/clang/tools/clang-import-test/CMakeLists.txt
+++ b/clang/tools/clang-import-test/CMakeLists.txt
@@ -7,7 +7,7 @@ if(NOT CLANG_BUILT_STANDALONE)
   set(tablegen_deps intrinsics_gen)
 endif()
 
-add_clang_tool(clang-import-test
+add_clang_executable(clang-import-test
   clang-import-test.cpp
   DEPENDS
   ${tablegen_deps}



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


[clang] 3ce0e92 - [update_cc_test_checks.py] Handle C++ methods

2020-06-18 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-06-18T18:09:21+01:00
New Revision: 3ce0e92f45f56fc1b93db35dec8c53dceb5c54a5

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

LOG: [update_cc_test_checks.py] Handle C++ methods

Previously the script only handled C input, this change extends the JSON
parsing to to also include C++ function types such as methods, constructors
and destructors.

Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D80914

Added: 
clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp
clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp.expected
clang/test/utils/update_cc_test_checks/basic-cplusplus.test

Modified: 
llvm/utils/update_cc_test_checks.py

Removed: 




diff  --git a/clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp 
b/clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp
new file mode 100644
index ..98be350b3937
--- /dev/null
+++ b/clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp
@@ -0,0 +1,25 @@
+// Basic C++ test for update_cc_test_checks
+// RUN: %clang_cc1 -triple=x86_64-unknown-linux-gnu -emit-llvm -o - %s | 
FileCheck %s
+
+class Foo {
+  int x;
+
+public:
+  explicit Foo(int x);
+  ~Foo();
+  inline int function_defined_inline(int arg) const {
+return arg + x;
+  }
+  inline int function_defined_out_of_line(int arg) const;
+};
+
+Foo::Foo(int x) : x(x) {}
+Foo::~Foo() {}
+int Foo::function_defined_out_of_line(int arg) const { return x - arg; }
+
+// Call the inline methods to ensure the LLVM IR is generated:
+int main() {
+  Foo f(1);
+  f.function_defined_inline(2);
+  f.function_defined_out_of_line(3);
+}

diff  --git 
a/clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp.expected 
b/clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp.expected
new file mode 100644
index ..48ee67a7165a
--- /dev/null
+++ b/clang/test/utils/update_cc_test_checks/Inputs/basic-cplusplus.cpp.expected
@@ -0,0 +1,80 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// Basic C++ test for update_cc_test_checks
+// RUN: %clang_cc1 -triple=x86_64-unknown-linux-gnu -emit-llvm -o - %s | 
FileCheck %s
+
+class Foo {
+  int x;
+
+public:
+  explicit Foo(int x);
+  ~Foo();
+// CHECK-LABEL: @_ZNK3Foo23function_defined_inlineEi(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[THIS_ADDR:%.*]] = alloca %class.Foo*, align 8
+// CHECK-NEXT:[[ARG_ADDR:%.*]] = alloca i32, align 4
+// CHECK-NEXT:store %class.Foo* [[THIS:%.*]], %class.Foo** [[THIS_ADDR]], 
align 8
+// CHECK-NEXT:store i32 [[ARG:%.*]], i32* [[ARG_ADDR]], align 4
+// CHECK-NEXT:[[THIS1:%.*]] = load %class.Foo*, %class.Foo** 
[[THIS_ADDR]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = load i32, i32* [[ARG_ADDR]], align 4
+// CHECK-NEXT:[[X:%.*]] = getelementptr inbounds [[CLASS_FOO:%.*]], 
%class.Foo* [[THIS1]], i32 0, i32 0
+// CHECK-NEXT:[[TMP1:%.*]] = load i32, i32* [[X]], align 4
+// CHECK-NEXT:[[ADD:%.*]] = add nsw i32 [[TMP0]], [[TMP1]]
+// CHECK-NEXT:ret i32 [[ADD]]
+//
+  inline int function_defined_inline(int arg) const {
+return arg + x;
+  }
+  inline int function_defined_out_of_line(int arg) const;
+};
+
+// CHECK-LABEL: @_ZN3FooC1Ei(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[THIS_ADDR:%.*]] = alloca %class.Foo*, align 8
+// CHECK-NEXT:[[X_ADDR:%.*]] = alloca i32, align 4
+// CHECK-NEXT:store %class.Foo* [[THIS:%.*]], %class.Foo** [[THIS_ADDR]], 
align 8
+// CHECK-NEXT:store i32 [[X:%.*]], i32* [[X_ADDR]], align 4
+// CHECK-NEXT:[[THIS1:%.*]] = load %class.Foo*, %class.Foo** 
[[THIS_ADDR]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = load i32, i32* [[X_ADDR]], align 4
+// CHECK-NEXT:call void @_ZN3FooC2Ei(%class.Foo* [[THIS1]], i32 [[TMP0]])
+// CHECK-NEXT:ret void
+//
+Foo::Foo(int x) : x(x) {}
+// CHECK-LABEL: @_ZN3FooD1Ev(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[THIS_ADDR:%.*]] = alloca %class.Foo*, align 8
+// CHECK-NEXT:store %class.Foo* [[THIS:%.*]], %class.Foo** [[THIS_ADDR]], 
align 8
+// CHECK-NEXT:[[THIS1:%.*]] = load %class.Foo*, %class.Foo** 
[[THIS_ADDR]], align 8
+// CHECK-NEXT:call void @_ZN3FooD2Ev(%class.Foo* [[THIS1]]) #2
+// CHECK-NEXT:ret void
+//
+Foo::~Foo() {}
+// CHECK-LABEL: @_ZNK3Foo28function_defined_out_of_lineEi(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[THIS_ADDR:%.*]] = alloca %class.Foo*, align 8
+// CHECK-NEXT:[[ARG_ADDR:%.*]] = alloca i32, align 4
+// CHECK-NEXT:store %class.Foo* [[THIS:%.*]], %class.Foo** [[THIS_ADDR]], 
align 8
+// CHECK-NEXT:store i32 [[ARG:%.*]], i32* [[ARG_ADDR]], align 4
+// CHECK-NEXT:[[THIS1:%.*]] = load %class.Foo*, %class.Foo** 
[[THIS_ADDR]], align 8
+// CHECK-NEXT:[[X:%.*

[clang] ead7a8b - [update_cc_test_checks.py] Correctly skip function definitions

2020-06-18 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-06-18T18:09:21+01:00
New Revision: ead7a8beccc18c2cbcde980d2f593267d63c5dc2

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

LOG: [update_cc_test_checks.py] Correctly skip function definitions

Function declarations can in fact have an 'inner' node that lists the
ParmVarDecls. It seems like either the JSON output has changed or that I
tested the original JSON parsing change with test files that only have
function definitions without arguments.

Reviewed By: MaskRay
Differential Revision: https://reviews.llvm.org/D80913

Added: 


Modified: 
clang/test/utils/update_cc_test_checks/Inputs/def-and-decl.c
clang/test/utils/update_cc_test_checks/Inputs/def-and-decl.c.expected
llvm/utils/update_cc_test_checks.py

Removed: 




diff  --git a/clang/test/utils/update_cc_test_checks/Inputs/def-and-decl.c 
b/clang/test/utils/update_cc_test_checks/Inputs/def-and-decl.c
index 8e2e4f69fe07..7fc539347e6c 100644
--- a/clang/test/utils/update_cc_test_checks/Inputs/def-and-decl.c
+++ b/clang/test/utils/update_cc_test_checks/Inputs/def-and-decl.c
@@ -1,17 +1,17 @@
 // Check that the CHECK lines are generated before the definition and not the 
declaration
 // RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu %s -emit-llvm -o - | 
FileCheck %s
 
-int foo();
+int foo(int arg);
 
-void empty_function();
+void empty_function(void);
 
 int main() {
   empty_function();
-  return foo();
+  return foo(1);
 }
 
-int foo() {
-  return 1;
+int foo(int arg) {
+  return arg;
 }
 
-void empty_function() {}
+void empty_function(void) {}

diff  --git 
a/clang/test/utils/update_cc_test_checks/Inputs/def-and-decl.c.expected 
b/clang/test/utils/update_cc_test_checks/Inputs/def-and-decl.c.expected
index 07503be84f43..855530abe303 100644
--- a/clang/test/utils/update_cc_test_checks/Inputs/def-and-decl.c.expected
+++ b/clang/test/utils/update_cc_test_checks/Inputs/def-and-decl.c.expected
@@ -2,33 +2,36 @@
 // Check that the CHECK lines are generated before the definition and not the 
declaration
 // RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu %s -emit-llvm -o - | 
FileCheck %s
 
-int foo();
+int foo(int arg);
 
-void empty_function();
+void empty_function(void);
 
 // CHECK-LABEL: @main(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[RETVAL:%.*]] = alloca i32, align 4
 // CHECK-NEXT:store i32 0, i32* [[RETVAL]], align 4
 // CHECK-NEXT:call void @empty_function()
-// CHECK-NEXT:[[CALL:%.*]] = call i32 @foo()
+// CHECK-NEXT:[[CALL:%.*]] = call i32 @foo(i32 1)
 // CHECK-NEXT:ret i32 [[CALL]]
 //
 int main() {
   empty_function();
-  return foo();
+  return foo(1);
 }
 
 // CHECK-LABEL: @foo(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:ret i32 1
+// CHECK-NEXT:[[ARG_ADDR:%.*]] = alloca i32, align 4
+// CHECK-NEXT:store i32 [[ARG:%.*]], i32* [[ARG_ADDR]], align 4
+// CHECK-NEXT:[[TMP0:%.*]] = load i32, i32* [[ARG_ADDR]], align 4
+// CHECK-NEXT:ret i32 [[TMP0]]
 //
-int foo() {
-  return 1;
+int foo(int arg) {
+  return arg;
 }
 
 // CHECK-LABEL: @empty_function(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:ret void
 //
-void empty_function() {}
+void empty_function(void) {}

diff  --git a/llvm/utils/update_cc_test_checks.py 
b/llvm/utils/update_cc_test_checks.py
index 9b236dbd2431..127d3d737576 100755
--- a/llvm/utils/update_cc_test_checks.py
+++ b/llvm/utils/update_cc_test_checks.py
@@ -76,8 +76,18 @@ def parse_clang_ast_json(node):
 if line is None:
   common.debug('Skipping function without line number:', node['name'], 
'@', node['loc'])
   return
-# If there is no 'inner' object, it is a function declaration -> skip
-if 'inner' not in node:
+
+# If there is no 'inner' object, it is a function declaration and we can
+# skip it. However, function declarations may also contain an 'inner' list,
+# but in that case it will only contains ParmVarDecls. If we find an entry
+# that is not a ParmVarDecl, we know that this is a function definition.
+has_body = False
+if 'inner' in node:
+  for i in node['inner']:
+if i.get('kind', 'ParmVarDecl') != 'ParmVarDecl':
+  has_body = True
+  break
+if not has_body:
   common.debug('Skipping function without body:', node['name'], '@', 
node['loc'])
   return
 spell = node['name']



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


[clang] 385e5f7 - Fix incorrect call to ExprResult::get()

2020-06-11 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-06-11T22:23:33+01:00
New Revision: 385e5f7e147fcf792085b365cc48380850612025

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

LOG: Fix incorrect call to ExprResult::get()

Res is already a ExprResult, so if we call .get(), we will convert an
ExprError() result into an unset result. I discovered this in our downstream
CHERI target where this resulted in a crash due to a NULL-dereference.
It appears that this was introduced in SVN revision 201788 
(8690a6860a45ba36e39b4ff0dbe434195e125d11)

Reviewed By: Anastasia
Differential Revision: https://reviews.llvm.org/D81608

Added: 


Modified: 
clang/lib/Sema/SemaExpr.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 0537d09a09eb..6477979e92fe 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -724,7 +724,7 @@ ExprResult Sema::CallExprUnaryConversions(Expr *E) {
   // to function type.
   if (Ty->isFunctionType()) {
 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
-CK_FunctionToPointerDecay).get();
+CK_FunctionToPointerDecay);
 if (Res.isInvalid())
   return ExprError();
   }



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


[clang] 61dd060 - Move update_cc_test_checks.py tests to clang

2020-02-14 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-02-14T14:39:55Z
New Revision: 61dd0603bd8afeaa0d467d19c1522b5fbcf0104c

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

LOG: Move update_cc_test_checks.py tests to clang

Having tests that depend on clang inside llvm/ are not a good idea since
it can break incremental `ninja check-llvm`.

Fixes https://llvm.org/PR44798

Reviewed By: lebedev.ri, MaskRay, rsmith
Differential Revision: https://reviews.llvm.org/D74051

Added: 
clang/test/utils/update_cc_test_checks/Inputs/def-and-decl.c
clang/test/utils/update_cc_test_checks/Inputs/def-and-decl.c.expected
clang/test/utils/update_cc_test_checks/Inputs/mangled_names.c
clang/test/utils/update_cc_test_checks/Inputs/mangled_names.c.expected

clang/test/utils/update_cc_test_checks/Inputs/mangled_names.c.funcsig.expected
clang/test/utils/update_cc_test_checks/def-and-decl.test
clang/test/utils/update_cc_test_checks/lit.local.cfg
clang/test/utils/update_cc_test_checks/mangled_names.test

Modified: 
llvm/test/tools/UpdateTestChecks/lit.local.cfg

Removed: 
llvm/test/tools/UpdateTestChecks/update_cc_test_checks/Inputs/def-and-decl.c

llvm/test/tools/UpdateTestChecks/update_cc_test_checks/Inputs/def-and-decl.c.expected

llvm/test/tools/UpdateTestChecks/update_cc_test_checks/Inputs/mangled_names.c

llvm/test/tools/UpdateTestChecks/update_cc_test_checks/Inputs/mangled_names.c.expected

llvm/test/tools/UpdateTestChecks/update_cc_test_checks/Inputs/mangled_names.c.funcsig.expected
llvm/test/tools/UpdateTestChecks/update_cc_test_checks/def-and-decl.test
llvm/test/tools/UpdateTestChecks/update_cc_test_checks/lit.local.cfg
llvm/test/tools/UpdateTestChecks/update_cc_test_checks/mangled_names.test



diff  --git 
a/llvm/test/tools/UpdateTestChecks/update_cc_test_checks/Inputs/def-and-decl.c 
b/clang/test/utils/update_cc_test_checks/Inputs/def-and-decl.c
similarity index 100%
rename from 
llvm/test/tools/UpdateTestChecks/update_cc_test_checks/Inputs/def-and-decl.c
rename to clang/test/utils/update_cc_test_checks/Inputs/def-and-decl.c

diff  --git 
a/llvm/test/tools/UpdateTestChecks/update_cc_test_checks/Inputs/def-and-decl.c.expected
 b/clang/test/utils/update_cc_test_checks/Inputs/def-and-decl.c.expected
similarity index 100%
rename from 
llvm/test/tools/UpdateTestChecks/update_cc_test_checks/Inputs/def-and-decl.c.expected
rename to clang/test/utils/update_cc_test_checks/Inputs/def-and-decl.c.expected

diff  --git 
a/llvm/test/tools/UpdateTestChecks/update_cc_test_checks/Inputs/mangled_names.c 
b/clang/test/utils/update_cc_test_checks/Inputs/mangled_names.c
similarity index 100%
rename from 
llvm/test/tools/UpdateTestChecks/update_cc_test_checks/Inputs/mangled_names.c
rename to clang/test/utils/update_cc_test_checks/Inputs/mangled_names.c

diff  --git 
a/llvm/test/tools/UpdateTestChecks/update_cc_test_checks/Inputs/mangled_names.c.expected
 b/clang/test/utils/update_cc_test_checks/Inputs/mangled_names.c.expected
similarity index 100%
rename from 
llvm/test/tools/UpdateTestChecks/update_cc_test_checks/Inputs/mangled_names.c.expected
rename to clang/test/utils/update_cc_test_checks/Inputs/mangled_names.c.expected

diff  --git 
a/llvm/test/tools/UpdateTestChecks/update_cc_test_checks/Inputs/mangled_names.c.funcsig.expected
 
b/clang/test/utils/update_cc_test_checks/Inputs/mangled_names.c.funcsig.expected
similarity index 100%
rename from 
llvm/test/tools/UpdateTestChecks/update_cc_test_checks/Inputs/mangled_names.c.funcsig.expected
rename to 
clang/test/utils/update_cc_test_checks/Inputs/mangled_names.c.funcsig.expected

diff  --git 
a/llvm/test/tools/UpdateTestChecks/update_cc_test_checks/def-and-decl.test 
b/clang/test/utils/update_cc_test_checks/def-and-decl.test
similarity index 100%
rename from 
llvm/test/tools/UpdateTestChecks/update_cc_test_checks/def-and-decl.test
rename to clang/test/utils/update_cc_test_checks/def-and-decl.test

diff  --git a/clang/test/utils/update_cc_test_checks/lit.local.cfg 
b/clang/test/utils/update_cc_test_checks/lit.local.cfg
new file mode 100644
index ..0250446423cb
--- /dev/null
+++ b/clang/test/utils/update_cc_test_checks/lit.local.cfg
@@ -0,0 +1,25 @@
+import os
+
+import lit.util
+
+# python 2.7 backwards compatibility
+try:
+from shlex import quote as shell_quote
+except ImportError:
+from pipes import quote as shell_quote
+
+
+config.test_format = lit.formats.ShTest(execute_external=False)
+config.suffixes = ['.test']
+
+clang_path = os.path.join(config.clang_tools_dir, 'clang')
+extra_args = '--clang ' + shell_quote(clang_path)
+opt_path = os.path.join(config.llvm_tools_dir, 'opt')
+extra_args += ' --opt ' + shell_quote(opt_path)
+script_path = os.path.join(config.llvm_src_root, 'utils',
+  

[clang] 8c387cb - Add builtins for aligning and checking alignment of pointers and integers

2020-01-09 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-01-09T21:48:29Z
New Revision: 8c387cbea76b169f1f8ecc7693797e96567ed896

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

LOG: Add builtins for aligning and checking alignment of pointers and integers

This change introduces three new builtins (which work on both pointers
and integers) that can be used instead of common bitwise arithmetic:
__builtin_align_up(x, alignment), __builtin_align_down(x, alignment) and
__builtin_is_aligned(x, alignment).

I originally added these builtins to the CHERI fork of LLVM a few years ago
to handle the slightly different C semantics that we use for CHERI [1].
Until recently these builtins (or sequences of other builtins) were
required to generate correct code. I have since made changes to the default
C semantics so that they are no longer strictly necessary (but using them
does generate slightly more efficient code). However, based on our experience
using them in various projects over the past few years, I believe that adding
these builtins to clang would be useful.

These builtins have the following benefit over bit-manipulation and casts
via uintptr_t:

- The named builtins clearly convey the semantics of the operation. While
  checking alignment using __builtin_is_aligned(x, 16) versus
  ((x & 15) == 0) is probably not a huge win in readably, I personally find
  __builtin_align_up(x, N) a lot easier to read than (x+(N-1))&~(N-1).
- They preserve the type of the argument (including const qualifiers). When
  using casts via uintptr_t, it is easy to cast to the wrong type or strip
  qualifiers such as const.
- If the alignment argument is a constant value, clang can check that it is
  a power-of-two and within the range of the type. Since the semantics of
  these builtins is well defined compared to arbitrary bit-manipulation,
  it is possible to add a UBSAN checker that the run-time value is a valid
  power-of-two. I intend to add this as a follow-up to this change.
- The builtins avoids int-to-pointer casts both in C and LLVM IR.
  In the future (i.e. once most optimizations handle it), we could use the new
  llvm.ptrmask intrinsic to avoid the ptrtoint instruction that would normally
  be generated.
- They can be used to round up/down to the next aligned value for both
  integers and pointers without requiring two separate macros.
- In many projects the alignment operations are already wrapped in macros (e.g.
  roundup2 and rounddown2 in FreeBSD), so by replacing the macro implementation
  with a builtin call, we get improved diagnostics for many call-sites while
  only having to change a few lines.
- Finally, the builtins also emit assume_aligned metadata when used on pointers.
  This can improve code generation compared to the uintptr_t casts.

[1] In our CHERI compiler we have compilation mode where all pointers are
implemented as capabilities (essentially unforgeable 128-bit fat pointers).
In our original model, casts from uintptr_t (which is a 128-bit capability)
to an integer value returned the "offset" of the capability (i.e. the
difference between the virtual address and the base of the allocation).
This causes problems for cases such as checking the alignment: for example, the
expression `if ((uintptr_t)ptr & 63) == 0` is generally used to check if the
pointer is aligned to a multiple of 64 bytes. The problem with offsets is that
any pointer to the beginning of an allocation will have an offset of zero, so
this check always succeeds in that case (even if the address is not correctly
aligned). The same issues also exist when aligning up or down. Using the
alignment builtins ensures that the address is used instead of the offset. While
I have since changed the default C semantics to return the address instead of
the offset when casting, this offset compilation mode can still be used by
passing a command-line flag.

Reviewers: rsmith, aaron.ballman, theraven, fhahn, lebedev.ri, nlopes, aqjune
Reviewed By: aaron.ballman, lebedev.ri
Differential Revision: https://reviews.llvm.org/D71499

Added: 
clang/test/CodeGen/builtin-align-array.c
clang/test/CodeGen/builtin-align-assumption.c
clang/test/CodeGen/builtin-align.c
clang/test/Sema/builtin-align.c
clang/test/SemaCXX/builtin-align-cxx.cpp

Modified: 
clang/docs/LanguageExtensions.rst
clang/include/clang/Basic/Builtins.def
clang/include/clang/Basic/DiagnosticASTKinds.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/AST/ExprConstant.cpp
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/CodeGen/CodeGenFunction.h
clang/lib/Sema/SemaChecking.cpp

Removed: 




diff  --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index b0f57202e079..0bd87903f349 100644
--- a/clang/docs/LanguageExten

[clang] 09c7e51 - Add a missing triple in ast-dump-decl-json.m

2019-11-16 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2019-11-15T20:15:00Z
New Revision: 09c7e51283dafbfd122cc0d7ab251476c451c9f5

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

LOG: Add a missing triple in ast-dump-decl-json.m

Since there was no triple argument this test started failing on macOS bots,
where the mangled names are prefixed with an underscore.

Added: 


Modified: 
clang/test/AST/ast-dump-decl-json.m

Removed: 




diff  --git a/clang/test/AST/ast-dump-decl-json.m 
b/clang/test/AST/ast-dump-decl-json.m
index 4b176b3fb52c..d100811c1c24 100644
--- a/clang/test/AST/ast-dump-decl-json.m
+++ b/clang/test/AST/ast-dump-decl-json.m
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -Wno-unused -fblocks -ast-dump=json -ast-dump-filter Test 
%s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -Wno-unused -fblocks 
-ast-dump=json -ast-dump-filter Test %s | FileCheck %s
 
 @protocol P
 @end
@@ -88,7 +88,7 @@ void f() {
 
 // CHECK:  "kind": "ObjCInterfaceDecl",
 // CHECK-NEXT:  "loc": {
-// CHECK-NEXT:   "offset": 144,
+// CHECK-NEXT:   "offset": 172,
 // CHECK-NEXT:   "file": "{{.*}}",
 // CHECK-NEXT:   "line": 9,
 // CHECK-NEXT:   "col": 12,
@@ -96,19 +96,19 @@ void f() {
 // CHECK-NEXT:  },
 // CHECK-NEXT:  "range": {
 // CHECK-NEXT:   "begin": {
-// CHECK-NEXT:"offset": 133,
+// CHECK-NEXT:"offset": 161,
 // CHECK-NEXT:"col": 1,
 // CHECK-NEXT:"tokLen": 1
 // CHECK-NEXT:   },
 // CHECK-NEXT:   "end": {
-// CHECK-NEXT:"offset": 166,
+// CHECK-NEXT:"offset": 194,
 // CHECK-NEXT:"line": 10,
 // CHECK-NEXT:"col": 2,
 // CHECK-NEXT:"tokLen": 3
 // CHECK-NEXT:   }
 // CHECK-NEXT:  },
 // CHECK-NEXT:  "name": "TestObjCIvarDecl",
-// CHECK-NEXT:  "mangledName": "OBJC_CLASS_$_TestObjCIvarDecl",
+// CHECK-NEXT:  "mangledName": "_OBJC_CLASS_$_TestObjCIvarDecl",
 // CHECK-NEXT:  "super": {
 // CHECK-NEXT:   "id": "0x{{.*}}",
 // CHECK-NEXT:   "kind": "ObjCInterfaceDecl",
@@ -124,7 +124,7 @@ void f() {
 
 // CHECK:  "kind": "ObjCImplementationDecl",
 // CHECK-NEXT:  "loc": {
-// CHECK-NEXT:   "offset": 187,
+// CHECK-NEXT:   "offset": 215,
 // CHECK-NEXT:   "file": "{{.*}}",
 // CHECK-NEXT:   "line": 12,
 // CHECK-NEXT:   "col": 17,
@@ -132,12 +132,12 @@ void f() {
 // CHECK-NEXT:  },
 // CHECK-NEXT:  "range": {
 // CHECK-NEXT:   "begin": {
-// CHECK-NEXT:"offset": 171,
+// CHECK-NEXT:"offset": 199,
 // CHECK-NEXT:"col": 1,
 // CHECK-NEXT:"tokLen": 1
 // CHECK-NEXT:   },
 // CHECK-NEXT:   "end": {
-// CHECK-NEXT:"offset": 336,
+// CHECK-NEXT:"offset": 364,
 // CHECK-NEXT:"line": 19,
 // CHECK-NEXT:"col": 1,
 // CHECK-NEXT:"tokLen": 1
@@ -157,19 +157,19 @@ void f() {
 // CHECK-NEXT:"id": "0x{{.*}}",
 // CHECK-NEXT:"kind": "ObjCIvarDecl",
 // CHECK-NEXT:"loc": {
-// CHECK-NEXT: "offset": 212,
+// CHECK-NEXT: "offset": 240,
 // CHECK-NEXT: "line": 13,
 // CHECK-NEXT: "col": 7,
 // CHECK-NEXT: "tokLen": 10
 // CHECK-NEXT:},
 // CHECK-NEXT:"range": {
 // CHECK-NEXT: "begin": {
-// CHECK-NEXT:  "offset": 208,
+// CHECK-NEXT:  "offset": 236,
 // CHECK-NEXT:  "col": 3,
 // CHECK-NEXT:  "tokLen": 3
 // CHECK-NEXT: },
 // CHECK-NEXT: "end": {
-// CHECK-NEXT:  "offset": 212,
+// CHECK-NEXT:  "offset": 240,
 // CHECK-NEXT:  "col": 7,
 // CHECK-NEXT:  "tokLen": 10
 // CHECK-NEXT: }
@@ -184,19 +184,19 @@ void f() {
 // CHECK-NEXT:"id": "0x{{.*}}",
 // CHECK-NEXT:"kind": "ObjCIvarDecl",
 // CHECK-NEXT:"loc": {
-// CHECK-NEXT: "offset": 239,
+// CHECK-NEXT: "offset": 267,
 // CHECK-NEXT: "line": 14,
 // CHECK-NEXT: "col": 16,
 // CHECK-NEXT: "tokLen": 10
 // CHECK-NEXT:},
 // CHECK-NEXT:"range": {
 // CHECK-NEXT: "begin": {
-// CHECK-NEXT:  "offset": 235,
+// CHECK-NEXT:  "offset": 263,
 // CHECK-NEXT:  "col": 12,
 // CHECK-NEXT:  "tokLen": 3
 // CHECK-NEXT: },
 // CHECK-NEXT: "end": {
-// CHECK-NEXT:  "offset": 239,
+// CHECK-NEXT:  "offset": 267,
 // CHECK-NEXT:  "col": 16,
 // CHECK-NEXT:  "tokLen": 10
 // CHECK-NEXT: }
@@ -211,19 +211,19 @@ void f() {
 // CHECK-NEXT:"id": "0x{{.*}}",
 // CHECK-NEXT:"kind": "ObjCIvarDecl",
 // CHECK-NEXT:"loc": {
-// CHECK-NEXT: "offset": 268,
+// CHECK-NEXT: "offset": 296,
 // CHECK-NEXT: "line": 15,
 // CHECK-NEXT: "col": 18,
 // CHECK-NEXT: "tokLen": 12
 // CHECK-NEXT:},
 // CHECK-NEXT:"range": {
 // CHECK-NEXT: "begin": {
-// CHECK-NEXT:  "offset": 264,
+// CHECK-NEXT:  "offset": 292,
 // CHECK-NEXT:  "col": 14,
 // CHECK-NEXT:  "tokLen": 3
 // CHECK-NEXT: },
 // CHECK-NEXT: "end": {
-// CHECK-NEXT:  "offset": 268,
+// CHECK-NEXT:  "offset": 296,
 // CHECK-NEXT: 

[clang] a763d98 - [gen_ast_dump_json_test.py] Add a --update flag

2019-11-16 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2019-11-15T12:52:30Z
New Revision: a763d985012bdc5c5fc7bbc836b0dfddbb9af2d8

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

LOG: [gen_ast_dump_json_test.py] Add a --update flag

This will allow updating the JSON tests for new format changes. Instead of
simply appending the JSON to the input file, the script will now make a
copy of the input file up to the "CHECK lines have been autogenerated"
disclaimer and then append the new JSON.

See https://reviews.llvm.org/D70119

Added: 


Modified: 
clang/test/AST/gen_ast_dump_json_test.py

Removed: 




diff  --git a/clang/test/AST/gen_ast_dump_json_test.py 
b/clang/test/AST/gen_ast_dump_json_test.py
index 54a5109aacff..4f4f37cd26d7 100644
--- a/clang/test/AST/gen_ast_dump_json_test.py
+++ b/clang/test/AST/gen_ast_dump_json_test.py
@@ -1,7 +1,5 @@
 #!/usr/bin/env python
-
 from collections import OrderedDict
-from sets import Set
 from shutil import copyfile
 import argparse
 import json
@@ -9,7 +7,8 @@
 import pprint
 import re
 import subprocess
-
+import tempfile
+
 def normalize(dict_var):
 for k, v in dict_var.items():
 if isinstance(v, OrderedDict):
@@ -63,6 +62,7 @@ def main():
 action="store", required=True)
 parser.add_argument("--filters", help="comma separated list of AST 
filters. Ex: --filters=TypedefDecl,BuiltinType",
 action="store", default='')
+parser.add_argument("--update", help="Update the file in-place", 
action="store_true")
 
 args = parser.parse_args()
 
@@ -76,7 +76,7 @@ def main():
 return -1
 
 options = args.opts.split(' ')
-filters = Set(args.filters.split(',')) if args.filters else Set([])
+filters = set(args.filters.split(',')) if args.filters else set()
 
 note = "// NOTE: CHECK lines have been autogenerated by " \
"gen_ast_dump_json_test.py"
@@ -118,13 +118,14 @@ def main():
 
 filter_json(j, filters, out_asts)
 
-partition = args.source.rpartition('.')
-dest_path = '%s-json%s%s' % (partition[0], partition[1], partition[2])
-
-print("Writing json appended source file to %s." %(dest_path))
-copyfile(args.source, dest_path)
-with open(dest_path, "a") as f:
-f.write("\n" + note + "\n")
+with tempfile.NamedTemporaryFile("w") as f:
+with open(args.source, "r") as srcf:
+for line in srcf.readlines():
+# copy up to the note:
+if line.rstrip() == note:
+break
+f.write(line)
+f.write(note + "\n")
 for out_ast in out_asts:
 append_str = json.dumps(out_ast, indent=1, ensure_ascii=False)
 out_str = '\n\n'
@@ -137,7 +138,15 @@ def main():
 out_str += '// CHECK-NEXT: %s\n' %(append_line.rstrip())
 
 f.write(out_str)
-
+f.flush()
+if args.update:
+print("Updating json appended source file to %s." %  args.source)
+copyfile(f.name, args.source)
+else:
+partition = args.source.rpartition('.')
+dest_path = '%s-json%s%s' % (partition[0], partition[1], 
partition[2])
+print("Writing json appended source file to %s." % dest_path)
+copyfile(f.name, dest_path)
 return 0
 
 if __name__ == '__main__':



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