[PATCH] D96110: [X86] Pass to transform tdpbf16ps intrinsics to scalar operation.

2021-02-04 Thread Bing Yu via Phabricator via cfe-commits
yubing created this revision.
Herald added subscribers: pengfei, hiraditya.
yubing requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96110

Files:
  clang/include/clang/Basic/BuiltinsX86_64.def
  clang/lib/Headers/amxintrin.h
  llvm/include/llvm/IR/IntrinsicsX86.td
  llvm/lib/Target/X86/X86ExpandPseudo.cpp
  llvm/lib/Target/X86/X86ISelDAGToDAG.cpp
  llvm/lib/Target/X86/X86InstrAMX.td
  llvm/lib/Target/X86/X86LowerAMXIntrinsics.cpp
  llvm/lib/Target/X86/X86LowerAMXType.cpp
  llvm/lib/Target/X86/X86PreTileConfig.cpp
  llvm/lib/Target/X86/X86RegisterInfo.cpp

Index: llvm/lib/Target/X86/X86RegisterInfo.cpp
===
--- llvm/lib/Target/X86/X86RegisterInfo.cpp
+++ llvm/lib/Target/X86/X86RegisterInfo.cpp
@@ -873,6 +873,7 @@
   // We only collect the tile shape that is defined.
   case X86::PTILELOADDV:
   case X86::PTDPBSSDV:
+  case X86::PTDPBF16PSV:
   case X86::PTILEZEROV:
 MachineOperand  = MI->getOperand(1);
 MachineOperand  = MI->getOperand(2);
Index: llvm/lib/Target/X86/X86PreTileConfig.cpp
===
--- llvm/lib/Target/X86/X86PreTileConfig.cpp
+++ llvm/lib/Target/X86/X86PreTileConfig.cpp
@@ -127,6 +127,7 @@
 llvm_unreachable("Unexpected machine instruction on tile");
   case X86::PTILELOADDV:
   case X86::PTDPBSSDV:
+  case X86::PTDPBF16PSV:
   case X86::PTILEZEROV:
 MachineOperand  = const_cast(MI.getOperand(1));
 MachineOperand  = const_cast(MI.getOperand(2));
@@ -221,6 +222,7 @@
   case X86::PTILELOADDV:
   case X86::PTILESTOREDV:
   case X86::PTDPBSSDV:
+  case X86::PTDPBF16PSV:
   case X86::PTILEZEROV:
 return true;
   }
Index: llvm/lib/Target/X86/X86LowerAMXType.cpp
===
--- llvm/lib/Target/X86/X86LowerAMXType.cpp
+++ llvm/lib/Target/X86/X86LowerAMXType.cpp
@@ -67,7 +67,8 @@
   }
   // a * b + c
   // The shape depends on which operand.
-  case Intrinsic::x86_tdpbssd_internal: {
+  case Intrinsic::x86_tdpbssd_internal:
+  case Intrinsic::x86_tdpbf16ps_internal:{
 switch (OpNo) {
 case 3:
   Row = II->getArgOperand(0);
Index: llvm/lib/Target/X86/X86LowerAMXIntrinsics.cpp
===
--- llvm/lib/Target/X86/X86LowerAMXIntrinsics.cpp
+++ llvm/lib/Target/X86/X86LowerAMXIntrinsics.cpp
@@ -306,6 +306,111 @@
   return NewVecC;
 }
 
+static Value *createTileDPBF16PSLoops(BasicBlock *Start, BasicBlock *End,
+IRBuilderBase , DomTreeUpdater ,
+LoopInfo , Value *Row, Value *Col,
+Value *K, Value *Acc, Value *LHS,
+Value *RHS) {
+  Loop *RowLoop = LI.AllocateLoop();
+  Loop *ColLoop = LI.AllocateLoop();
+  Loop *InnerLoop = LI.AllocateLoop();
+  ColLoop->addChildLoop(InnerLoop);
+  RowLoop->addChildLoop(ColLoop);
+  if (Loop *ParentL = LI.getLoopFor(Start))
+ParentL->addChildLoop(RowLoop);
+  else
+LI.addTopLevelLoop(RowLoop);
+
+  BasicBlock *RowBody =
+  createLoop(Start, End, Row, B.getInt16(1), "tiledpbf16ps.unroll.rows", B,
+ DTU, RowLoop, LI);
+  BasicBlock *RowLatch = RowBody->getSingleSuccessor();
+
+  BasicBlock *ColBody =
+  createLoop(RowBody, RowLatch, Col, B.getInt16(1),
+ "tiledpbf16ps.unroll.cols", B, DTU, ColLoop, LI);
+  BasicBlock *ColLoopLatch = ColBody->getSingleSuccessor();
+
+  B.SetInsertPoint(ColBody->getTerminator());
+  BasicBlock *InnerBody =
+  createLoop(ColBody, ColLoopLatch, K, B.getInt16(1),
+ "tiledpbf16ps.unroll.inner", B, DTU, InnerLoop, LI);
+
+  BasicBlock *ColumnLoopHeader = ColBody->getSinglePredecessor();
+  BasicBlock *RowLoopHeader = RowBody->getSinglePredecessor();
+  BasicBlock *InnerLoopHeader = InnerBody->getSinglePredecessor();
+  BasicBlock *InnerLoopLatch = InnerBody->getSingleSuccessor();
+  Value *CurrentRow = &*RowLoopHeader->begin();
+  Value *CurrentCol = &*ColumnLoopHeader->begin();
+  Value *CurrentInner = &*InnerLoopHeader->begin();
+
+  FixedVectorType *V256I32Ty = FixedVectorType::get(B.getInt32Ty(), 256);
+  // Type *EltTy = V256I32Ty->getElementType();
+  Value *VecC, *VecA, *VecB;
+  if (auto BitCast = dyn_cast(Acc))
+VecC = BitCast->getOperand(0);
+  assert(VecC->getType()->isVectorTy() && "bitcast from non-v256i32 to x86amx");
+  // TODO else create BitCast from x86amx to v256i32.
+  // Store x86amx to memory, and reload from memory
+  // to vector. However with -O0, it doesn't happen.
+  if (auto BitCast = dyn_cast(LHS))
+VecA = BitCast->getOperand(0);
+  assert(VecA->getType()->isVectorTy() && "bitcast from non-v256i32 to x86amx");
+  if (auto BitCast = dyn_cast(RHS))
+VecB = BitCast->getOperand(0);
+  

[PATCH] D96102: [clangd] Fix missing __syncthreads.

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

I doubt this compiles:

  https://godbolt.org/z/c51v5d

even with adjusted type, this fails because `__syncthreads` is a builtin (right 
now):

  https://godbolt.org/z/jP7e6h

(and `__nvvm_bar_sync` requires an argument).


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

https://reviews.llvm.org/D96102

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


[PATCH] D96105: [CUDA][HIP] Pass -fgpu-rdc to host clang -cc1

2021-02-04 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl created this revision.
yaxunl added a reviewer: tra.
yaxunl requested review of this revision.

Currently -fgpu-rdc is not passed to host clang -cc1.
This causes issue because -fgpu-rdc affects shadow
variable linkage in host compilation.


https://reviews.llvm.org/D96105

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/lib/Driver/ToolChains/HIP.cpp
  clang/test/Driver/hip-rdc-device-only.hip
  clang/test/Driver/hip-toolchain-rdc-separate.hip
  clang/test/Driver/hip-toolchain-rdc-static-lib.hip
  clang/test/Driver/hip-toolchain-rdc.hip

Index: clang/test/Driver/hip-toolchain-rdc.hip
===
--- clang/test/Driver/hip-toolchain-rdc.hip
+++ clang/test/Driver/hip-toolchain-rdc.hip
@@ -21,6 +21,7 @@
 // CHECK-SAME: "-aux-triple" "amdgcn-amd-amdhsa"
 // CHECK-SAME: "-emit-obj"
 // CHECK-SAME: {{.*}} "-main-file-name" "a.cu"
+// CHECK-SAME: "-fgpu-rdc"
 // CHECK-SAME: {{.*}} "-o" [[A_OBJ_HOST:".*o"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[A_SRC:".*a.cu"]]
 
@@ -28,6 +29,7 @@
 // CHECK-SAME: "-aux-triple" "amdgcn-amd-amdhsa"
 // CHECK-SAME: "-emit-obj"
 // CHECK-SAME: {{.*}} "-main-file-name" "b.hip"
+// CHECK-SAME: "-fgpu-rdc"
 // CHECK-SAME: {{.*}} "-o" [[B_OBJ_HOST:".*o"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[B_SRC:".*b.hip"]]
 
@@ -36,10 +38,11 @@
 // CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu"
 // CHECK-SAME: "-emit-llvm-bc"
 // CHECK-SAME: {{.*}} "-main-file-name" "a.cu"
-// CHECK-SAME: "-fcuda-is-device" "-fgpu-rdc" "-fcuda-allow-variadic-functions" "-fvisibility" "hidden"
+// CHECK-SAME: "-fcuda-is-device" "-fcuda-allow-variadic-functions" "-fvisibility" "hidden"
 // CHECK-SAME: "-fapply-global-visibility-to-externs"
 // CHECK-SAME: "{{.*}}lib1.bc" "{{.*}}lib2.bc"
 // CHECK-SAME: "-target-cpu" "gfx803"
+// CHECK-SAME: "-fgpu-rdc"
 // CHECK-SAME: {{.*}} "-o" [[A_BC1:".*bc"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[A_SRC]]
 
@@ -47,10 +50,11 @@
 // CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu"
 // CHECK-SAME: "-emit-llvm-bc"
 // CHECK-SAME: {{.*}} "-main-file-name" "b.hip"
-// CHECK-SAME: "-fcuda-is-device" "-fgpu-rdc" "-fcuda-allow-variadic-functions" "-fvisibility" "hidden"
+// CHECK-SAME: "-fcuda-is-device" "-fcuda-allow-variadic-functions" "-fvisibility" "hidden"
 // CHECK-SAME: "-fapply-global-visibility-to-externs"
 // CHECK-SAME: "{{.*}}lib1.bc" "{{.*}}lib2.bc"
 // CHECK-SAME: "-target-cpu" "gfx803"
+// CHECK-SAME: "-fgpu-rdc"
 // CHECK-SAME: {{.*}} "-o" [[B_BC1:".*bc"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[B_SRC]]
 
@@ -66,7 +70,7 @@
 // CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu"
 // CHECK-SAME: "-emit-llvm-bc"
 // CHECK-SAME: {{.*}} "-main-file-name" "a.cu"
-// CHECK-SAME: "-fcuda-is-device" "-fgpu-rdc"
+// CHECK-SAME: "-fcuda-is-device"
 // CHECK-SAME: "{{.*}}lib1.bc" "{{.*}}lib2.bc"
 // CHECK-SAME: "-target-cpu" "gfx900"
 // CHECK-SAME: {{.*}} "-o" [[A_BC2:".*bc"]] "-x" "hip"
@@ -76,9 +80,10 @@
 // CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu"
 // CHECK-SAME: "-emit-llvm-bc"
 // CHECK-SAME: {{.*}} "-main-file-name" "b.hip"
-// CHECK-SAME: "-fcuda-is-device" "-fgpu-rdc"
+// CHECK-SAME: "-fcuda-is-device"
 // CHECK-SAME: "{{.*}}lib1.bc" "{{.*}}lib2.bc"
 // CHECK-SAME: "-target-cpu" "gfx900"
+// CHECK-SAME: "-fgpu-rdc"
 // CHECK-SAME: {{.*}} "-o" [[B_BC2:".*bc"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[B_SRC]]
 
Index: clang/test/Driver/hip-toolchain-rdc-static-lib.hip
===
--- clang/test/Driver/hip-toolchain-rdc-static-lib.hip
+++ clang/test/Driver/hip-toolchain-rdc-static-lib.hip
@@ -15,6 +15,7 @@
 // CHECK-SAME: "-aux-triple" "amdgcn-amd-amdhsa"
 // CHECK-SAME: "-emit-obj"
 // CHECK-SAME: {{.*}} "-main-file-name" "a.cu"
+// CHECK-SAME: "-fgpu-rdc"
 // CHECK-SAME: {{.*}} "-o" [[A_OBJ_HOST:".*o"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[A_SRC:".*a.cu"]]
 
@@ -22,6 +23,7 @@
 // CHECK-SAME: "-aux-triple" "amdgcn-amd-amdhsa"
 // CHECK-SAME: "-emit-obj"
 // CHECK-SAME: {{.*}} "-main-file-name" "b.hip"
+// CHECK-SAME: "-fgpu-rdc"
 // CHECK-SAME: {{.*}} "-o" [[B_OBJ_HOST:".*o"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[B_SRC:".*b.hip"]]
 
@@ -30,8 +32,9 @@
 // CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu"
 // CHECK-SAME: "-emit-llvm-bc"
 // CHECK-SAME: {{.*}} "-main-file-name" "a.cu"
-// CHECK-SAME: "-fcuda-is-device" "-fgpu-rdc"
+// CHECK-SAME: "-fcuda-is-device"
 // CHECK-SAME: "-target-cpu" "gfx803"
+// CHECK-SAME: "-fgpu-rdc"
 // CHECK-SAME: {{.*}} "-o" [[A_BC1:".*bc"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[A_SRC]]
 
@@ -39,8 +42,9 @@
 // CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu"
 // CHECK-SAME: "-emit-llvm-bc"
 // CHECK-SAME: {{.*}} "-main-file-name" "b.hip"
-// CHECK-SAME: "-fcuda-is-device" "-fgpu-rdc"
+// CHECK-SAME: "-fcuda-is-device"
 // CHECK-SAME: "-target-cpu" "gfx803"
+// CHECK-SAME: "-fgpu-rdc"
 // CHECK-SAME: {{.*}} "-o" [[B_BC1:".*bc"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[B_SRC]]
 
@@ 

[PATCH] D96102: [clangd] Fix missing __syncthreads.

2021-02-04 Thread Tommy Chiang via Phabricator via cfe-commits
oToToT updated this revision to Diff 321652.
oToToT added a comment.

I guess __nvvm_bar_sync is the right instruction.


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

https://reviews.llvm.org/D96102

Files:
  clang/lib/Headers/__clang_cuda_device_functions.h


Index: clang/lib/Headers/__clang_cuda_device_functions.h
===
--- clang/lib/Headers/__clang_cuda_device_functions.h
+++ clang/lib/Headers/__clang_cuda_device_functions.h
@@ -519,6 +519,7 @@
   return __nv_fast_sincosf(__a, __s, __c);
 }
 __DEVICE__ float __sinf(float __a) { return __nv_fast_sinf(__a); }
+__DEVICE__ int __syncthreads() { return __nvvm_bar_sync(); }
 __DEVICE__ int __syncthreads_and(int __a) { return __nvvm_bar0_and(__a); }
 __DEVICE__ int __syncthreads_count(int __a) { return __nvvm_bar0_popc(__a); }
 __DEVICE__ int __syncthreads_or(int __a) { return __nvvm_bar0_or(__a); }


Index: clang/lib/Headers/__clang_cuda_device_functions.h
===
--- clang/lib/Headers/__clang_cuda_device_functions.h
+++ clang/lib/Headers/__clang_cuda_device_functions.h
@@ -519,6 +519,7 @@
   return __nv_fast_sincosf(__a, __s, __c);
 }
 __DEVICE__ float __sinf(float __a) { return __nv_fast_sinf(__a); }
+__DEVICE__ int __syncthreads() { return __nvvm_bar_sync(); }
 __DEVICE__ int __syncthreads_and(int __a) { return __nvvm_bar0_and(__a); }
 __DEVICE__ int __syncthreads_count(int __a) { return __nvvm_bar0_popc(__a); }
 __DEVICE__ int __syncthreads_or(int __a) { return __nvvm_bar0_or(__a); }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D96102: [clangd] Fix missing __syncthreads.

2021-02-04 Thread Tommy Chiang via Phabricator via cfe-commits
oToToT created this revision.
oToToT added reviewers: tra, chandlerc, jdoerfert, gtbercea, emankov, 
JDevlieghere.
Herald added subscribers: usaxena95, kadircet, arphaman.
oToToT requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

I think the symbol for __syncthreads is missing. Therefore, I've added this 
into the __clang_cuda_device_functions.h.

This also solve an issue on GitHub opened about half a year ago.
Ref: https://github.com/clangd/clangd/issues/404


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96102

Files:
  clang/lib/Headers/__clang_cuda_device_functions.h


Index: clang/lib/Headers/__clang_cuda_device_functions.h
===
--- clang/lib/Headers/__clang_cuda_device_functions.h
+++ clang/lib/Headers/__clang_cuda_device_functions.h
@@ -519,6 +519,7 @@
   return __nv_fast_sincosf(__a, __s, __c);
 }
 __DEVICE__ float __sinf(float __a) { return __nv_fast_sinf(__a); }
+__DEVICE__ int __syncthreads() { return __nvvm_bar(); }
 __DEVICE__ int __syncthreads_and(int __a) { return __nvvm_bar0_and(__a); }
 __DEVICE__ int __syncthreads_count(int __a) { return __nvvm_bar0_popc(__a); }
 __DEVICE__ int __syncthreads_or(int __a) { return __nvvm_bar0_or(__a); }


Index: clang/lib/Headers/__clang_cuda_device_functions.h
===
--- clang/lib/Headers/__clang_cuda_device_functions.h
+++ clang/lib/Headers/__clang_cuda_device_functions.h
@@ -519,6 +519,7 @@
   return __nv_fast_sincosf(__a, __s, __c);
 }
 __DEVICE__ float __sinf(float __a) { return __nv_fast_sinf(__a); }
+__DEVICE__ int __syncthreads() { return __nvvm_bar(); }
 __DEVICE__ int __syncthreads_and(int __a) { return __nvvm_bar0_and(__a); }
 __DEVICE__ int __syncthreads_count(int __a) { return __nvvm_bar0_popc(__a); }
 __DEVICE__ int __syncthreads_or(int __a) { return __nvvm_bar0_or(__a); }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D96091: [WebAssembly] Use single-threaded mode when -matomics isn't enabled.

2021-02-04 Thread Sam Clegg via Phabricator via cfe-commits
sbc100 added inline comments.



Comment at: clang/lib/Basic/Targets/WebAssembly.cpp:260
+  if (!HasAtomics) {
+Opts.POSIXThreads = false;
+Opts.setThreadModel(LangOptions::ThreadModelKind::Single);

POSIXThreads already defaults to false I think.   It gets set if the user 
specified `-pthread` on the command line I think.   I think there should be no 
need to override it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96091

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


[PATCH] D96091: [WebAssembly] Use single-threaded mode when -matomics isn't enabled.

2021-02-04 Thread Dan Gohman via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG95da64da23ac: [WebAssembly] Use single-threaded mode when 
-matomics isnt enabled. (authored by sunfish).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96091

Files:
  clang/lib/Basic/Targets/WebAssembly.cpp
  clang/lib/Basic/Targets/WebAssembly.h
  clang/test/Preprocessor/init.c


Index: clang/test/Preprocessor/init.c
===
--- clang/test/Preprocessor/init.c
+++ clang/test/Preprocessor/init.c
@@ -1479,6 +1479,12 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -fgnuc-version=4.2.1 
-triple=wasm64-wasi \
 // RUN:   < /dev/null \
 // RUN:   | FileCheck -match-full-lines 
-check-prefixes=WEBASSEMBLY,WEBASSEMBLY64,WEBASSEMBLY-WASI %s
+// RUN: %clang_cc1 -E -dM -ffreestanding -fgnuc-version=4.2.1 
-triple=wasm32-unknown-unknown -x c++ \
+// RUN:   < /dev/null \
+// RUN:   | FileCheck -match-full-lines -check-prefixes=WEBASSEMBLY-CXX %s
+// RUN: %clang_cc1 -E -dM -ffreestanding -fgnuc-version=4.2.1 
-triple=wasm32-unknown-unknown -x c++ -pthread -target-feature +atomics \
+// RUN:   < /dev/null \
+// RUN:   | FileCheck -match-full-lines 
-check-prefixes=WEBASSEMBLY-CXX-ATOMICS %s
 //
 // WEBASSEMBLY32:#define _ILP32 1
 // WEBASSEMBLY32-NOT:#define _LP64
@@ -1847,6 +1853,10 @@
 // WEBASSEMBLY64-NEXT:#define __wasm64 1
 // WEBASSEMBLY64-NEXT:#define __wasm64__ 1
 // WEBASSEMBLY-NEXT:#define __wasm__ 1
+// WEBASSEMBLY-CXX-NOT:_REENTRANT
+// WEBASSEMBLY-CXX-NOT:__STDCPP_THREADS__
+// WEBASSEMBLY-CXX-ATOMICS:#define _REENTRANT 1
+// WEBASSEMBLY-CXX-ATOMICS:#define __STDCPP_THREADS__ 1
 
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple i686-windows-cygnus < 
/dev/null | FileCheck -match-full-lines -check-prefix CYGWIN-X32 %s
 // CYGWIN-X32: #define __USER_LABEL_PREFIX__ _
Index: clang/lib/Basic/Targets/WebAssembly.h
===
--- clang/lib/Basic/Targets/WebAssembly.h
+++ clang/lib/Basic/Targets/WebAssembly.h
@@ -138,6 +138,8 @@
   bool hasExtIntType() const override { return true; }
 
   bool hasProtectedVisibility() const override { return false; }
+
+  void adjust(LangOptions ) override;
 };
 
 class LLVM_LIBRARY_VISIBILITY WebAssembly32TargetInfo
Index: clang/lib/Basic/Targets/WebAssembly.cpp
===
--- clang/lib/Basic/Targets/WebAssembly.cpp
+++ clang/lib/Basic/Targets/WebAssembly.cpp
@@ -253,6 +253,15 @@
  Builtin::FirstTSBuiltin);
 }
 
+void WebAssemblyTargetInfo::adjust(LangOptions ) {
+  // If the Atomics feature isn't available, turn off POSIXThreads and
+  // ThreadModel, so that we don't predefine _REENTRANT or __STDCPP_THREADS__.
+  if (!HasAtomics) {
+Opts.POSIXThreads = false;
+Opts.setThreadModel(LangOptions::ThreadModelKind::Single);
+  }
+}
+
 void WebAssembly32TargetInfo::getTargetDefines(const LangOptions ,
MacroBuilder ) const {
   WebAssemblyTargetInfo::getTargetDefines(Opts, Builder);


Index: clang/test/Preprocessor/init.c
===
--- clang/test/Preprocessor/init.c
+++ clang/test/Preprocessor/init.c
@@ -1479,6 +1479,12 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -fgnuc-version=4.2.1 -triple=wasm64-wasi \
 // RUN:   < /dev/null \
 // RUN:   | FileCheck -match-full-lines -check-prefixes=WEBASSEMBLY,WEBASSEMBLY64,WEBASSEMBLY-WASI %s
+// RUN: %clang_cc1 -E -dM -ffreestanding -fgnuc-version=4.2.1 -triple=wasm32-unknown-unknown -x c++ \
+// RUN:   < /dev/null \
+// RUN:   | FileCheck -match-full-lines -check-prefixes=WEBASSEMBLY-CXX %s
+// RUN: %clang_cc1 -E -dM -ffreestanding -fgnuc-version=4.2.1 -triple=wasm32-unknown-unknown -x c++ -pthread -target-feature +atomics \
+// RUN:   < /dev/null \
+// RUN:   | FileCheck -match-full-lines -check-prefixes=WEBASSEMBLY-CXX-ATOMICS %s
 //
 // WEBASSEMBLY32:#define _ILP32 1
 // WEBASSEMBLY32-NOT:#define _LP64
@@ -1847,6 +1853,10 @@
 // WEBASSEMBLY64-NEXT:#define __wasm64 1
 // WEBASSEMBLY64-NEXT:#define __wasm64__ 1
 // WEBASSEMBLY-NEXT:#define __wasm__ 1
+// WEBASSEMBLY-CXX-NOT:_REENTRANT
+// WEBASSEMBLY-CXX-NOT:__STDCPP_THREADS__
+// WEBASSEMBLY-CXX-ATOMICS:#define _REENTRANT 1
+// WEBASSEMBLY-CXX-ATOMICS:#define __STDCPP_THREADS__ 1
 
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple i686-windows-cygnus < /dev/null | FileCheck -match-full-lines -check-prefix CYGWIN-X32 %s
 // CYGWIN-X32: #define __USER_LABEL_PREFIX__ _
Index: clang/lib/Basic/Targets/WebAssembly.h
===
--- clang/lib/Basic/Targets/WebAssembly.h
+++ clang/lib/Basic/Targets/WebAssembly.h
@@ -138,6 +138,8 @@
   bool hasExtIntType() const override { return true; }
 
   

[clang] 95da64d - [WebAssembly] Use single-threaded mode when -matomics isn't enabled.

2021-02-04 Thread Dan Gohman via cfe-commits

Author: Dan Gohman
Date: 2021-02-04T18:16:48-08:00
New Revision: 95da64da23ac3a5855a8934a738b0fa10aa1323c

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

LOG: [WebAssembly] Use single-threaded mode when -matomics isn't enabled.

When the -matomics feature is not enabled, disable POSIXThreads
mode and set the thread model to Single, so that we don't predefine
macros like `__STDCPP_THREADS__`.

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

Added: 


Modified: 
clang/lib/Basic/Targets/WebAssembly.cpp
clang/lib/Basic/Targets/WebAssembly.h
clang/test/Preprocessor/init.c

Removed: 




diff  --git a/clang/lib/Basic/Targets/WebAssembly.cpp 
b/clang/lib/Basic/Targets/WebAssembly.cpp
index dcb3d8fd7790..89babe85794d 100644
--- a/clang/lib/Basic/Targets/WebAssembly.cpp
+++ b/clang/lib/Basic/Targets/WebAssembly.cpp
@@ -253,6 +253,15 @@ ArrayRef 
WebAssemblyTargetInfo::getTargetBuiltins() const {
  Builtin::FirstTSBuiltin);
 }
 
+void WebAssemblyTargetInfo::adjust(LangOptions ) {
+  // If the Atomics feature isn't available, turn off POSIXThreads and
+  // ThreadModel, so that we don't predefine _REENTRANT or __STDCPP_THREADS__.
+  if (!HasAtomics) {
+Opts.POSIXThreads = false;
+Opts.setThreadModel(LangOptions::ThreadModelKind::Single);
+  }
+}
+
 void WebAssembly32TargetInfo::getTargetDefines(const LangOptions ,
MacroBuilder ) const {
   WebAssemblyTargetInfo::getTargetDefines(Opts, Builder);

diff  --git a/clang/lib/Basic/Targets/WebAssembly.h 
b/clang/lib/Basic/Targets/WebAssembly.h
index 0068ccb5d71f..9150d849f601 100644
--- a/clang/lib/Basic/Targets/WebAssembly.h
+++ b/clang/lib/Basic/Targets/WebAssembly.h
@@ -138,6 +138,8 @@ class LLVM_LIBRARY_VISIBILITY WebAssemblyTargetInfo : 
public TargetInfo {
   bool hasExtIntType() const override { return true; }
 
   bool hasProtectedVisibility() const override { return false; }
+
+  void adjust(LangOptions ) override;
 };
 
 class LLVM_LIBRARY_VISIBILITY WebAssembly32TargetInfo

diff  --git a/clang/test/Preprocessor/init.c b/clang/test/Preprocessor/init.c
index 23c4989c5152..e29b6d3972f8 100644
--- a/clang/test/Preprocessor/init.c
+++ b/clang/test/Preprocessor/init.c
@@ -1479,6 +1479,12 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -fgnuc-version=4.2.1 
-triple=wasm64-wasi \
 // RUN:   < /dev/null \
 // RUN:   | FileCheck -match-full-lines 
-check-prefixes=WEBASSEMBLY,WEBASSEMBLY64,WEBASSEMBLY-WASI %s
+// RUN: %clang_cc1 -E -dM -ffreestanding -fgnuc-version=4.2.1 
-triple=wasm32-unknown-unknown -x c++ \
+// RUN:   < /dev/null \
+// RUN:   | FileCheck -match-full-lines -check-prefixes=WEBASSEMBLY-CXX %s
+// RUN: %clang_cc1 -E -dM -ffreestanding -fgnuc-version=4.2.1 
-triple=wasm32-unknown-unknown -x c++ -pthread -target-feature +atomics \
+// RUN:   < /dev/null \
+// RUN:   | FileCheck -match-full-lines 
-check-prefixes=WEBASSEMBLY-CXX-ATOMICS %s
 //
 // WEBASSEMBLY32:#define _ILP32 1
 // WEBASSEMBLY32-NOT:#define _LP64
@@ -1847,6 +1853,10 @@
 // WEBASSEMBLY64-NEXT:#define __wasm64 1
 // WEBASSEMBLY64-NEXT:#define __wasm64__ 1
 // WEBASSEMBLY-NEXT:#define __wasm__ 1
+// WEBASSEMBLY-CXX-NOT:_REENTRANT
+// WEBASSEMBLY-CXX-NOT:__STDCPP_THREADS__
+// WEBASSEMBLY-CXX-ATOMICS:#define _REENTRANT 1
+// WEBASSEMBLY-CXX-ATOMICS:#define __STDCPP_THREADS__ 1
 
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple i686-windows-cygnus < 
/dev/null | FileCheck -match-full-lines -check-prefix CYGWIN-X32 %s
 // CYGWIN-X32: #define __USER_LABEL_PREFIX__ _



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


[PATCH] D95691: Implement P2173 for attributes on lambdas

2021-02-04 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticGroups.td:269
+def CXXPre2BCompatPedantic :
+  DiagGroup<"c++98-c++11-c++14-c++17-c++20-compat-pedantic", [CXXPre2BCompat]>;
 

rjmccall wrote:
> rsmith wrote:
> > rjmccall wrote:
> > > Quuxplusone wrote:
> > > > aaron.ballman wrote:
> > > > > rjmccall wrote:
> > > > > > Uh, I think we're a couple standard releases past the point at 
> > > > > > which we should have reconsidered this schema.  I guess the problem 
> > > > > > is that we can't say `-Wpre-c++23-compat` without jumping the gun.  
> > > > > > Is there a problem with `-Wc++20-compat` and then having the 
> > > > > > earlier warning groups imply the later ones?  That seems to be what 
> > > > > > we do with `-Wc++98-compat`; did we abandon that approach 
> > > > > > intentionally?
> > > > > @rsmith may have more background here. I was following the pattern 
> > > > > already in the file, but I tend to agree that this pattern is not 
> > > > > leading us somewhere good. FWIW, I ran into a similar situation with 
> > > > > this on the C side of things in D95396, so we should probably be 
> > > > > consistent there too.
> > > > My understanding is that the //command-line user// is expected to pass
> > > > - `clang++ -std=c++20 -Wc++11-compat` to indicate "I want //actually// 
> > > > to compile in C++20 mode, but give me warnings about anything that 
> > > > would prevent compiling in C++11 mode"
> > > > - `clang++ -std=c++17 -Wc++14-compat` to indicate "I want //actually// 
> > > > to compile in C++17 mode, but give me warnings about anything that 
> > > > would prevent compiling in C++14 mode"
> > > > - `clang++ -std=c++14 -Wc++20-compat` to indicate "I want //actually// 
> > > > to compile in C++14 mode, but give me warnings about anything that 
> > > > would prevent compiling in C++20 mode" — EXCEPT that I think this is 
> > > > not supported. My impression is that forward-compatibility warnings are 
> > > > generally just rolled into `-Wall` and not handled separately beyond 
> > > > that?
> > > > 
> > > > I don't think any human user is expected to pass 
> > > > `-Wc++98-c++11-c++14-c++17-c++20-compat` by hand; it's just an internal 
> > > > name for a particular subset of `-Wc++98-compat`.
> > > > 
> > > > IOW, we could choose a new naming scheme for it, but that would be a 
> > > > purely internal change that won't affect how command-line users 
> > > > interact with Clang at all (for better and for worse).
> > > Diagnostic groups can both directly contain diagnostics and imply other 
> > > diagnostic groups, so I don't think there's any reason to make a 
> > > dedicated group just to contain the new diagnostics in e.g. 
> > > `-Wc++14-compat` except to allow someone turn on those warnings 
> > > separately.  And it does show up to users as the warning group under 
> > > `-fdiagnostics-show-option` (which is the default).
> > @Quuxplusone's comment describes the intent. `-std=c++20 -Wc++14-compat` 
> > should give a more or less complete list of reasons why the code would not 
> > compile in C++14 (at least on the language side; we don't check for stdlib 
> > compatibility). The other direction -- `-std=c++11 -Wc++14-compat` -- is 
> > more of a best-effort check for things that we've seen cause problems in 
> > practice and can easily detect. (As a consequence, I don't think there's 
> > any subset/superset relation between `-Wc++X-compat` and `-Wc++Y-compat`.)
> > 
> > I'd be happy to see these groups renamed to `-Wpre-c++20-compat` or 
> > similar. Warning group synonyms are relatively cheap, so I wouldn't be 
> > worried about adding a `-Wpre-c++2b-compat` now and renaming it to 
> > `-Wpre-c++23-compat` flag later.
> > 
> > (As an aside, it'd be handy if there were some way to mark a `DiagGroup` as 
> > existing only for grouping purposes, so that we could avoid exposing a `-W` 
> > flag for cases where groups are added for internal reasons.)
> Okay.  It looks like `-Wc++X-compat` is consistently (1) all the 
> this-feature-used-not-to-exist diagnostics from C++X and later plus (2) 
> warnings about deprecation and semantic changes introduced by exactly version 
> X.  This seems like an unfortunate pairing, basically caused by the option 
> names not being very clear about what kind of compatibility they mean.  If we 
> want @Quuxplusone's interpretation, which I agree is a natural human 
> interpretation of those command lines, we'll need special support for it in 
> diagnostic-option handling, so that we include specific diagnostics based on 
> the relationship between the option and the language version.
> 
> There is a natural subset relationship between the 
> this-feature-used-not-to-exist groups; we're just not taking advantage of it 
> at all.
(2) sounds like a bug. Maybe we should add `CXXPostXYCompat` groups, symmetric 
to the `CXXPreXYCompat` groups, to better handle that?

I'm not sure about the need for special 

[PATCH] D96082: [clang-tidy] Add 'readability-useless-return-value' check

2021-02-04 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added a comment.

New check must be mentioned in Release Notes.




Comment at: 
clang-tools-extra/clang-tidy/readability/UselessReturnValueCheck.cpp:1
+//===--- UselessReturnValueCheck.cpp - clang-tidy
+//---===//

Please merge two lines. See other files as example.



Comment at: 
clang-tools-extra/clang-tidy/readability/UselessReturnValueCheck.cpp:64
+
+  const auto *ProtoDecl = MatchedDecl->getCanonicalDecl();
+  if (ProtoDecl)

Please don't use auto unless type is explicitly stated in statement or iterator.



Comment at: 
clang-tools-extra/clang-tidy/readability/UselessReturnValueCheck.cpp:72
+  {
+auto RemovalStartLocation =
+MatchedReturn->getBeginLoc().getLocWithOffset(6);

Please don't use auto unless type is explicitly stated in statement or iterator.



Comment at: 
clang-tools-extra/clang-tidy/readability/UselessReturnValueCheck.cpp:74
+MatchedReturn->getBeginLoc().getLocWithOffset(6);
+auto RemovalEndLocation = MatchedReturn->getEndLoc();
+auto RemovalRange = SourceRange(RemovalStartLocation, RemovalEndLocation);

Please don't use auto unless type is explicitly stated in statement or iterator.



Comment at: 
clang-tools-extra/clang-tidy/readability/UselessReturnValueCheck.cpp:75
+auto RemovalEndLocation = MatchedReturn->getEndLoc();
+auto RemovalRange = SourceRange(RemovalStartLocation, RemovalEndLocation);
+diag(RemovalStartLocation, "remove return value", DiagnosticIDs::Note)

Please don't use auto unless type is explicitly stated in statement or iterator.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/readability-useless-return-value.rst:6
+
+This check looks for functions that always return ``0``.
+Such functions could be ``void``.

Please use single back-tick for value.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/readability-useless-return-value.rst:16
+it feels strange to have only 1 possible return value.
+
+

Please remove one empty line.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/readability-useless-return-value.rst:20
+
+The following function `f` and `f2` return always ``0``:
+

Please use single back-tick for value.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/readability-useless-return-value.rst:38
+  void f() {
+return;
+  }

Return is redundant. See readability-redundant-control-flow.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/readability-useless-return-value.rst:43
+int ret = 0;
+return;
+  }

Return is redundant. See readability-redundant-control-flow.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/readability-useless-return-value.rst:45
+  }
+
+

Please remove one empty line.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96082

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


[PATCH] D96092: [AST] Update LVal before evaluating lambda decl fields.

2021-02-04 Thread Zequan Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG96fb49c3ff8e: [AST] Update LVal before evaluating lambda 
decl fields. (authored by zequanwu).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96092

Files:
  clang/lib/AST/ExprConstant.cpp
  clang/test/SemaCXX/constant-expression-cxx2a.cpp


Index: clang/test/SemaCXX/constant-expression-cxx2a.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx2a.cpp
+++ clang/test/SemaCXX/constant-expression-cxx2a.cpp
@@ -1437,3 +1437,13 @@
   return true;
 }
 static_assert(destroy_at_test());
+
+namespace PR48582 {
+  struct S {
+void *p = this;
+constexpr S() {}
+constexpr S(const S&) {}
+  };
+  constexpr bool b = [a = S(), b = S()] { return a.p == b.p; }();
+  static_assert(!b);
+}
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -10016,6 +10016,7 @@
   auto *CaptureInitIt = E->capture_init_begin();
   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
   bool Success = true;
+  const ASTRecordLayout  = Info.Ctx.getASTRecordLayout(ClosureClass);
   for (const auto *Field : ClosureClass->fields()) {
 assert(CaptureInitIt != E->capture_init_end());
 // Get the initializer for this field
@@ -10026,8 +10027,13 @@
 if (!CurFieldInit)
   return Error(E);
 
+LValue Subobject = This;
+
+if (!HandleLValueMember(Info, E, Subobject, Field, ))
+  return false;
+
 APValue  = Result.getStructField(Field->getFieldIndex());
-if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
+if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
   if (!Info.keepEvaluatingAfterFailure())
 return false;
   Success = false;


Index: clang/test/SemaCXX/constant-expression-cxx2a.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx2a.cpp
+++ clang/test/SemaCXX/constant-expression-cxx2a.cpp
@@ -1437,3 +1437,13 @@
   return true;
 }
 static_assert(destroy_at_test());
+
+namespace PR48582 {
+  struct S {
+void *p = this;
+constexpr S() {}
+constexpr S(const S&) {}
+  };
+  constexpr bool b = [a = S(), b = S()] { return a.p == b.p; }();
+  static_assert(!b);
+}
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -10016,6 +10016,7 @@
   auto *CaptureInitIt = E->capture_init_begin();
   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
   bool Success = true;
+  const ASTRecordLayout  = Info.Ctx.getASTRecordLayout(ClosureClass);
   for (const auto *Field : ClosureClass->fields()) {
 assert(CaptureInitIt != E->capture_init_end());
 // Get the initializer for this field
@@ -10026,8 +10027,13 @@
 if (!CurFieldInit)
   return Error(E);
 
+LValue Subobject = This;
+
+if (!HandleLValueMember(Info, E, Subobject, Field, ))
+  return false;
+
 APValue  = Result.getStructField(Field->getFieldIndex());
-if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
+if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
   if (!Info.keepEvaluatingAfterFailure())
 return false;
   Success = false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 96fb49c - [AST] Update LVal before evaluating lambda decl fields.

2021-02-04 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2021-02-04T17:01:09-08:00
New Revision: 96fb49c3ff8e08680127ddd4ec45a0e6c199243b

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

LOG: [AST] Update LVal before evaluating lambda decl fields.

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

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/test/SemaCXX/constant-expression-cxx2a.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 0f0c33b0ac85..b19f11208485 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -10016,6 +10016,7 @@ bool RecordExprEvaluator::VisitLambdaExpr(const 
LambdaExpr *E) {
   auto *CaptureInitIt = E->capture_init_begin();
   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
   bool Success = true;
+  const ASTRecordLayout  = Info.Ctx.getASTRecordLayout(ClosureClass);
   for (const auto *Field : ClosureClass->fields()) {
 assert(CaptureInitIt != E->capture_init_end());
 // Get the initializer for this field
@@ -10026,8 +10027,13 @@ bool RecordExprEvaluator::VisitLambdaExpr(const 
LambdaExpr *E) {
 if (!CurFieldInit)
   return Error(E);
 
+LValue Subobject = This;
+
+if (!HandleLValueMember(Info, E, Subobject, Field, ))
+  return false;
+
 APValue  = Result.getStructField(Field->getFieldIndex());
-if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
+if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
   if (!Info.keepEvaluatingAfterFailure())
 return false;
   Success = false;

diff  --git a/clang/test/SemaCXX/constant-expression-cxx2a.cpp 
b/clang/test/SemaCXX/constant-expression-cxx2a.cpp
index 4adadc9988ab..86020a09db44 100644
--- a/clang/test/SemaCXX/constant-expression-cxx2a.cpp
+++ b/clang/test/SemaCXX/constant-expression-cxx2a.cpp
@@ -1437,3 +1437,13 @@ constexpr bool destroy_at_test() {
   return true;
 }
 static_assert(destroy_at_test());
+
+namespace PR48582 {
+  struct S {
+void *p = this;
+constexpr S() {}
+constexpr S(const S&) {}
+  };
+  constexpr bool b = [a = S(), b = S()] { return a.p == b.p; }();
+  static_assert(!b);
+}



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


[PATCH] D96092: [AST] Update LVal before evaluating lambda decl fields.

2021-02-04 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu added inline comments.



Comment at: clang/lib/AST/ExprConstant.cpp:10032-10033
+
+// FIXME: Diagnostics here should point to the end of the initializer
+// list, not the start.
+if (!HandleLValueMember(Info, E, Subobject, Field, ))

rsmith wrote:
> I don't think this FIXME is appropriate in the new context; just remove it. 
> `E` here should already be providing the best location information we have.
Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96092

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


[PATCH] D96092: [AST] Update LVal before evaluating lambda decl fields.

2021-02-04 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu updated this revision to Diff 321617.
zequanwu marked an inline comment as done.
zequanwu added a comment.

Remove comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96092

Files:
  clang/lib/AST/ExprConstant.cpp
  clang/test/SemaCXX/constant-expression-cxx2a.cpp


Index: clang/test/SemaCXX/constant-expression-cxx2a.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx2a.cpp
+++ clang/test/SemaCXX/constant-expression-cxx2a.cpp
@@ -1437,3 +1437,13 @@
   return true;
 }
 static_assert(destroy_at_test());
+
+namespace PR48582 {
+  struct S {
+void *p = this;
+constexpr S() {}
+constexpr S(const S&) {}
+  };
+  constexpr bool b = [a = S(), b = S()] { return a.p == b.p; }();
+  static_assert(!b);
+}
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -10016,6 +10016,7 @@
   auto *CaptureInitIt = E->capture_init_begin();
   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
   bool Success = true;
+  const ASTRecordLayout  = Info.Ctx.getASTRecordLayout(ClosureClass);
   for (const auto *Field : ClosureClass->fields()) {
 assert(CaptureInitIt != E->capture_init_end());
 // Get the initializer for this field
@@ -10026,8 +10027,13 @@
 if (!CurFieldInit)
   return Error(E);
 
+LValue Subobject = This;
+
+if (!HandleLValueMember(Info, E, Subobject, Field, ))
+  return false;
+
 APValue  = Result.getStructField(Field->getFieldIndex());
-if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
+if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
   if (!Info.keepEvaluatingAfterFailure())
 return false;
   Success = false;


Index: clang/test/SemaCXX/constant-expression-cxx2a.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx2a.cpp
+++ clang/test/SemaCXX/constant-expression-cxx2a.cpp
@@ -1437,3 +1437,13 @@
   return true;
 }
 static_assert(destroy_at_test());
+
+namespace PR48582 {
+  struct S {
+void *p = this;
+constexpr S() {}
+constexpr S(const S&) {}
+  };
+  constexpr bool b = [a = S(), b = S()] { return a.p == b.p; }();
+  static_assert(!b);
+}
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -10016,6 +10016,7 @@
   auto *CaptureInitIt = E->capture_init_begin();
   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
   bool Success = true;
+  const ASTRecordLayout  = Info.Ctx.getASTRecordLayout(ClosureClass);
   for (const auto *Field : ClosureClass->fields()) {
 assert(CaptureInitIt != E->capture_init_end());
 // Get the initializer for this field
@@ -10026,8 +10027,13 @@
 if (!CurFieldInit)
   return Error(E);
 
+LValue Subobject = This;
+
+if (!HandleLValueMember(Info, E, Subobject, Field, ))
+  return false;
+
 APValue  = Result.getStructField(Field->getFieldIndex());
-if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
+if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
   if (!Info.keepEvaluatingAfterFailure())
 return false;
   Success = false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D96092: [AST] Update LVal before evaluating lambda decl fields.

2021-02-04 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith accepted this revision.
rsmith added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/AST/ExprConstant.cpp:10032-10033
+
+// FIXME: Diagnostics here should point to the end of the initializer
+// list, not the start.
+if (!HandleLValueMember(Info, E, Subobject, Field, ))

I don't think this FIXME is appropriate in the new context; just remove it. `E` 
here should already be providing the best location information we have.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96092

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


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

2021-02-04 Thread Tiago Macarios via Phabricator via cfe-commits
tiagoma marked 5 inline comments as done.
tiagoma added inline comments.



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

njames93 wrote:
> MyDeveloperDay wrote:
> > MyDeveloperDay wrote:
> > > MyDeveloperDay wrote:
> > > > are you testing do/while? 
> > > whilst people discuss the ethics of modifying the code ;-) 
> > > 
> > > Can you add some comment based examples
> > > 
> > > ```
> > > if (condition) // my test
> > >   you_do_you();
> > > 
> > > if (condition)
> > >   you_do_you(); // my test
> > > ```
> > bonus points..
> > 
> > ```
> > if /*condition*/ (condition) /*condition*/
> > /*condition*/  you_do_you(); /*condition*/
> > ```
> Should also add test for chained conditionals just to make sure the semantics 
> of the code doesn't change.
> ```lang=c
> if (A)
>   if (B)
> callAB();
>   else
> callA();
> else if (B)
>   callB();
> else
>   call();```
do/while are not supported in it's current form. We would need to change the 
logic to add more state. I can have a look at it after this patch is accepted.



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

tiagoma wrote:
> njames93 wrote:
> > MyDeveloperDay wrote:
> > > MyDeveloperDay wrote:
> > > > MyDeveloperDay wrote:
> > > > > are you testing do/while? 
> > > > whilst people discuss the ethics of modifying the code ;-) 
> > > > 
> > > > Can you add some comment based examples
> > > > 
> > > > ```
> > > > if (condition) // my test
> > > >   you_do_you();
> > > > 
> > > > if (condition)
> > > >   you_do_you(); // my test
> > > > ```
> > > bonus points..
> > > 
> > > ```
> > > if /*condition*/ (condition) /*condition*/
> > > /*condition*/  you_do_you(); /*condition*/
> > > ```
> > Should also add test for chained conditionals just to make sure the 
> > semantics of the code doesn't change.
> > ```lang=c
> > if (A)
> >   if (B)
> > callAB();
> >   else
> > callA();
> > else if (B)
> >   callB();
> > else
> >   call();```
> do/while are not supported in it's current form. We would need to change the 
> logic to add more state. I can have a look at it after this patch is accepted.
This specific test will fail by itself, ie:

```
StringRef Test = "if /*condition*/ (condition)  /*condition*/\n"
 "  /*condition*/ you_do_you(); /*condition*/";

verifyFormat(Test);
```

AFAICT it is because test::messUp causes the 2nd and 3rd comment to stay on the 
same line. I added a variation of the test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95168

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


[PATCH] D96091: [WebAssembly] Use single-threaded mode when -matomics isn't enabled.

2021-02-04 Thread Thomas Lively via Phabricator via cfe-commits
tlively accepted this revision.
tlively added a comment.
This revision is now accepted and ready to land.

LGTM, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96091

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


[PATCH] D96092: [AST] Update LVal before evaluating lambda decl fields.

2021-02-04 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu created this revision.
zequanwu added reviewers: rsmith, rnk.
zequanwu requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

PR48582


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96092

Files:
  clang/lib/AST/ExprConstant.cpp
  clang/test/SemaCXX/constant-expression-cxx2a.cpp


Index: clang/test/SemaCXX/constant-expression-cxx2a.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx2a.cpp
+++ clang/test/SemaCXX/constant-expression-cxx2a.cpp
@@ -1437,3 +1437,13 @@
   return true;
 }
 static_assert(destroy_at_test());
+
+namespace PR48582 {
+  struct S {
+void *p = this;
+constexpr S() {}
+constexpr S(const S&) {}
+  };
+  constexpr bool b = [a = S(), b = S()] { return a.p == b.p; }();
+  static_assert(!b);
+}
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -10016,6 +10016,7 @@
   auto *CaptureInitIt = E->capture_init_begin();
   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
   bool Success = true;
+  const ASTRecordLayout  = Info.Ctx.getASTRecordLayout(ClosureClass);
   for (const auto *Field : ClosureClass->fields()) {
 assert(CaptureInitIt != E->capture_init_end());
 // Get the initializer for this field
@@ -10026,8 +10027,15 @@
 if (!CurFieldInit)
   return Error(E);
 
+LValue Subobject = This;
+
+// FIXME: Diagnostics here should point to the end of the initializer
+// list, not the start.
+if (!HandleLValueMember(Info, E, Subobject, Field, ))
+  return false;
+
 APValue  = Result.getStructField(Field->getFieldIndex());
-if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
+if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
   if (!Info.keepEvaluatingAfterFailure())
 return false;
   Success = false;


Index: clang/test/SemaCXX/constant-expression-cxx2a.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx2a.cpp
+++ clang/test/SemaCXX/constant-expression-cxx2a.cpp
@@ -1437,3 +1437,13 @@
   return true;
 }
 static_assert(destroy_at_test());
+
+namespace PR48582 {
+  struct S {
+void *p = this;
+constexpr S() {}
+constexpr S(const S&) {}
+  };
+  constexpr bool b = [a = S(), b = S()] { return a.p == b.p; }();
+  static_assert(!b);
+}
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -10016,6 +10016,7 @@
   auto *CaptureInitIt = E->capture_init_begin();
   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
   bool Success = true;
+  const ASTRecordLayout  = Info.Ctx.getASTRecordLayout(ClosureClass);
   for (const auto *Field : ClosureClass->fields()) {
 assert(CaptureInitIt != E->capture_init_end());
 // Get the initializer for this field
@@ -10026,8 +10027,15 @@
 if (!CurFieldInit)
   return Error(E);
 
+LValue Subobject = This;
+
+// FIXME: Diagnostics here should point to the end of the initializer
+// list, not the start.
+if (!HandleLValueMember(Info, E, Subobject, Field, ))
+  return false;
+
 APValue  = Result.getStructField(Field->getFieldIndex());
-if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
+if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
   if (!Info.keepEvaluatingAfterFailure())
 return false;
   Success = false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

2021-02-04 Thread Tiago Macarios via Phabricator via cfe-commits
tiagoma updated this revision to Diff 321611.
tiagoma added a comment.

Add more tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95168

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

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -72,7 +72,10 @@
 EXPECT_EQ(Expected.str(), format(Expected, Style))
 << "Expected code is not stable";
 EXPECT_EQ(Expected.str(), format(Code, Style));
-if (Style.Language == FormatStyle::LK_Cpp) {
+// clang::format::internal::reformat does not run any of the options that
+// modify code for ObjC
+if (Style.Language == FormatStyle::LK_Cpp &&
+Style.InsertBraces == FormatStyle::BIS_Never) {
   // Objective-C++ is a superset of C++, so everything checked for C++
   // needs to be checked for Objective-C++ as well.
   FormatStyle ObjCStyle = Style;
@@ -15879,6 +15882,12 @@
   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
   FormatStyle::IEBS_NoIndent);
 
+  Style.InsertBraces = FormatStyle::BIS_Never;
+  CHECK_PARSE("InsertBraces: Always", InsertBraces, FormatStyle::BIS_Always);
+  CHECK_PARSE("InsertBraces: WrapLikely", InsertBraces,
+  FormatStyle::BIS_WrapLikely);
+  CHECK_PARSE("InsertBraces: Never", InsertBraces, FormatStyle::BIS_Never);
+
   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
   FormatStyle::BFCS_Both);
@@ -19050,6 +19059,150 @@
 "}",
 format(Source, Style));
 }
+
+TEST_F(FormatTest, InsertBraces) {
+  FormatStyle Style = getLLVMStyle();
+  StringRef IfSourceShort = "if (condition)\n"
+"  call_function(arg, arg);";
+  verifyFormat(IfSourceShort);
+
+  StringRef IfSourceLong = "if (condition)\n"
+   "  call_function(arg, arg, arg, arg, arg, arg);";
+  verifyFormat(IfSourceLong);
+
+  StringRef IfElseSourceShort = "if (condition)\n"
+"  a_function(arg, arg);\n"
+"else\n"
+"  another_function(arg, arg);";
+  verifyFormat(IfElseSourceShort);
+
+  StringRef IfElseSourceLong =
+  "if (condition)\n"
+  "  a_function(arg, arg, arg, arg, arg, arg);\n"
+  "else\n"
+  "  another_function(arg, arg, arg, arg, arg, arg);";
+  verifyFormat(IfElseSourceLong);
+
+  StringRef ForSourceShort = "for (auto val : container)\n"
+ "  call_function(arg, arg);";
+  verifyFormat(ForSourceShort);
+
+  StringRef ForSourceLong = "for (auto val : container)\n"
+"  call_function(arg, arg, arg, arg, arg, arg);";
+  verifyFormat(ForSourceLong);
+
+  StringRef ChainedConditionals = "if (A)\n"
+  "  if (B)\n"
+  "callAB();\n"
+  "  else\n"
+  "callA();\n"
+  "else if (B)\n"
+  "  callB();\n"
+  "else\n"
+  "  call();\n";
+  verifyFormat(ChainedConditionals);
+
+  StringRef IfWithMultilineComment =
+  "if /*condition*/ (condition) /*condition*/\n"
+  "  you_do_you();  /*condition*/";
+  verifyFormat(IfWithMultilineComment);
+
+  StringRef IfSinglelineCommentOnConditional = "if (condition) // my test\n"
+   "  you_do_you();";
+  verifyFormat(IfSinglelineCommentOnConditional);
+
+  Style.InsertBraces = FormatStyle::BIS_Always;
+
+  verifyFormat("if (condition) {\n"
+   "  call_function(arg, arg);\n"
+   "}",
+   IfSourceShort, Style);
+
+  verifyFormat("if (condition) {\n"
+   "  call_function(arg, arg, arg, arg, arg, arg);\n"
+   "}",
+   IfSourceLong, Style);
+
+  verifyFormat("if (condition) {\n"
+   "  a_function(arg, arg);\n"
+   "} else {\n"
+   "  another_function(arg, arg);\n"
+   "}",
+   IfElseSourceShort, Style);
+
+  verifyFormat("if (condition) {\n"
+   "  a_function(arg, arg, arg, arg, arg, arg);\n"
+   "} else {\n"
+   "  another_function(arg, arg, arg, arg, arg, arg);\n"
+   "}",
+   IfElseSourceLong, Style);
+
+  verifyFormat("for (auto val : container) {\n"
+   "  call_function(arg, arg);\n"
+   "}",
+   ForSourceShort, Style);
+
+  verifyFormat("for (auto val : container) {\n"
+ 

[PATCH] D92928: [analyzer] Highlight arrows for currently selected event

2021-02-04 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.
Herald added a subscriber: nullptr.cpp.

HTML sample looks fine! But there is the same problem as in D92639 
. IE doesn't draw arrows.




Comment at: clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp:166
+  ArrowMap(unsigned Size) : Base(Size, 0) {}
+  unsigned getTotalNumberOfArrows() const { return at(0); }
+};

  # Whether `size()` is not an aim?
  # It can fail in case of empty container.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92928

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


[PATCH] D96091: [WebAssembly] Use single-threaded mode when -matomics isn't enabled.

2021-02-04 Thread Dan Gohman via Phabricator via cfe-commits
sunfish created this revision.
sunfish added a reviewer: tlively.
Herald added subscribers: ecnelises, jfb, jgravelle-google, sbc100, dschuff.
sunfish requested review of this revision.
Herald added subscribers: cfe-commits, aheejin.
Herald added a project: clang.

When the -matomics feature is not enabled, disable POSIXThreads
mode and set the thread model to Single, so that we don't predefine
macros like `__STDCPP_THREADS__`.

This will help save code size (a thing I care about!) in programs which
use `__STDCPP_THREADS__` to determine whether to include support
for threads.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96091

Files:
  clang/lib/Basic/Targets/WebAssembly.cpp
  clang/lib/Basic/Targets/WebAssembly.h
  clang/test/Preprocessor/init.c


Index: clang/test/Preprocessor/init.c
===
--- clang/test/Preprocessor/init.c
+++ clang/test/Preprocessor/init.c
@@ -1479,6 +1479,12 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -fgnuc-version=4.2.1 
-triple=wasm64-wasi \
 // RUN:   < /dev/null \
 // RUN:   | FileCheck -match-full-lines 
-check-prefixes=WEBASSEMBLY,WEBASSEMBLY64,WEBASSEMBLY-WASI %s
+// RUN: %clang_cc1 -E -dM -ffreestanding -fgnuc-version=4.2.1 
-triple=wasm32-unknown-unknown -x c++ \
+// RUN:   < /dev/null \
+// RUN:   | FileCheck -match-full-lines -check-prefixes=WEBASSEMBLY-CXX %s
+// RUN: %clang_cc1 -E -dM -ffreestanding -fgnuc-version=4.2.1 
-triple=wasm32-unknown-unknown -x c++ -pthread -target-feature +atomics \
+// RUN:   < /dev/null \
+// RUN:   | FileCheck -match-full-lines 
-check-prefixes=WEBASSEMBLY-CXX-ATOMICS %s
 //
 // WEBASSEMBLY32:#define _ILP32 1
 // WEBASSEMBLY32-NOT:#define _LP64
@@ -1847,6 +1853,10 @@
 // WEBASSEMBLY64-NEXT:#define __wasm64 1
 // WEBASSEMBLY64-NEXT:#define __wasm64__ 1
 // WEBASSEMBLY-NEXT:#define __wasm__ 1
+// WEBASSEMBLY-CXX-NOT:_REENTRANT
+// WEBASSEMBLY-CXX-NOT:__STDCPP_THREADS__
+// WEBASSEMBLY-CXX-ATOMICS:#define _REENTRANT 1
+// WEBASSEMBLY-CXX-ATOMICS:#define __STDCPP_THREADS__ 1
 
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple i686-windows-cygnus < 
/dev/null | FileCheck -match-full-lines -check-prefix CYGWIN-X32 %s
 // CYGWIN-X32: #define __USER_LABEL_PREFIX__ _
Index: clang/lib/Basic/Targets/WebAssembly.h
===
--- clang/lib/Basic/Targets/WebAssembly.h
+++ clang/lib/Basic/Targets/WebAssembly.h
@@ -138,6 +138,8 @@
   bool hasExtIntType() const override { return true; }
 
   bool hasProtectedVisibility() const override { return false; }
+
+  void adjust(LangOptions ) override;
 };
 
 class LLVM_LIBRARY_VISIBILITY WebAssembly32TargetInfo
Index: clang/lib/Basic/Targets/WebAssembly.cpp
===
--- clang/lib/Basic/Targets/WebAssembly.cpp
+++ clang/lib/Basic/Targets/WebAssembly.cpp
@@ -253,6 +253,15 @@
  Builtin::FirstTSBuiltin);
 }
 
+void WebAssemblyTargetInfo::adjust(LangOptions ) {
+  // If the Atomics feature isn't available, turn off POSIXThreads and
+  // ThreadModel, so that we don't predefine _REENTRANT or __STDCPP_THREADS__.
+  if (!HasAtomics) {
+Opts.POSIXThreads = false;
+Opts.setThreadModel(LangOptions::ThreadModelKind::Single);
+  }
+}
+
 void WebAssembly32TargetInfo::getTargetDefines(const LangOptions ,
MacroBuilder ) const {
   WebAssemblyTargetInfo::getTargetDefines(Opts, Builder);


Index: clang/test/Preprocessor/init.c
===
--- clang/test/Preprocessor/init.c
+++ clang/test/Preprocessor/init.c
@@ -1479,6 +1479,12 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -fgnuc-version=4.2.1 -triple=wasm64-wasi \
 // RUN:   < /dev/null \
 // RUN:   | FileCheck -match-full-lines -check-prefixes=WEBASSEMBLY,WEBASSEMBLY64,WEBASSEMBLY-WASI %s
+// RUN: %clang_cc1 -E -dM -ffreestanding -fgnuc-version=4.2.1 -triple=wasm32-unknown-unknown -x c++ \
+// RUN:   < /dev/null \
+// RUN:   | FileCheck -match-full-lines -check-prefixes=WEBASSEMBLY-CXX %s
+// RUN: %clang_cc1 -E -dM -ffreestanding -fgnuc-version=4.2.1 -triple=wasm32-unknown-unknown -x c++ -pthread -target-feature +atomics \
+// RUN:   < /dev/null \
+// RUN:   | FileCheck -match-full-lines -check-prefixes=WEBASSEMBLY-CXX-ATOMICS %s
 //
 // WEBASSEMBLY32:#define _ILP32 1
 // WEBASSEMBLY32-NOT:#define _LP64
@@ -1847,6 +1853,10 @@
 // WEBASSEMBLY64-NEXT:#define __wasm64 1
 // WEBASSEMBLY64-NEXT:#define __wasm64__ 1
 // WEBASSEMBLY-NEXT:#define __wasm__ 1
+// WEBASSEMBLY-CXX-NOT:_REENTRANT
+// WEBASSEMBLY-CXX-NOT:__STDCPP_THREADS__
+// WEBASSEMBLY-CXX-ATOMICS:#define _REENTRANT 1
+// WEBASSEMBLY-CXX-ATOMICS:#define __STDCPP_THREADS__ 1
 
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple i686-windows-cygnus < /dev/null | FileCheck -match-full-lines -check-prefix CYGWIN-X32 %s
 // CYGWIN-X32: #define __USER_LABEL_PREFIX__ _
Index: 

[PATCH] D95691: Implement P2173 for attributes on lambdas

2021-02-04 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticGroups.td:269
+def CXXPre2BCompatPedantic :
+  DiagGroup<"c++98-c++11-c++14-c++17-c++20-compat-pedantic", [CXXPre2BCompat]>;
 

rsmith wrote:
> rjmccall wrote:
> > Quuxplusone wrote:
> > > aaron.ballman wrote:
> > > > rjmccall wrote:
> > > > > Uh, I think we're a couple standard releases past the point at which 
> > > > > we should have reconsidered this schema.  I guess the problem is that 
> > > > > we can't say `-Wpre-c++23-compat` without jumping the gun.  Is there 
> > > > > a problem with `-Wc++20-compat` and then having the earlier warning 
> > > > > groups imply the later ones?  That seems to be what we do with 
> > > > > `-Wc++98-compat`; did we abandon that approach intentionally?
> > > > @rsmith may have more background here. I was following the pattern 
> > > > already in the file, but I tend to agree that this pattern is not 
> > > > leading us somewhere good. FWIW, I ran into a similar situation with 
> > > > this on the C side of things in D95396, so we should probably be 
> > > > consistent there too.
> > > My understanding is that the //command-line user// is expected to pass
> > > - `clang++ -std=c++20 -Wc++11-compat` to indicate "I want //actually// to 
> > > compile in C++20 mode, but give me warnings about anything that would 
> > > prevent compiling in C++11 mode"
> > > - `clang++ -std=c++17 -Wc++14-compat` to indicate "I want //actually// to 
> > > compile in C++17 mode, but give me warnings about anything that would 
> > > prevent compiling in C++14 mode"
> > > - `clang++ -std=c++14 -Wc++20-compat` to indicate "I want //actually// to 
> > > compile in C++14 mode, but give me warnings about anything that would 
> > > prevent compiling in C++20 mode" — EXCEPT that I think this is not 
> > > supported. My impression is that forward-compatibility warnings are 
> > > generally just rolled into `-Wall` and not handled separately beyond that?
> > > 
> > > I don't think any human user is expected to pass 
> > > `-Wc++98-c++11-c++14-c++17-c++20-compat` by hand; it's just an internal 
> > > name for a particular subset of `-Wc++98-compat`.
> > > 
> > > IOW, we could choose a new naming scheme for it, but that would be a 
> > > purely internal change that won't affect how command-line users interact 
> > > with Clang at all (for better and for worse).
> > Diagnostic groups can both directly contain diagnostics and imply other 
> > diagnostic groups, so I don't think there's any reason to make a dedicated 
> > group just to contain the new diagnostics in e.g. `-Wc++14-compat` except 
> > to allow someone turn on those warnings separately.  And it does show up to 
> > users as the warning group under `-fdiagnostics-show-option` (which is the 
> > default).
> @Quuxplusone's comment describes the intent. `-std=c++20 -Wc++14-compat` 
> should give a more or less complete list of reasons why the code would not 
> compile in C++14 (at least on the language side; we don't check for stdlib 
> compatibility). The other direction -- `-std=c++11 -Wc++14-compat` -- is more 
> of a best-effort check for things that we've seen cause problems in practice 
> and can easily detect. (As a consequence, I don't think there's any 
> subset/superset relation between `-Wc++X-compat` and `-Wc++Y-compat`.)
> 
> I'd be happy to see these groups renamed to `-Wpre-c++20-compat` or similar. 
> Warning group synonyms are relatively cheap, so I wouldn't be worried about 
> adding a `-Wpre-c++2b-compat` now and renaming it to `-Wpre-c++23-compat` 
> flag later.
> 
> (As an aside, it'd be handy if there were some way to mark a `DiagGroup` as 
> existing only for grouping purposes, so that we could avoid exposing a `-W` 
> flag for cases where groups are added for internal reasons.)
Okay.  It looks like `-Wc++X-compat` is consistently (1) all the 
this-feature-used-not-to-exist diagnostics from C++X and later plus (2) 
warnings about deprecation and semantic changes introduced by exactly version 
X.  This seems like an unfortunate pairing, basically caused by the option 
names not being very clear about what kind of compatibility they mean.  If we 
want @Quuxplusone's interpretation, which I agree is a natural human 
interpretation of those command lines, we'll need special support for it in 
diagnostic-option handling, so that we include specific diagnostics based on 
the relationship between the option and the language version.

There is a natural subset relationship between the 
this-feature-used-not-to-exist groups; we're just not taking advantage of it at 
all.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95691

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


[PATCH] D96090: [analyzer] Replace StoreManager::CastRetrievedVal with SValBuilder::evalCast

2021-02-04 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov created this revision.
ASDenysPetrov added reviewers: NoQ, steakhal, xazax.hun.
ASDenysPetrov added a project: clang.
Herald added subscribers: nullptr.cpp, martong, Charusso, dkrupp, donat.nagy, 
Szelethus, mikhail.ramalho, a.sidorin, rnkovacs, szepet, baloghadamsoftware.
ASDenysPetrov requested review of this revision.
Herald added a subscriber: cfe-commits.

Move logic from CastRetrievedVal to evalCast and replace CastRetrievedVal with 
evalCast. Also we need to move guts from SimpleSValBuilder::dispatchCast inside 
evalCast. Now evalCast operates in two modes:

- without passing last parameter it works like previous dispatchCast
- with passing last parameter it stays as is.

This patch ideally shall not change any behavior. (Should we mark it as [NFC]?)

This is an intermediate revision for D89055 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96090

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
  clang/lib/StaticAnalyzer/Core/Store.cpp

Index: clang/lib/StaticAnalyzer/Core/Store.cpp
===
--- clang/lib/StaticAnalyzer/Core/Store.cpp
+++ clang/lib/StaticAnalyzer/Core/Store.cpp
@@ -394,37 +394,6 @@
   return UnknownVal();
 }
 
-static bool hasSameUnqualifiedPointeeType(QualType ty1, QualType ty2) {
-  return ty1->getPointeeType().getCanonicalType().getTypePtr() ==
- ty2->getPointeeType().getCanonicalType().getTypePtr();
-}
-
-/// CastRetrievedVal - Used by subclasses of StoreManager to implement
-///  implicit casts that arise from loads from regions that are reinterpreted
-///  as another region.
-SVal StoreManager::CastRetrievedVal(SVal V, const TypedValueRegion *R,
-QualType castTy) {
-  if (castTy.isNull() || V.isUnknownOrUndef())
-return V;
-
-  // When retrieving symbolic pointer and expecting a non-void pointer,
-  // wrap them into element regions of the expected type if necessary.
-  // SValBuilder::dispatchCast() doesn't do that, but it is necessary to
-  // make sure that the retrieved value makes sense, because there's no other
-  // cast in the AST that would tell us to cast it to the correct pointer type.
-  // We might need to do that for non-void pointers as well.
-  // FIXME: We really need a single good function to perform casts for us
-  // correctly every time we need it.
-  if (castTy->isPointerType() && !castTy->isVoidPointerType())
-if (const auto *SR = dyn_cast_or_null(V.getAsRegion())) {
-  QualType sr = SR->getSymbol()->getType();
-  if (!hasSameUnqualifiedPointeeType(sr, castTy))
-  return loc::MemRegionVal(castRegion(SR, castTy));
-}
-
-  return svalBuilder.dispatchCast(V, castTy);
-}
-
 SVal StoreManager::getLValueFieldOrIvar(const Decl *D, SVal Base) {
   if (Base.isUnknownOrUndef())
 return Base;
Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -66,9 +66,7 @@
 //===--===//
 
 SVal SimpleSValBuilder::dispatchCast(SVal Val, QualType CastTy) {
-  assert(Val.getAs() || Val.getAs());
-  return Val.getAs() ? evalCastFromLoc(Val.castAs(), CastTy)
-   : evalCastFromNonLoc(Val.castAs(), CastTy);
+  return evalCast(Val, CastTy);
 }
 
 SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -541,20 +541,29 @@
 // `evalCastKind` and `evalCastSubKind` are helpers
 //===--===//
 
-SVal SValBuilder::evalCast(SVal V, QualType CastTy, QualType OriginalTy) {
-  CastTy = Context.getCanonicalType(CastTy);
-  OriginalTy = Context.getCanonicalType(OriginalTy);
-  if (CastTy == OriginalTy)
+// In case when `OriginalTy.isNull() == true` we cast `V` a bit differently.
+SVal SValBuilder::evalCast(SVal V, QualType CastTy,
+   QualType OriginalTy /*= QualType{}*/) {
+  if (CastTy.isNull())
 return V;
 
-  // FIXME: Move this check to the most appropriate evalCastKind/evalCastSubKind
-  // function.
-  // For const casts, casts to void, just propagate the value.
-  if (!CastTy->isVariableArrayType() && !OriginalTy->isVariableArrayType())
-if (shouldBeModeledWithNoOp(Context, Context.getPointerType(CastTy),
-

[PATCH] D95799: [analyzer] Symbolicate float values with integral casting

2021-02-04 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 321585.
ASDenysPetrov added a comment.

Updated. Moved comments as well.


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

https://reviews.llvm.org/D95799

Files:
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/lib/StaticAnalyzer/Core/Store.cpp
  clang/test/Analysis/svalbuilder-float-cast.c


Index: clang/test/Analysis/svalbuilder-float-cast.c
===
--- clang/test/Analysis/svalbuilder-float-cast.c
+++ clang/test/Analysis/svalbuilder-float-cast.c
@@ -4,17 +4,23 @@
 
 void SymbolCast_of_float_type_aux(int *p) {
   *p += 0;
-  // FIXME: Ideally, all unknown values should be symbolicated.
-  clang_analyzer_denote(*p, "$x"); // expected-warning{{Not a symbol}}
+  clang_analyzer_denote(*p, "$x");
 
   *p += 1;
-  // This should NOT be (float)$x + 1. Symbol $x was never casted to float.
-  // FIXME: Ideally, this should be $x + 1.
-  clang_analyzer_express(*p); // expected-warning{{Not a symbol}}
+  // expected-warning@+3{{(float)$x + 1}}
+  // expected-warning@+2{{(double)$x + 1}}
+  // expected-warning@+1{{(long double)$x + 1}}
+  clang_analyzer_express(*p);
 }
 
 void SymbolCast_of_float_type() {
-  extern float x;
+  extern float x1;
+  extern double x2;
+  extern long double x3;
+
   void (*f)() = SymbolCast_of_float_type_aux;
-  f();
+
+  f();
+  f();
+  f();
 }
Index: clang/lib/StaticAnalyzer/Core/Store.cpp
===
--- clang/lib/StaticAnalyzer/Core/Store.cpp
+++ clang/lib/StaticAnalyzer/Core/Store.cpp
@@ -407,17 +407,6 @@
   if (castTy.isNull() || V.isUnknownOrUndef())
 return V;
 
-  // The dispatchCast() call below would convert the int into a float.
-  // What we want, however, is a bit-by-bit reinterpretation of the int
-  // as a float, which usually yields nothing garbage. For now skip casts
-  // from ints to floats.
-  // TODO: What other combinations of types are affected?
-  if (castTy->isFloatingType()) {
-SymbolRef Sym = V.getAsSymbol();
-if (Sym && !Sym->getType()->isFloatingType())
-  return UnknownVal();
-  }
-
   // When retrieving symbolic pointer and expecting a non-void pointer,
   // wrap them into element regions of the expected type if necessary.
   // SValBuilder::dispatchCast() doesn't do that, but it is necessary to
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -501,8 +501,13 @@
   if (getContext().getTypeSize(castTy) >= getContext().getTypeSize(originalTy))
 return evalCast(val, castTy, originalTy);
 
+  // The code call below would convert the int into a float.
+  // What we want, however, is a bit-by-bit reinterpretation of the int
+  // as a float, which usually yields nothing garbage.
+  // TODO: What other combinations of types are affected?
+  // Let evalCast handle non symbolic expressions and float symbols.
   SymbolRef se = val.getAsSymbol();
-  if (!se) // Let evalCast handle non symbolic expressions.
+  if (!se || se->getType()->isFloatingType())
 return evalCast(val, castTy, originalTy);
 
   // Find the maximum value of the target type.


Index: clang/test/Analysis/svalbuilder-float-cast.c
===
--- clang/test/Analysis/svalbuilder-float-cast.c
+++ clang/test/Analysis/svalbuilder-float-cast.c
@@ -4,17 +4,23 @@
 
 void SymbolCast_of_float_type_aux(int *p) {
   *p += 0;
-  // FIXME: Ideally, all unknown values should be symbolicated.
-  clang_analyzer_denote(*p, "$x"); // expected-warning{{Not a symbol}}
+  clang_analyzer_denote(*p, "$x");
 
   *p += 1;
-  // This should NOT be (float)$x + 1. Symbol $x was never casted to float.
-  // FIXME: Ideally, this should be $x + 1.
-  clang_analyzer_express(*p); // expected-warning{{Not a symbol}}
+  // expected-warning@+3{{(float)$x + 1}}
+  // expected-warning@+2{{(double)$x + 1}}
+  // expected-warning@+1{{(long double)$x + 1}}
+  clang_analyzer_express(*p);
 }
 
 void SymbolCast_of_float_type() {
-  extern float x;
+  extern float x1;
+  extern double x2;
+  extern long double x3;
+
   void (*f)() = SymbolCast_of_float_type_aux;
-  f();
+
+  f();
+  f();
+  f();
 }
Index: clang/lib/StaticAnalyzer/Core/Store.cpp
===
--- clang/lib/StaticAnalyzer/Core/Store.cpp
+++ clang/lib/StaticAnalyzer/Core/Store.cpp
@@ -407,17 +407,6 @@
   if (castTy.isNull() || V.isUnknownOrUndef())
 return V;
 
-  // The dispatchCast() call below would convert the int into a float.
-  // What we want, however, is a bit-by-bit reinterpretation of the int
-  // as a float, which usually yields nothing garbage. For now skip casts
-  // from ints to floats.
-  // TODO: What other combinations of types are affected?
-  if 

[PATCH] D96082: [clang-tidy] Add 'readability-useless-return-value' check

2021-02-04 Thread Lukas Hänel via Phabricator via cfe-commits
LukasHanel updated this revision to Diff 321580.
LukasHanel edited projects, added clang-tools-extra; removed clang.
LukasHanel added a comment.
Herald added a project: clang.

Add the real changes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96082

Files:
  clang-tools-extra/clang-tidy/readability/CMakeLists.txt
  clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
  clang-tools-extra/clang-tidy/readability/UselessReturnValueCheck.cpp
  clang-tools-extra/clang-tidy/readability/UselessReturnValueCheck.h
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/readability-useless-return-value.rst
  clang-tools-extra/test/clang-tidy/checkers/readability-useless-return-value.c
  
clang-tools-extra/test/clang-tidy/checkers/readability-useless-return-value.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-useless-return-value.h

Index: clang-tools-extra/test/clang-tidy/checkers/readability-useless-return-value.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-useless-return-value.h
@@ -0,0 +1,3 @@
+int f11(void);
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: function 'f11' returns always the same value [readability-useless-return-value]
+// CHECK-FIXES: {{^}}void f11(void);{{$}}
Index: clang-tools-extra/test/clang-tidy/checkers/readability-useless-return-value.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-useless-return-value.cpp
@@ -0,0 +1,32 @@
+// RUN: %check_clang_tidy %s readability-useless-return-value %t
+
+int f() {
+  return 0;
+}
+// CHECK-MESSAGES: :[[@LINE-3]]:5: warning: function 'f' returns always the same value [readability-useless-return-value]
+// CHECK-MESSAGES: :[[@LINE-3]]:5: warning: returns 0 here [readability-useless-return-value]
+
+// CHECK-FIXES: {{^}}void f() {{{$}}
+// CHECK-FIXES: {{^}}return;{{$}}
+
+struct Foo {
+  Foo(int i);
+  Foo =(int &);
+};
+Foo tie(int i) {
+  return Foo(i);
+}
+
+int demangleUnsigned() {
+  int Number = 0;
+  tie(Number) = 1;
+  return Number;
+}
+
+class Foo1 {
+  virtual unsigned g(void) const;
+};
+
+unsigned Foo1::g(void) const {
+  return 0;
+}
Index: clang-tools-extra/test/clang-tidy/checkers/readability-useless-return-value.c
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-useless-return-value.c
@@ -0,0 +1,247 @@
+// RUN: %check_clang_tidy %s readability-useless-return-value %t
+
+int f() {
+  return 0;
+}
+// CHECK-MESSAGES: :[[@LINE-3]]:5: warning: function 'f' returns always the same value [readability-useless-return-value]
+// CHECK-MESSAGES: :[[@LINE-3]]:3: warning: returns 0 here [readability-useless-return-value]
+
+// CHECK-FIXES: {{^}}void f() {{{$}}
+// CHECK-FIXES: {{^}}  return;{{$}}
+
+unsigned int f2() {
+  return 0U;
+}
+// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: function 'f2' returns always the same value [readability-useless-return-value]
+// CHECK-MESSAGES: :[[@LINE-3]]:3: warning: returns 0 here [readability-useless-return-value]
+
+// CHECK-FIXES: {{^}}void f2() {{{$}}
+// CHECK-FIXES: {{^}}  return;{{$}}
+
+typedef unsigned int mytype_t;
+mytype_t f3() {
+  return 0U;
+}
+// CHECK-MESSAGES: :[[@LINE-3]]:10: warning: function 'f3' returns always the same value [readability-useless-return-value]
+// CHECK-MESSAGES: :[[@LINE-3]]:3: warning: returns 0 here [readability-useless-return-value]
+
+// CHECK-FIXES: {{^}}void f3() {{{$}}
+// CHECK-FIXES: {{^}}  return;{{$}}
+
+const int f4() {
+  return 0;
+}
+// CHECK-MESSAGES: :[[@LINE-3]]:11: warning: function 'f4' returns always the same value [readability-useless-return-value]
+// CHECK-MESSAGES: :[[@LINE-3]]:3: warning: returns 0 here [readability-useless-return-value]
+
+// CHECK-FIXES: {{^}}const void f4() {{{$}}
+// CHECK-FIXES: {{^}}  return;{{$}}
+
+static int f5() {
+  return 0;
+}
+// CHECK-MESSAGES: :[[@LINE-3]]:12: warning: function 'f5' returns always the same value [readability-useless-return-value]
+// CHECK-MESSAGES: :[[@LINE-3]]:3: warning: returns 0 here [readability-useless-return-value]
+
+// CHECK-FIXES: {{^}}static void f5() {{{$}}
+// CHECK-FIXES: {{^}}  return;{{$}}
+
+#define EXIT_SUCCESS 0
+
+int f6() {
+  return EXIT_SUCCESS; //EXIT_SUCCESS
+}
+// CHECK-MESSAGES: :[[@LINE-3]]:5: warning: function 'f6' returns always the same value [readability-useless-return-value]
+// CHECK-MESSAGES: :[[@LINE-3]]:3: warning: returns 0 here [readability-useless-return-value]
+
+// CHECK-FIXES: {{^}}void f6() {{{$}}
+// CHECK-FIXES: {{^}}  return; //EXIT_SUCCESS{{$}}
+
+#define NULL 0
+
+int f7() {
+  return NULL; //NULL
+}
+// CHECK-MESSAGES: :[[@LINE-3]]:5: warning: function 'f7' returns always the same value 

[PATCH] D96082: [clang-tidy] Add 'readability-useless-return-value' check

2021-02-04 Thread Lukas Hänel via Phabricator via cfe-commits
LukasHanel created this revision.
Herald added subscribers: nullptr.cpp, xazax.hun, mgorny.
LukasHanel requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96082

Files:
  clang-tools-extra/clang-tidy/readability/CMakeLists.txt
  clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
  clang-tools-extra/clang-tidy/readability/UselessReturnValueCheck.cpp
  clang-tools-extra/clang-tidy/readability/UselessReturnValueCheck.h
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/readability-useless-return-value.rst
  clang-tools-extra/test/clang-tidy/checkers/readability-useless-return-value.c
  
clang-tools-extra/test/clang-tidy/checkers/readability-useless-return-value.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-useless-return-value.h

Index: clang-tools-extra/test/clang-tidy/checkers/readability-useless-return-value.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-useless-return-value.h
@@ -0,0 +1,3 @@
+int f11(void);
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: function 'f11' returns always the same value [readability-useless-return-value]
+// CHECK-FIXES: {{^}}void f11(void);{{$}}
Index: clang-tools-extra/test/clang-tidy/checkers/readability-useless-return-value.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-useless-return-value.cpp
@@ -0,0 +1,32 @@
+// RUN: %check_clang_tidy %s readability-useless-return-value %t
+
+int f() {
+  return 0;
+}
+// CHECK-MESSAGES: :[[@LINE-3]]:5: warning: function 'f' returns always the same value [readability-useless-return-value]
+// CHECK-MESSAGES: :[[@LINE-3]]:5: warning: returns 0 here [readability-useless-return-value]
+
+// CHECK-FIXES: {{^}}void f() {{{$}}
+// CHECK-FIXES: {{^}}return;{{$}}
+
+struct Foo {
+  Foo(int i);
+  Foo =(int &);
+};
+Foo tie(int i) {
+  return Foo(i);
+}
+
+int demangleUnsigned() {
+  int Number = 0;
+  tie(Number) = 1;
+  return Number;
+}
+
+class Foo1 {
+  virtual unsigned g(void) const;
+};
+
+unsigned Foo1::g(void) const {
+  return 0;
+}
Index: clang-tools-extra/test/clang-tidy/checkers/readability-useless-return-value.c
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-useless-return-value.c
@@ -0,0 +1,247 @@
+// RUN: %check_clang_tidy %s readability-useless-return-value %t
+
+int f() {
+  return 0;
+}
+// CHECK-MESSAGES: :[[@LINE-3]]:5: warning: function 'f' returns always the same value [readability-useless-return-value]
+// CHECK-MESSAGES: :[[@LINE-3]]:3: warning: returns 0 here [readability-useless-return-value]
+
+// CHECK-FIXES: {{^}}void f() {{{$}}
+// CHECK-FIXES: {{^}}  return;{{$}}
+
+unsigned int f2() {
+  return 0U;
+}
+// CHECK-MESSAGES: :[[@LINE-3]]:14: warning: function 'f2' returns always the same value [readability-useless-return-value]
+// CHECK-MESSAGES: :[[@LINE-3]]:3: warning: returns 0 here [readability-useless-return-value]
+
+// CHECK-FIXES: {{^}}void f2() {{{$}}
+// CHECK-FIXES: {{^}}  return;{{$}}
+
+typedef unsigned int mytype_t;
+mytype_t f3() {
+  return 0U;
+}
+// CHECK-MESSAGES: :[[@LINE-3]]:10: warning: function 'f3' returns always the same value [readability-useless-return-value]
+// CHECK-MESSAGES: :[[@LINE-3]]:3: warning: returns 0 here [readability-useless-return-value]
+
+// CHECK-FIXES: {{^}}void f3() {{{$}}
+// CHECK-FIXES: {{^}}  return;{{$}}
+
+const int f4() {
+  return 0;
+}
+// CHECK-MESSAGES: :[[@LINE-3]]:11: warning: function 'f4' returns always the same value [readability-useless-return-value]
+// CHECK-MESSAGES: :[[@LINE-3]]:3: warning: returns 0 here [readability-useless-return-value]
+
+// CHECK-FIXES: {{^}}const void f4() {{{$}}
+// CHECK-FIXES: {{^}}  return;{{$}}
+
+static int f5() {
+  return 0;
+}
+// CHECK-MESSAGES: :[[@LINE-3]]:12: warning: function 'f5' returns always the same value [readability-useless-return-value]
+// CHECK-MESSAGES: :[[@LINE-3]]:3: warning: returns 0 here [readability-useless-return-value]
+
+// CHECK-FIXES: {{^}}static void f5() {{{$}}
+// CHECK-FIXES: {{^}}  return;{{$}}
+
+#define EXIT_SUCCESS 0
+
+int f6() {
+  return EXIT_SUCCESS; //EXIT_SUCCESS
+}
+// CHECK-MESSAGES: :[[@LINE-3]]:5: warning: function 'f6' returns always the same value [readability-useless-return-value]
+// CHECK-MESSAGES: :[[@LINE-3]]:3: warning: returns 0 here [readability-useless-return-value]
+
+// CHECK-FIXES: {{^}}void f6() {{{$}}
+// CHECK-FIXES: {{^}}  return; //EXIT_SUCCESS{{$}}
+
+#define NULL 0
+
+int f7() {
+  return NULL; //NULL
+}
+// CHECK-MESSAGES: :[[@LINE-3]]:5: warning: function 'f7' returns always the same value [readability-useless-return-value]
+// CHECK-MESSAGES: :[[@LINE-3]]:3: warning: returns 

[PATCH] D95840: [CUDA][HIP] Fix checking dependent initalizer

2021-02-04 Thread Yaxun Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
yaxunl marked 2 inline comments as done.
Closed by commit rGe355110040d1: [CUDA][HIP] Fix checking dependent initalizer 
(authored by yaxunl).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D95840?vs=320642=321577#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95840

Files:
  clang/lib/Sema/SemaCUDA.cpp
  clang/test/SemaCUDA/dependent-device-var.cu


Index: clang/test/SemaCUDA/dependent-device-var.cu
===
--- /dev/null
+++ clang/test/SemaCUDA/dependent-device-var.cu
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -fsyntax-only -verify=host,com -x hip %s
+// RUN: %clang_cc1 -fsyntax-only -fcuda-is-device -verify=dev,com -x hip %s
+
+#include "Inputs/cuda.h"
+
+template
+__device__ int fun1(T x) {
+  // Check type-dependent constant is allowed in initializer.
+  static __device__ int a = sizeof(x);
+  static __device__ int b = x;
+  // com-error@-1 {{dynamic initialization is not supported for __device__, 
__constant__, __shared__, and __managed__ variables}}
+  return  a + b;
+}
+
+__device__ int fun1_caller() {
+  return fun1(1);
+  // com-note@-1 {{in instantiation of function template specialization 
'fun1' requested here}}
+}
Index: clang/lib/Sema/SemaCUDA.cpp
===
--- clang/lib/Sema/SemaCUDA.cpp
+++ clang/lib/Sema/SemaCUDA.cpp
@@ -530,9 +530,12 @@
 if (!AllowedInit &&
 (VD->hasAttr() || VD->hasAttr())) {
   auto *Init = VD->getInit();
+  // isConstantInitializer cannot be called with dependent value, therefore
+  // we skip checking dependent value here. This is OK since
+  // checkAllowedCUDAInitializer is called again when the template is
+  // instantiated.
   AllowedInit =
-  ((VD->getType()->isDependentType() || Init->isValueDependent()) &&
-   VD->isConstexpr()) ||
+  VD->getType()->isDependentType() || Init->isValueDependent() ||
   Init->isConstantInitializer(Context,
   VD->getType()->isReferenceType());
 }


Index: clang/test/SemaCUDA/dependent-device-var.cu
===
--- /dev/null
+++ clang/test/SemaCUDA/dependent-device-var.cu
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -fsyntax-only -verify=host,com -x hip %s
+// RUN: %clang_cc1 -fsyntax-only -fcuda-is-device -verify=dev,com -x hip %s
+
+#include "Inputs/cuda.h"
+
+template
+__device__ int fun1(T x) {
+  // Check type-dependent constant is allowed in initializer.
+  static __device__ int a = sizeof(x);
+  static __device__ int b = x;
+  // com-error@-1 {{dynamic initialization is not supported for __device__, __constant__, __shared__, and __managed__ variables}}
+  return  a + b;
+}
+
+__device__ int fun1_caller() {
+  return fun1(1);
+  // com-note@-1 {{in instantiation of function template specialization 'fun1' requested here}}
+}
Index: clang/lib/Sema/SemaCUDA.cpp
===
--- clang/lib/Sema/SemaCUDA.cpp
+++ clang/lib/Sema/SemaCUDA.cpp
@@ -530,9 +530,12 @@
 if (!AllowedInit &&
 (VD->hasAttr() || VD->hasAttr())) {
   auto *Init = VD->getInit();
+  // isConstantInitializer cannot be called with dependent value, therefore
+  // we skip checking dependent value here. This is OK since
+  // checkAllowedCUDAInitializer is called again when the template is
+  // instantiated.
   AllowedInit =
-  ((VD->getType()->isDependentType() || Init->isValueDependent()) &&
-   VD->isConstexpr()) ||
+  VD->getType()->isDependentType() || Init->isValueDependent() ||
   Init->isConstantInitializer(Context,
   VD->getType()->isReferenceType());
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] e355110 - [CUDA][HIP] Fix checking dependent initalizer

2021-02-04 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2021-02-04T18:04:54-05:00
New Revision: e355110040d17dcbf0fcfcba386c4d96fe6fe7ec

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

LOG: [CUDA][HIP] Fix checking dependent initalizer

Defer constant checking of dependent initializer to template instantiation
since it cannot be done for dependent values.

Reviewed by: Artem Belevich

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

Added: 
clang/test/SemaCUDA/dependent-device-var.cu

Modified: 
clang/lib/Sema/SemaCUDA.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaCUDA.cpp b/clang/lib/Sema/SemaCUDA.cpp
index ee91eb4c5deb..b907374b466f 100644
--- a/clang/lib/Sema/SemaCUDA.cpp
+++ b/clang/lib/Sema/SemaCUDA.cpp
@@ -530,9 +530,12 @@ void Sema::checkAllowedCUDAInitializer(VarDecl *VD) {
 if (!AllowedInit &&
 (VD->hasAttr() || VD->hasAttr())) {
   auto *Init = VD->getInit();
+  // isConstantInitializer cannot be called with dependent value, therefore
+  // we skip checking dependent value here. This is OK since
+  // checkAllowedCUDAInitializer is called again when the template is
+  // instantiated.
   AllowedInit =
-  ((VD->getType()->isDependentType() || Init->isValueDependent()) &&
-   VD->isConstexpr()) ||
+  VD->getType()->isDependentType() || Init->isValueDependent() ||
   Init->isConstantInitializer(Context,
   VD->getType()->isReferenceType());
 }

diff  --git a/clang/test/SemaCUDA/dependent-device-var.cu 
b/clang/test/SemaCUDA/dependent-device-var.cu
new file mode 100644
index ..41139c8e64c1
--- /dev/null
+++ b/clang/test/SemaCUDA/dependent-device-var.cu
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -fsyntax-only -verify=host,com -x hip %s
+// RUN: %clang_cc1 -fsyntax-only -fcuda-is-device -verify=dev,com -x hip %s
+
+#include "Inputs/cuda.h"
+
+template
+__device__ int fun1(T x) {
+  // Check type-dependent constant is allowed in initializer.
+  static __device__ int a = sizeof(x);
+  static __device__ int b = x;
+  // com-error@-1 {{dynamic initialization is not supported for __device__, 
__constant__, __shared__, and __managed__ variables}}
+  return  a + b;
+}
+
+__device__ int fun1_caller() {
+  return fun1(1);
+  // com-note@-1 {{in instantiation of function template specialization 
'fun1' requested here}}
+}



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


[PATCH] D95691: Implement P2173 for attributes on lambdas

2021-02-04 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticGroups.td:269
+def CXXPre2BCompatPedantic :
+  DiagGroup<"c++98-c++11-c++14-c++17-c++20-compat-pedantic", [CXXPre2BCompat]>;
 

rjmccall wrote:
> Quuxplusone wrote:
> > aaron.ballman wrote:
> > > rjmccall wrote:
> > > > Uh, I think we're a couple standard releases past the point at which we 
> > > > should have reconsidered this schema.  I guess the problem is that we 
> > > > can't say `-Wpre-c++23-compat` without jumping the gun.  Is there a 
> > > > problem with `-Wc++20-compat` and then having the earlier warning 
> > > > groups imply the later ones?  That seems to be what we do with 
> > > > `-Wc++98-compat`; did we abandon that approach intentionally?
> > > @rsmith may have more background here. I was following the pattern 
> > > already in the file, but I tend to agree that this pattern is not leading 
> > > us somewhere good. FWIW, I ran into a similar situation with this on the 
> > > C side of things in D95396, so we should probably be consistent there too.
> > My understanding is that the //command-line user// is expected to pass
> > - `clang++ -std=c++20 -Wc++11-compat` to indicate "I want //actually// to 
> > compile in C++20 mode, but give me warnings about anything that would 
> > prevent compiling in C++11 mode"
> > - `clang++ -std=c++17 -Wc++14-compat` to indicate "I want //actually// to 
> > compile in C++17 mode, but give me warnings about anything that would 
> > prevent compiling in C++14 mode"
> > - `clang++ -std=c++14 -Wc++20-compat` to indicate "I want //actually// to 
> > compile in C++14 mode, but give me warnings about anything that would 
> > prevent compiling in C++20 mode" — EXCEPT that I think this is not 
> > supported. My impression is that forward-compatibility warnings are 
> > generally just rolled into `-Wall` and not handled separately beyond that?
> > 
> > I don't think any human user is expected to pass 
> > `-Wc++98-c++11-c++14-c++17-c++20-compat` by hand; it's just an internal 
> > name for a particular subset of `-Wc++98-compat`.
> > 
> > IOW, we could choose a new naming scheme for it, but that would be a purely 
> > internal change that won't affect how command-line users interact with 
> > Clang at all (for better and for worse).
> Diagnostic groups can both directly contain diagnostics and imply other 
> diagnostic groups, so I don't think there's any reason to make a dedicated 
> group just to contain the new diagnostics in e.g. `-Wc++14-compat` except to 
> allow someone turn on those warnings separately.  And it does show up to 
> users as the warning group under `-fdiagnostics-show-option` (which is the 
> default).
@Quuxplusone's comment describes the intent. `-std=c++20 -Wc++14-compat` should 
give a more or less complete list of reasons why the code would not compile in 
C++14 (at least on the language side; we don't check for stdlib compatibility). 
The other direction -- `-std=c++11 -Wc++14-compat` -- is more of a best-effort 
check for things that we've seen cause problems in practice and can easily 
detect. (As a consequence, I don't think there's any subset/superset relation 
between `-Wc++X-compat` and `-Wc++Y-compat`.)

I'd be happy to see these groups renamed to `-Wpre-c++20-compat` or similar. 
Warning group synonyms are relatively cheap, so I wouldn't be worried about 
adding a `-Wpre-c++2b-compat` now and renaming it to `-Wpre-c++23-compat` flag 
later.

(As an aside, it'd be handy if there were some way to mark a `DiagGroup` as 
existing only for grouping purposes, so that we could avoid exposing a `-W` 
flag for cases where groups are added for internal reasons.)



Comment at: clang/include/clang/Basic/DiagnosticGroups.td:1023
+// earlier C++ versions.
+def CXX2B : DiagGroup<"c++2b-extensions">;
+

I think we generally use a lowercase letter here, so `CXX2b`. (For example, see 
the `C2x` group.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95691

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


[PATCH] D96080: format

2021-02-04 Thread Lukas Hänel via Phabricator via cfe-commits
LukasHanel created this revision.
Herald added a subscriber: nullptr.cpp.
LukasHanel requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96080

Files:
  clang-tools-extra/clang-tidy/readability/UselessReturnValueCheck.cpp


Index: clang-tools-extra/clang-tidy/readability/UselessReturnValueCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/UselessReturnValueCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/UselessReturnValueCheck.cpp
@@ -30,14 +30,13 @@
   forEachDescendant(
   returnStmt(hasReturnValue(Int0Var)).bind("return-to-void")),
   unless(hasDescendant(returnStmt(unless(hasReturnValue(Int0Var),
-  unless(hasDescendant(
-  binaryOperator(isAssignmentOperator(),
- hasLHS(declRefExpr(
- to(varDecl(equalsBoundNode("retvar",
-  unless(hasDescendant(
-  cxxOperatorCallExpr(isAssignmentOperator(),
- hasLHS(hasDescendant(declRefExpr(
- to(varDecl(equalsBoundNode("retvar"),
+  unless(hasDescendant(binaryOperator(
+  isAssignmentOperator(),
+  hasLHS(declRefExpr(to(varDecl(equalsBoundNode("retvar",
+  unless(hasDescendant(cxxOperatorCallExpr(
+  isAssignmentOperator(),
+  hasLHS(hasDescendant(
+  declRefExpr(to(varDecl(equalsBoundNode("retvar"),
   unless(hasDescendant(
   unaryOperator(hasAnyOperatorName("++", "--", "&"),
 hasUnaryOperand(ignoringImplicit(declRefExpr(


Index: clang-tools-extra/clang-tidy/readability/UselessReturnValueCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/UselessReturnValueCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/UselessReturnValueCheck.cpp
@@ -30,14 +30,13 @@
   forEachDescendant(
   returnStmt(hasReturnValue(Int0Var)).bind("return-to-void")),
   unless(hasDescendant(returnStmt(unless(hasReturnValue(Int0Var),
-  unless(hasDescendant(
-  binaryOperator(isAssignmentOperator(),
- hasLHS(declRefExpr(
- to(varDecl(equalsBoundNode("retvar",
-  unless(hasDescendant(
-  cxxOperatorCallExpr(isAssignmentOperator(),
- hasLHS(hasDescendant(declRefExpr(
- to(varDecl(equalsBoundNode("retvar"),
+  unless(hasDescendant(binaryOperator(
+  isAssignmentOperator(),
+  hasLHS(declRefExpr(to(varDecl(equalsBoundNode("retvar",
+  unless(hasDescendant(cxxOperatorCallExpr(
+  isAssignmentOperator(),
+  hasLHS(hasDescendant(
+  declRefExpr(to(varDecl(equalsBoundNode("retvar"),
   unless(hasDescendant(
   unaryOperator(hasAnyOperatorName("++", "--", "&"),
 hasUnaryOperand(ignoringImplicit(declRefExpr(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D96070: [clang] [driver] Enable static linking to libc++

2021-02-04 Thread Tom Stellard via Phabricator via cfe-commits
tstellar added a comment.

The goal here is for distributions to be able to build libc++ one way and then 
have it work with clang without requiring that users add additional linker 
flags besides -static or -stdlib=libc++.  Is there a combination of CMake 
arguments we can use when building libc++ to make all static and shared linking 
with libc++ work out of the box?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96070

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


[PATCH] D95745: Support unwinding from inline assembly

2021-02-04 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

Basically, this seems totally reasonable and I think this is the right 
direction.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95745

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


[PATCH] D96070: [clang] [driver] Enable static linking to libc++

2021-02-04 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay requested changes to this revision.
MaskRay added a comment.
This revision now requires changes to proceed.

It is difficult for clang driver to make the decision because libc++ has 
multiple C++ ABI implementations as @mstorsjo said.

Persoanlly I use:

`clang++ -stdlib=libc++ -static-libstdc++ -nostdlib++ a.cc 
-Wl,--push-state,-Bstatic -lc++ -lc++abi -Wl,--pop-state -pthread`

This is still a bit inferior because there is a duplicate -lc++ passed by the 
driver.

Dynamically link against libc++.so (which depends on libc++abi.so) 
(additionally specify -pthread if threads are used):
`clang++ -stdlib=libc++ -nostdlib++ a.cc -lc++ -lc++abi` (clang -stdlib=libc++ 
a.cc -lc++ -lc++abi does not pass -lm to the linker.)
Omitting `-lc++abi` most works, but can fail if your program reference some 
definitions in ` ` directly and you are using gold or LLD.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96070

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


[PATCH] D96070: [clang] [driver] Enable static linking to libc++

2021-02-04 Thread Joerg Sonnenberger via Phabricator via cfe-commits
joerg added a comment.

The NetBSD part is most definitely not acceptable.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96070

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


[PATCH] D96027: [clangd] Trace queue state for each TUScheduler action.

2021-02-04 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/TUScheduler.cpp:1054
 Requests.push_back({std::move(Task), std::string(Name), 
steady_clock::now(),
-std::move(Ctx), Update, Invalidation,
-std::move(Invalidate)});
+std::move(Ctx), std::move(QueueCtx), Update,
+Invalidation, std::move(Invalidate)});

kadircet wrote:
> what if we just pushed the span here and kept it alive in the queue? it is 
> move-able at the moment.
> 
> our tracing contract seem to be saying beginSpan/endSpan calls would always 
> form a proper stack, i am not sure about its importance to the jsontracer, 
> but I don't think rest of our tracers cares (and i think it would be nice for 
> that trace to actually span the whole time in queue).
> what if we just pushed the span here and kept it alive in the queue?
Mechanically it's a little more complicated than that, but I get what you're 
saying - unfortunately it doesn't quite work.

> it is move-able at the moment.
(in fact not: it has a WithContext member whose move operators are deleted)

> our tracing contract seem to be saying beginSpan/endSpan calls would always 
> form a proper stack
Yes - this is in fact documented as the *only* point of endSpan - it marks the 
strictly-stacking lifetimes of stack-allocated trace::Spans objects themselves. 
Tracers that don't need this strict stacking are supposed to watch for the 
destruction of the context frames created by beginSpan instead. This extends 
the span over context-propagation, at the cost of no longer strictly stacking.

> i am not sure about its importance to the jsontracer
The chrome trace viewer (which jsontracer targets) really does require strict 
stacking. I'm not 100% sure, but I think the behavior was just to silently 
discard events that don't nest properly.

> I don't think rest of our tracers cares (and i think it would be nice for 
> that trace to actually span the whole time in queue).
Right, so our private out-of-tree tracer follows request/context timelines 
rather than thread ones, and doesn't require strict nesting. It completely 
ignores endSpan(), and ends events when the context gets destroyed instead. 
That's why we bundle up the QueueCtx into the request and then destroy it as 
soon as we dequeue - it makes that trace actually span the whole time in queue 
:-)

(Happy to chat more about this or add some comments/diagrams/something if we 
should make this more clear)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96027

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


[clang] 0211877 - [HIP] Add __managed__ macro to header

2021-02-04 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2021-02-04T16:22:42-05:00
New Revision: 0211877a0754c06e3aeaba690a1c860c6edf6288

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

LOG: [HIP] Add __managed__ macro to header

Added: 


Modified: 
clang/lib/Headers/__clang_hip_runtime_wrapper.h

Removed: 




diff  --git a/clang/lib/Headers/__clang_hip_runtime_wrapper.h 
b/clang/lib/Headers/__clang_hip_runtime_wrapper.h
index 81a16a265ae8..4fd8f23d49f3 100644
--- a/clang/lib/Headers/__clang_hip_runtime_wrapper.h
+++ b/clang/lib/Headers/__clang_hip_runtime_wrapper.h
@@ -27,6 +27,7 @@
 #define __global__ __attribute__((global))
 #define __shared__ __attribute__((shared))
 #define __constant__ __attribute__((constant))
+#define __managed__ __attribute__((managed))
 
 #if !defined(__cplusplus) || __cplusplus < 201103L
   #define nullptr NULL;



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


[PATCH] D96058: [CodeComplete] Guess type for designated initializers

2021-02-04 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGeb4ab3358cd4: [CodeComplete] Guess type for designated 
initializers (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D96058?vs=321495=321556#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96058

Files:
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseInit.cpp
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/CodeCompletion/desig-init.cpp

Index: clang/test/CodeCompletion/desig-init.cpp
===
--- clang/test/CodeCompletion/desig-init.cpp
+++ clang/test/CodeCompletion/desig-init.cpp
@@ -16,8 +16,8 @@
   // CHECK-CC1-NOT: foo
   // CHECK-CC1-NOT: t
 
-  // FIXME: Handle nested designators
-  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:11:20 %s -o - | count 0
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:11:20 %s -o - | FileCheck -check-prefix=CHECK-NESTED %s
+  // CHECK-NESTED: COMPLETION: t : [#int#]t
 
   Base B = {.t = 2};
   auto z = [](Base B) {};
@@ -29,6 +29,14 @@
   // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:25:11 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC2 %s
   // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:26:13 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC2 %s
   // CHECK-CC2: COMPLETION: t : [#int#]t
+
+  Foo G1{.b = {.t = 0}};
+  Foo G2{.b{.t = 0}};
+  Foo G3{b: {.t = 0}};
+  // RUN: %clang_cc1 -code-completion-at=%s:33:17 -fsyntax-only -code-completion-patterns %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-NESTED-2 %s
+  // RUN: %clang_cc1 -code-completion-at=%s:34:14 -fsyntax-only -code-completion-patterns %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-NESTED-2 %s
+  // RUN: %clang_cc1 -code-completion-at=%s:35:15 -fsyntax-only -code-completion-patterns %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-NESTED-2 %s
+  // CHECK-NESTED-2: COMPLETION: t : [#int#]t
 }
 
 // Handle templates
@@ -41,10 +49,10 @@
 };
 void bar() {
   Test T{.x = 2};
-  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:43:17 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC3 %s
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:51:17 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC3 %s
   // CHECK-CC3: COMPLETION: x : [#T#]x
   Test X{.x = 2};
-  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:46:16 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC4 %s
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:54:16 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC4 %s
   // CHECK-CC4: COMPLETION: x : [#int#]x
   // CHECK-CC4-NEXT: COMPLETION: y : [#char#]y
 }
@@ -52,5 +60,5 @@
 template 
 void aux() {
   Test X{.x = T(2)};
-  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:54:14 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC3 %s
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:62:14 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC3 %s
 }
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -405,6 +405,16 @@
   ExpectedLoc = Tok;
 }
 
+static QualType getDesignatedType(QualType BaseType, const Designation );
+
+void PreferredTypeBuilder::enterDesignatedInitializer(SourceLocation Tok,
+  QualType BaseType,
+  const Designation ) {
+  ComputeType = nullptr;
+  Type = getDesignatedType(BaseType, D);
+  ExpectedLoc = Tok;
+}
+
 void PreferredTypeBuilder::enterFunctionArgument(
 SourceLocation Tok, llvm::function_ref ComputeType) {
   this->ComputeType = ComputeType;
@@ -4784,8 +4794,16 @@
 // in case of specializations. Since we might not have a decl for the
 // instantiation/specialization yet, e.g. dependent code.
 static RecordDecl *getAsRecordDecl(const QualType BaseType) {
-  if (auto *RD = BaseType->getAsRecordDecl())
+  if (auto *RD = BaseType->getAsRecordDecl()) {
+if (const auto *CTSD =
+llvm::dyn_cast(RD)) {
+  // Template might not be instantiated yet, fall back to primary template
+  // in such cases.
+  if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared)
+RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
+}
 return RD;
+  }
 
   if (const auto *TST = BaseType->getAs()) {
 if (const auto *TD = dyn_cast_or_null(
@@ -5754,25 +5772,39 @@
   

[clang] eb4ab33 - [CodeComplete] Guess type for designated initializers

2021-02-04 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2021-02-04T22:14:49+01:00
New Revision: eb4ab3358cd4dc834a761191b5531b38114f7b13

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

LOG: [CodeComplete] Guess type for designated initializers

This enables:
 - completion in { .x.^ }
 - completion in { .x = { .^ } }
 - type-based ranking of candidates for { .x = ^ }

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

Added: 


Modified: 
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/Sema.h
clang/lib/Parse/ParseInit.cpp
clang/lib/Sema/SemaCodeComplete.cpp
clang/test/CodeCompletion/desig-init.cpp

Removed: 




diff  --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index 61996f0d5699..f8b746446e7e 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -2018,8 +2018,11 @@ class Parser : public CodeCompletionHandler {
   }
   bool MayBeDesignationStart();
   ExprResult ParseBraceInitializer();
-  ExprResult ParseInitializerWithPotentialDesignator(
-  llvm::function_ref CodeCompleteCB);
+  struct DesignatorCompletionInfo {
+SmallVectorImpl 
+QualType PreferredBaseType;
+  };
+  ExprResult ParseInitializerWithPotentialDesignator(DesignatorCompletionInfo);
 
   
//======//
   // clang Expressions

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 2fca81d25345..ea20ada56abc 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -298,6 +298,9 @@ class PreferredTypeBuilder {
   void enterCondition(Sema , SourceLocation Tok);
   void enterReturn(Sema , SourceLocation Tok);
   void enterVariableInit(SourceLocation Tok, Decl *D);
+  /// Handles e.g. BaseType{ .D = Tok...
+  void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
+  const Designation );
   /// Computing a type for the function argument may require running
   /// overloading, so we postpone its computation until it is actually needed.
   ///

diff  --git a/clang/lib/Parse/ParseInit.cpp b/clang/lib/Parse/ParseInit.cpp
index 9ac2b2e6f79b..50e1f1eaba4d 100644
--- a/clang/lib/Parse/ParseInit.cpp
+++ b/clang/lib/Parse/ParseInit.cpp
@@ -159,7 +159,9 @@ static void CheckArrayDesignatorSyntax(Parser , 
SourceLocation Loc,
 ///
 /// \p CodeCompleteCB is called with Designation parsed so far.
 ExprResult Parser::ParseInitializerWithPotentialDesignator(
-llvm::function_ref CodeCompleteCB) {
+DesignatorCompletionInfo DesignatorCompletion) {
+  if (!getPreprocessor().isCodeCompletionEnabled())
+DesignatorCompletion.PreferredBaseType = QualType(); // skip field lookup
 
   // If this is the old-style GNU extension:
   //   designation ::= identifier ':'
@@ -183,6 +185,8 @@ ExprResult Parser::ParseInitializerWithPotentialDesignator(
 
 Designation D;
 D.AddDesignator(Designator::getField(FieldName, SourceLocation(), 
NameLoc));
+PreferredType.enterDesignatedInitializer(
+Tok.getLocation(), DesignatorCompletion.PreferredBaseType, D);
 return Actions.ActOnDesignatedInitializer(D, ColonLoc, true,
   ParseInitializer());
   }
@@ -199,7 +203,8 @@ ExprResult Parser::ParseInitializerWithPotentialDesignator(
   SourceLocation DotLoc = ConsumeToken();
 
   if (Tok.is(tok::code_completion)) {
-CodeCompleteCB(Desig);
+Actions.CodeCompleteDesignator(DesignatorCompletion.PreferredBaseType,
+   DesignatorCompletion.InitExprs, Desig);
 cutOffParsing();
 return ExprError();
   }
@@ -388,6 +393,8 @@ ExprResult Parser::ParseInitializerWithPotentialDesignator(
   // Handle a normal designator sequence end, which is an equal.
   if (Tok.is(tok::equal)) {
 SourceLocation EqualLoc = ConsumeToken();
+PreferredType.enterDesignatedInitializer(
+Tok.getLocation(), DesignatorCompletion.PreferredBaseType, Desig);
 return Actions.ActOnDesignatedInitializer(Desig, EqualLoc, false,
   ParseInitializer());
   }
@@ -396,6 +403,8 @@ ExprResult Parser::ParseInitializerWithPotentialDesignator(
   // direct-list-initialization of the aggregate element. We allow this as an
   // extension from C++11 onwards (when direct-list-initialization was added).
   if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
+PreferredType.enterDesignatedInitializer(
+Tok.getLocation(), DesignatorCompletion.PreferredBaseType, Desig);
 return Actions.ActOnDesignatedInitializer(Desig, SourceLocation(), false,
   ParseBraceInitializer());
   }
@@ 

[PATCH] D95948: Stop traping on sNaN in __builtin_isnan

2021-02-04 Thread Thomas Preud'homme via Phabricator via cfe-commits
thopre added inline comments.



Comment at: clang/test/CodeGen/aarch64-strictfp-builtins.c:1
+// RUN: %clang_cc1 %s -emit-llvm -ffp-exception-behavior=maytrap 
-fexperimental-strict-floating-point -o - -triple arm64-none-linux-gnu | 
FileCheck %s
+

AArch64 is not StrictFP enabled so we need this option.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95948

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


[PATCH] D96058: [CodeComplete] Guess type for designated initializers

2021-02-04 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked an inline comment as done.
sammccall added inline comments.



Comment at: clang/lib/Parse/ParseInit.cpp:163
+DesignatorCompletionInfo DesignatorCompletion) {
+  if (!getPreprocessor().isCodeCompletionEnabled())
+DesignatorCompletion.PreferredBaseType = QualType(); // skip field lookup

kadircet wrote:
> it might be nice to make the whole preferredtypebuilder a no-op on 
> construction when codecompletion is disabled. but that can be an adventure 
> for another day.
Agree, this felt awkward. There's already a laziness mechanism (the 
function-arg stuff) but it doesn't quite fit for this case.



Comment at: clang/lib/Sema/SemaCodeComplete.cpp:4803
+  if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared)
+RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
+}

kadircet wrote:
> i think this means we are going to offer completion for uninstantiated 
> specializations using the primary template now (through 
> `Sema::CodeCompleteMemberReferenceExpr`), which i am not sure is possible, 
> but should be an improvement in either case.
> 
> but not having any tests (especially failing) makes me a little anxious.
I think this case is vacuous for CodeCompleteMemberExpr, like you say.

Before calling CodeCompleteMemberExpr, we call ActOnStartCXXMemberReference. If 
it's a non-dependent record type, then it calls RequireCompleteType, which will 
try to instantiate the template. If this fails, then we bail out and never 
invoke code completion.

So I think there's no change in behavior for member completion, and thus can't 
produce a test for it. The reason for moving the fallback case into this 
function is that instead of 2 callsites where 1 needed the fallback, we now 
have 3 callsites where 2 need it. So it seems less awkward to factor this way.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96058

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


[PATCH] D95948: Stop traping on sNaN in __builtin_isnan

2021-02-04 Thread Thomas Preud'homme via Phabricator via cfe-commits
thopre updated this revision to Diff 321554.
thopre added a comment.

Add AArch64 testcase and rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95948

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

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

[clang] fcb90cb - Fix miscomputation of dependence for elaborated types that are

2021-02-04 Thread Richard Smith via cfe-commits

Author: Richard Smith
Date: 2021-02-04T13:14:15-08:00
New Revision: fcb90cbd3b4ae3934bdd05d538647d37ce899962

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

LOG: Fix miscomputation of dependence for elaborated types that are
explicitly qualified as members of the current instantiation.

Despite the nested name specifier being fully-dependent in this case,
the elaborated type might only be instantiation-dependent, because the
type is a member of the current instantiation.

Added: 


Modified: 
clang/include/clang/AST/DependenceFlags.h
clang/include/clang/AST/Type.h
clang/test/SemaTemplate/instantiation-dependence.cpp

Removed: 




diff  --git a/clang/include/clang/AST/DependenceFlags.h 
b/clang/include/clang/AST/DependenceFlags.h
index ca96b65574bd..62efdb4ce6e4 100644
--- a/clang/include/clang/AST/DependenceFlags.h
+++ b/clang/include/clang/AST/DependenceFlags.h
@@ -128,6 +128,9 @@ class Dependence {
 // Type depends on a runtime value (variable-length array).
 VariablyModified = 32,
 
+// Dependence that is propagated syntactically, regardless of semantics.
+Syntactic = UnexpandedPack | Instantiation | Error,
+
 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/VariablyModified)
   };
 
@@ -165,6 +168,13 @@ class Dependence {
  translate(D, TNDependence::Dependent, Dependent) |
  translate(D, TNDependence::Error, Error)) {}
 
+  /// Extract only the syntactic portions of this type's dependence.
+  Dependence syntactic() {
+Dependence Result = *this;
+Result.V &= Syntactic;
+return Result;
+  }
+
   TypeDependence type() const {
 return translate(V, UnexpandedPack, TypeDependence::UnexpandedPack) |
translate(V, Instantiation, TypeDependence::Instantiation) |
@@ -256,6 +266,10 @@ inline TypeDependence 
toTypeDependence(TemplateArgumentDependence D) {
   return Dependence(D).type();
 }
 
+inline TypeDependence toSyntacticDependence(TypeDependence D) {
+  return Dependence(D).syntactic().type();
+}
+
 inline NestedNameSpecifierDependence
 toNestedNameSpecifierDependendence(TypeDependence D) {
   return Dependence(D).nestedNameSpecifier();

diff  --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index 319d3850346b..66ed32a9e9e5 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -5412,8 +5412,13 @@ class ElaboratedType final
   ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
  QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
   : TypeWithKeyword(Keyword, Elaborated, CanonType,
+// Any semantic dependence on the qualifier will have
+// been incorporated into NamedType. We still need to
+// track syntactic (instantiation / error / pack)
+// dependence on the qualifier.
 NamedType->getDependence() |
-(NNS ? toTypeDependence(NNS->getDependence())
+(NNS ? toSyntacticDependence(
+   toTypeDependence(NNS->getDependence()))
  : TypeDependence::None)),
 NNS(NNS), NamedType(NamedType) {
 ElaboratedTypeBits.HasOwnedTagDecl = false;

diff  --git a/clang/test/SemaTemplate/instantiation-dependence.cpp 
b/clang/test/SemaTemplate/instantiation-dependence.cpp
index 2b9a47ad25a4..ae641080bec0 100644
--- a/clang/test/SemaTemplate/instantiation-dependence.cpp
+++ b/clang/test/SemaTemplate/instantiation-dependence.cpp
@@ -80,3 +80,24 @@ namespace TypeQualifier {
   template A::type f() {} // 
expected-note {{'int' cannot be used prior to '::'}}
   int k = f(); // expected-error {{no matching}}
 }
+
+namespace MemberOfInstantiationDependentBase {
+  template struct A { template void f(int); };
+  template struct B { using X = A; };
+  template struct C1 : B {
+using X = typename C1::X;
+void f(X *p) {
+  p->f<0>(0);
+  p->template f<0>(0);
+}
+  };
+  template struct C2 : B {
+using X = typename C2::X;
+void f(X *p) {
+  p->f<0>(0);
+  p->template f<0>(0);
+}
+  };
+  void q(C1 *c) { c->f(0); }
+  void q(C2 *c) { c->f(0); }
+}



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


[clang] cd2f65b - Correct some confused diagnostic terminology

2021-02-04 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2021-02-04T15:52:07-05:00
New Revision: cd2f65b71a4239dcb5a4bcfe25da32a9ac9620cb

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

LOG: Correct some confused diagnostic terminology

Attributes accept arguments, not parameters, so we should report that
the duplicate attribute arguments don't match.

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/test/Sema/attr-min-vector-width.c
clang/test/SemaOpenCL/invalid-kernel-attrs.cl

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 61e8f7f28f1c..3ec38a2858ea 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9621,7 +9621,7 @@ def warn_duplicate_attribute_exact : Warning<
   "attribute %0 is already applied">, InGroup;
 
 def warn_duplicate_attribute : Warning<
-  "attribute %0 is already applied with 
diff erent parameters">,
+  "attribute %0 is already applied with 
diff erent arguments">,
   InGroup;
 
 def warn_sync_fetch_and_nand_semantics_change : Warning<

diff  --git a/clang/test/Sema/attr-min-vector-width.c 
b/clang/test/Sema/attr-min-vector-width.c
index 0e6f84a672f2..0ba2975d6a9f 100644
--- a/clang/test/Sema/attr-min-vector-width.c
+++ b/clang/test/Sema/attr-min-vector-width.c
@@ -5,7 +5,7 @@ void f(void) __attribute__((__min_vector_width__(i))); /* 
expected-error {{'__mi
 
 void f2(void) __attribute__((__min_vector_width__(128)));
 
-void f3(void) __attribute__((__min_vector_width__(128), 
__min_vector_width__(256))); /* expected-warning {{attribute 
'__min_vector_width__' is already applied with 
diff erent parameters}} */
+void f3(void) __attribute__((__min_vector_width__(128), 
__min_vector_width__(256))); /* expected-warning {{attribute 
'__min_vector_width__' is already applied with 
diff erent arguments}} */
 
 void f4(void) __attribute__((__min_vector_width__())); /* expected-error 
{{'__min_vector_width__' attribute takes one argument}} */
 

diff  --git a/clang/test/SemaOpenCL/invalid-kernel-attrs.cl 
b/clang/test/SemaOpenCL/invalid-kernel-attrs.cl
index daa8fa07f68d..0883379601ef 100644
--- a/clang/test/SemaOpenCL/invalid-kernel-attrs.cl
+++ b/clang/test/SemaOpenCL/invalid-kernel-attrs.cl
@@ -8,11 +8,11 @@ kernel __attribute__((vec_type_hint(void))) void kernel3() {} 
//expected-error{{
 
 kernel __attribute__((vec_type_hint(bool))) void kernel4() {} 
//expected-error{{a non-vector or non-vectorizable scalar type is an invalid 
argument to attribute 'vec_type_hint'}}
 
-kernel __attribute__((vec_type_hint(int))) 
__attribute__((vec_type_hint(float))) void kernel5() {} 
//expected-warning{{attribute 'vec_type_hint' is already applied with 
diff erent parameters}}
+kernel __attribute__((vec_type_hint(int))) 
__attribute__((vec_type_hint(float))) void kernel5() {} 
//expected-warning{{attribute 'vec_type_hint' is already applied with 
diff erent arguments}}
 
 kernel __attribute__((work_group_size_hint(8,16,32,4))) void kernel6() {} 
//expected-error{{'work_group_size_hint' attribute requires exactly 3 
arguments}}
 
-kernel __attribute__((work_group_size_hint(1,2,3))) 
__attribute__((work_group_size_hint(3,2,1))) void kernel7() {}  
//expected-warning{{attribute 'work_group_size_hint' is already applied with 
diff erent parameters}}
+kernel __attribute__((work_group_size_hint(1,2,3))) 
__attribute__((work_group_size_hint(3,2,1))) void kernel7() {}  
//expected-warning{{attribute 'work_group_size_hint' is already applied with 
diff erent arguments}}
 
 __attribute__((reqd_work_group_size(8,16,32))) void kernel8(){} // 
expected-error {{attribute 'reqd_work_group_size' can only be applied to an 
OpenCL kernel}}
 
@@ -36,7 +36,7 @@ kernel __attribute__((reqd_work_group_size(0,1,2))) void 
kernel13(){} // expecte
 
 __attribute__((intel_reqd_sub_group_size(8))) void kernel14(){} // 
expected-error {{attribute 'intel_reqd_sub_group_size' can only be applied to 
an OpenCL kernel}}
 kernel __attribute__((intel_reqd_sub_group_size(0))) void kernel15(){} // 
expected-error {{'intel_reqd_sub_group_size' attribute must be greater than 0}}
-kernel __attribute__((intel_reqd_sub_group_size(8))) 
__attribute__((intel_reqd_sub_group_size(16))) void kernel16() {}  
//expected-warning{{attribute 'intel_reqd_sub_group_size' is already applied 
with 
diff erent parameters}}
+kernel __attribute__((intel_reqd_sub_group_size(8))) 
__attribute__((intel_reqd_sub_group_size(16))) void kernel16() {}  
//expected-warning{{attribute 'intel_reqd_sub_group_size' is already applied 
with 
diff erent arguments}}
 
 __kernel __attribute__((work_group_size_hint(8,-16,32))) void neg1() {} 
//expected-error{{'work_group_size_hint' 

[PATCH] D96070: [clang] [driver] Enable static linking to libc++

2021-02-04 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

I'm not convinced that this is the right way of handling it. Libc++ can be used 
on top of a number of C++ ABI libraries (both libsupc++/libstdc++ and 
libcxxabi), and how they are linked varies with how a toolchain is assembled. 
In particular, if libcxx is built with `LIBCXX_ENABLE_STATIC_ABI_LIBRARY` 
enabled, the libcxxabi static library is merged into libc++.a, making static 
linking work just fine.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96070

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


[PATCH] D96009: [clangd] Improve name conflict detection

2021-02-04 Thread Kirill Bobyrev via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe8a2b7c91563: [clangd] Improve name conflict detection 
(authored by kbobyrev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96009

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


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1067,6 +1067,14 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(
+void func() {
+  for (int V^ar = 14, Conflict = 42;;) {
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(
 void func(int Conflict) {
   bool V^ar;
@@ -1074,6 +1082,19 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(
+void func(int V^ar) {
+  bool Conflict;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func(int V^ar, int Conflict) {
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
   int S^ameName;
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -337,9 +337,10 @@
   };
 
   // We need to get to the enclosing scope: NamedDecl's parent is typically
-  // DeclStmt, so enclosing scope would be the second order parent.
+  // DeclStmt (or FunctionProtoTypeLoc in case of function arguments), so
+  // enclosing scope would be the second order parent.
   const auto *Parent = GetSingleParent(DynTypedNode::create(RenamedDecl));
-  if (!Parent || !Parent->get())
+  if (!Parent || !(Parent->get() || Parent->get()))
 return nullptr;
   Parent = GetSingleParent(*Parent);
 
@@ -407,8 +408,21 @@
   }
   if (const auto *EnclosingWhile = Parent->get())
 return CheckCompoundStmt(EnclosingWhile->getBody(), NewName);
-  if (const auto *EnclosingFor = Parent->get())
+  if (const auto *EnclosingFor = Parent->get()) {
+// Check for conflicts with other declarations within initialization
+// statement.
+if (const auto *Result = CheckDeclStmt(
+dyn_cast_or_null(EnclosingFor->getInit()), NewName))
+  return Result;
 return CheckCompoundStmt(EnclosingFor->getBody(), NewName);
+  }
+  if (const auto *EnclosingFunction = Parent->get()) {
+// Check for conflicts with other arguments.
+for (const auto *Parameter : EnclosingFunction->parameters())
+  if (Parameter !=  && Parameter->getName() == NewName)
+return Parameter;
+return CheckCompoundStmt(EnclosingFunction->getBody(), NewName);
+  }
 
   return nullptr;
 }


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1067,6 +1067,14 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(
+void func() {
+  for (int V^ar = 14, Conflict = 42;;) {
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(
 void func(int Conflict) {
   bool V^ar;
@@ -1074,6 +1082,19 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(
+void func(int V^ar) {
+  bool Conflict;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func(int V^ar, int Conflict) {
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
   int S^ameName;
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -337,9 +337,10 @@
   };
 
   // We need to get to the enclosing scope: NamedDecl's parent is typically
-  // DeclStmt, so enclosing scope would be the second order parent.
+  // DeclStmt (or FunctionProtoTypeLoc in case of function arguments), so
+  // enclosing scope would be the second order parent.
   const auto *Parent = GetSingleParent(DynTypedNode::create(RenamedDecl));
-  if (!Parent || !Parent->get())
+  if (!Parent || !(Parent->get() || 

[clang-tools-extra] e8a2b7c - [clangd] Improve name conflict detection

2021-02-04 Thread Kirill Bobyrev via cfe-commits

Author: Kirill Bobyrev
Date: 2021-02-04T21:37:41+01:00
New Revision: e8a2b7c91563169b68d2a878c65deecc85ced466

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

LOG: [clangd] Improve name conflict detection

Follow-up on D95925: adds better detection for function arguments and also
checks for conflicts in muli-variable init statements in ForStmt.

Reviewed By: hokein

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

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/Rename.cpp 
b/clang-tools-extra/clangd/refactor/Rename.cpp
index bcce307a4362..07422a06a923 100644
--- a/clang-tools-extra/clangd/refactor/Rename.cpp
+++ b/clang-tools-extra/clangd/refactor/Rename.cpp
@@ -337,9 +337,10 @@ const NamedDecl 
*lookupSiblingWithinEnclosingScope(ASTContext ,
   };
 
   // We need to get to the enclosing scope: NamedDecl's parent is typically
-  // DeclStmt, so enclosing scope would be the second order parent.
+  // DeclStmt (or FunctionProtoTypeLoc in case of function arguments), so
+  // enclosing scope would be the second order parent.
   const auto *Parent = GetSingleParent(DynTypedNode::create(RenamedDecl));
-  if (!Parent || !Parent->get())
+  if (!Parent || !(Parent->get() || Parent->get()))
 return nullptr;
   Parent = GetSingleParent(*Parent);
 
@@ -407,8 +408,21 @@ const NamedDecl 
*lookupSiblingWithinEnclosingScope(ASTContext ,
   }
   if (const auto *EnclosingWhile = Parent->get())
 return CheckCompoundStmt(EnclosingWhile->getBody(), NewName);
-  if (const auto *EnclosingFor = Parent->get())
+  if (const auto *EnclosingFor = Parent->get()) {
+// Check for conflicts with other declarations within initialization
+// statement.
+if (const auto *Result = CheckDeclStmt(
+dyn_cast_or_null(EnclosingFor->getInit()), NewName))
+  return Result;
 return CheckCompoundStmt(EnclosingFor->getBody(), NewName);
+  }
+  if (const auto *EnclosingFunction = Parent->get()) {
+// Check for conflicts with other arguments.
+for (const auto *Parameter : EnclosingFunction->parameters())
+  if (Parameter !=  && Parameter->getName() == NewName)
+return Parameter;
+return CheckCompoundStmt(EnclosingFunction->getBody(), NewName);
+  }
 
   return nullptr;
 }

diff  --git a/clang-tools-extra/clangd/unittests/RenameTests.cpp 
b/clang-tools-extra/clangd/unittests/RenameTests.cpp
index 4678d35199f1..78b2af6f8cfc 100644
--- a/clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ b/clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1067,6 +1067,14 @@ TEST(RenameTest, Renameable) {
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(
+void func() {
+  for (int V^ar = 14, Conflict = 42;;) {
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(
 void func(int Conflict) {
   bool V^ar;
@@ -1074,6 +1082,19 @@ TEST(RenameTest, Renameable) {
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(
+void func(int V^ar) {
+  bool Conflict;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func(int V^ar, int Conflict) {
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
   int S^ameName;



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


[PATCH] D96009: [clangd] Improve name conflict detection

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

Can't instantiate DynTypedNode with FunctionProtoTypeLoc, has to be just 
TypeLoc :(


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96009

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


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1067,6 +1067,14 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(
+void func() {
+  for (int V^ar = 14, Conflict = 42;;) {
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(
 void func(int Conflict) {
   bool V^ar;
@@ -1074,6 +1082,19 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(
+void func(int V^ar) {
+  bool Conflict;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func(int V^ar, int Conflict) {
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
   int S^ameName;
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -337,9 +337,10 @@
   };
 
   // We need to get to the enclosing scope: NamedDecl's parent is typically
-  // DeclStmt, so enclosing scope would be the second order parent.
+  // DeclStmt (or FunctionProtoTypeLoc in case of function arguments), so
+  // enclosing scope would be the second order parent.
   const auto *Parent = GetSingleParent(DynTypedNode::create(RenamedDecl));
-  if (!Parent || !Parent->get())
+  if (!Parent || !(Parent->get() || Parent->get()))
 return nullptr;
   Parent = GetSingleParent(*Parent);
 
@@ -407,8 +408,21 @@
   }
   if (const auto *EnclosingWhile = Parent->get())
 return CheckCompoundStmt(EnclosingWhile->getBody(), NewName);
-  if (const auto *EnclosingFor = Parent->get())
+  if (const auto *EnclosingFor = Parent->get()) {
+// Check for conflicts with other declarations within initialization
+// statement.
+if (const auto *Result = CheckDeclStmt(
+dyn_cast_or_null(EnclosingFor->getInit()), NewName))
+  return Result;
 return CheckCompoundStmt(EnclosingFor->getBody(), NewName);
+  }
+  if (const auto *EnclosingFunction = Parent->get()) {
+// Check for conflicts with other arguments.
+for (const auto *Parameter : EnclosingFunction->parameters())
+  if (Parameter !=  && Parameter->getName() == NewName)
+return Parameter;
+return CheckCompoundStmt(EnclosingFunction->getBody(), NewName);
+  }
 
   return nullptr;
 }


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1067,6 +1067,14 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(
+void func() {
+  for (int V^ar = 14, Conflict = 42;;) {
+  }
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(
 void func(int Conflict) {
   bool V^ar;
@@ -1074,6 +1082,19 @@
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(
+void func(int V^ar) {
+  bool Conflict;
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
+  {R"cpp(
+void func(int V^ar, int Conflict) {
+}
+  )cpp",
+   "conflict", !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
   int S^ameName;
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -337,9 +337,10 @@
   };
 
   // We need to get to the enclosing scope: NamedDecl's parent is typically
-  // DeclStmt, so enclosing scope would be the second order parent.
+  // DeclStmt (or FunctionProtoTypeLoc in case of function arguments), so
+  // enclosing scope would be the second order parent.
   const auto *Parent = GetSingleParent(DynTypedNode::create(RenamedDecl));
-  if (!Parent || !Parent->get())
+  if (!Parent || !(Parent->get() || Parent->get()))
 return nullptr;
   Parent = 

[PATCH] D96027: [clangd] Trace queue state for each TUScheduler action.

2021-02-04 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/TUScheduler.cpp:511
   llvm::Optional> LatestPreamble;
-  std::queue PreambleRequests; /* GUARDED_BY(Mutex) */
+  std::deque PreambleRequests; /* GUARDED_BY(Mutex) */
   /// Signaled whenever LatestPreamble changes state or there's a new

TIL: queue doesn't allow iteration :shrug:



Comment at: clang-tools-extra/clangd/TUScheduler.cpp:1054
 Requests.push_back({std::move(Task), std::string(Name), 
steady_clock::now(),
-std::move(Ctx), Update, Invalidation,
-std::move(Invalidate)});
+std::move(Ctx), std::move(QueueCtx), Update,
+Invalidation, std::move(Invalidate)});

what if we just pushed the span here and kept it alive in the queue? it is 
move-able at the moment.

our tracing contract seem to be saying beginSpan/endSpan calls would always 
form a proper stack, i am not sure about its importance to the jsontracer, but 
I don't think rest of our tracers cares (and i think it would be nice for that 
trace to actually span the whole time in queue).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96027

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


[PATCH] D96033: [clang-repl] Land initial infrastructure for incremental parsing

2021-02-04 Thread Vassil Vassilev via Phabricator via cfe-commits
v.g.vassilev added a comment.

@teemperor, thanks for the hints.




Comment at: clang/include/clang/Interpreter/Transaction.h:1
+//===--- Transaction.h - Incremental Compilation and Execution---*- C++ 
-*-===//
+//

teemperor wrote:
> Could this whole file just be part of `IncrementalParser.h` which is the only 
> user ? `clang::Transaction` seems anyway a bit of a generic name, so maybe 
> this could become `clang::IncrementalParser::Transaction` then.
The intent is to expose the Transaction class and if I move it in the 
`IncrementalParser` I will have to expose the `IncrementalParser.h`. Would it 
make sense to move it as part of the Interpreter object? Eg. 
`clang::Interpreter::Transaction`?



Comment at: clang/include/clang/Parse/Parser.h:2403
   }
-
+private:
   /// isForInitDeclaration - Disambiguates between a declaration or an

teemperor wrote:
> This doesn't seem to be needed for anything?
Good catch -- indeed that's a leftover of a previous experiments.



Comment at: clang/lib/Interpreter/Interpreter.cpp:43
+#include "llvm/Support/Host.h"
+//
+

teemperor wrote:
> I think the comment here/above and some of the empty lines aren't really 
> needed here.
Yeah, the include section surrounded with `//` is to keep track of the includes 
required by `IncrementalCompilerBuilder::create`. I am not sure where this code 
should live... 

Ideally, I'd like to have it in a place where it can be included by other 
clients which require compiler instance set up for incremental compilation.



Comment at: clang/tools/clang-repl/CMakeLists.txt:3
+#  ${LLVM_TARGETS_TO_BUILD}
+#  Option
+  Support

teemperor wrote:
> Commented out by mistake?
Does not seem to be required. I will remove it for now...



Comment at: clang/unittests/Interpreter/InterpreterTest.cpp:69
+
+  EXPECT_DEATH((void)Interp->Parse("int var1 = 42;"), "");
+}

teemperor wrote:
> I think that's usually used for testing asserts but here it's an invalid 
> memory access (which might even work out just if the stars align correctly).
> 
> What about either:
> 1. Shutting down clang-repl cleanly after we hit a diagnostic.
> 2. Making an assert that we can't codegen a TU that already had any error 
> diagnostic (in which case you can surround it with the following):
> 
> ```
> #if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
> ```
Would it make sense just to not test that case?


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

https://reviews.llvm.org/D96033

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


[PATCH] D96033: [clang-repl] Land initial infrastructure for incremental parsing

2021-02-04 Thread Vassil Vassilev via Phabricator via cfe-commits
v.g.vassilev updated this revision to Diff 321544.
v.g.vassilev marked 6 inline comments as done.
v.g.vassilev added a comment.

Address comments.


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

https://reviews.llvm.org/D96033

Files:
  clang/include/clang/CodeGen/CodeGenAction.h
  clang/include/clang/Frontend/FrontendAction.h
  clang/include/clang/Interpreter/Interpreter.h
  clang/include/clang/Interpreter/Transaction.h
  clang/lib/CMakeLists.txt
  clang/lib/CodeGen/CodeGenAction.cpp
  clang/lib/Interpreter/CMakeLists.txt
  clang/lib/Interpreter/IncrementalExecutor.cpp
  clang/lib/Interpreter/IncrementalExecutor.h
  clang/lib/Interpreter/IncrementalParser.cpp
  clang/lib/Interpreter/IncrementalParser.h
  clang/lib/Interpreter/Interpreter.cpp
  clang/test/CMakeLists.txt
  clang/test/Interpreter/execute.c
  clang/test/Interpreter/sanity.c
  clang/tools/CMakeLists.txt
  clang/tools/clang-repl/CMakeLists.txt
  clang/tools/clang-repl/ClangRepl.cpp
  clang/unittests/CMakeLists.txt
  clang/unittests/CodeGen/CMakeLists.txt
  clang/unittests/CodeGen/IncrementalProcessingTest.cpp
  clang/unittests/Interpreter/CMakeLists.txt
  clang/unittests/Interpreter/InterpreterTest.cpp

Index: clang/unittests/Interpreter/InterpreterTest.cpp
===
--- /dev/null
+++ clang/unittests/Interpreter/InterpreterTest.cpp
@@ -0,0 +1,93 @@
+//===- unittests/Interpreter/InterpreterTest.cpp --- Interpreter tests ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// Unit tests for our Interpreter library.
+//
+//===--===//
+
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Interpreter/Interpreter.h"
+
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclGroup.h"
+
+#include "llvm/ADT/ArrayRef.h"
+
+#include "gtest/gtest.h"
+
+using namespace clang;
+
+namespace {
+
+static std::unique_ptr createInterpreter() {
+  std::vector ClangArgs = {"-Xclang", "-emit-llvm-only"};
+  auto CI = cantFail(clang::IncrementalCompilerBuilder::create(ClangArgs));
+  return std::move(cantFail(clang::Interpreter::create(std::move(CI;
+}
+
+TEST(InterpreterTest, Sanity) {
+  std::unique_ptr Interp = createInterpreter();
+  Transaction (cantFail(Interp->Parse("void g(); void g() {}")));
+  EXPECT_EQ(2U, R1.Decls.size());
+
+  Transaction (cantFail(Interp->Parse("int i;")));
+  EXPECT_EQ(1U, R2.Decls.size());
+}
+
+static std::string DeclToString(DeclGroupRef DGR) {
+  return llvm::cast(DGR.getSingleDecl())->getQualifiedNameAsString();
+}
+
+TEST(InterpreterTest, IncrementalInputTopLevelDecls) {
+  std::unique_ptr Interp = createInterpreter();
+  auto R1OrErr = Interp->Parse("int var1 = 42; int f() { return var1; }");
+  // gtest doesn't expand into explicit bool conversions.
+  EXPECT_TRUE(!!R1OrErr);
+  auto R1 = R1OrErr->Decls;
+  EXPECT_EQ(2U, R1.size());
+  EXPECT_EQ("var1", DeclToString(R1[0]));
+  EXPECT_EQ("f", DeclToString(R1[1]));
+
+  auto R2OrErr = Interp->Parse("int var2 = f();");
+  EXPECT_TRUE(!!R2OrErr);
+  auto R2 = R2OrErr->Decls;
+  EXPECT_EQ(1U, R2.size());
+  EXPECT_EQ("var2", DeclToString(R2[0]));
+}
+
+
+TEST(InterpreterTest, Errors) {
+  std::unique_ptr Interp = createInterpreter();
+  auto Err = Interp->Parse("intentional_error v1 = 42; ").takeError();
+  EXPECT_EQ("Parsing failed.", llvm::toString(std::move(Err)));
+
+  EXPECT_DEATH((void)Interp->Parse("int var1 = 42;"), "");
+}
+
+// Here we test whether the user can mix declarations and statements. The
+// interpreter should be smart enough to recognize the declarations from the
+// statements and wrap the latter into a declaration, producing valid code.
+TEST(InterpreterTest, DeclsAndStatements) {
+  std::unique_ptr Interp = createInterpreter();
+  auto R1OrErr = Interp->Parse(
+  "int var1 = 42; extern \"C\" int printf(const char*, ...);");
+  // gtest doesn't expand into explicit bool conversions.
+  EXPECT_TRUE(!!R1OrErr);
+
+  auto R1 = R1OrErr->Decls;
+  EXPECT_EQ(2U, R1.size());
+
+  // FIXME: Add support for wrapping and running statements.
+  auto R2OrErr =
+Interp->Parse("var1++; printf(\"var1 value is %d\\n\", var1);");
+  EXPECT_FALSE(!!R2OrErr);
+  auto Err = R2OrErr.takeError();
+  EXPECT_EQ("Parsing failed.", llvm::toString(std::move(Err)));
+}
+
+} // end anonymous namespace
Index: clang/unittests/Interpreter/CMakeLists.txt
===
--- /dev/null
+++ clang/unittests/Interpreter/CMakeLists.txt
@@ -0,0 +1,10 @@
+set(LLVM_LINK_COMPONENTS
+  )
+
+add_clang_unittest(ClangReplInterpreterTests
+  InterpreterTest.cpp
+  )
+target_link_libraries(ClangReplInterpreterTests PUBLIC
+  clangInterpreter

[PATCH] D95561: [Clang] Introduce Swift async calling convention.

2021-02-04 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/include/clang/Basic/AttrDocs.td:4409
+  calls to other ``swiftasynccall`` functions must be in tail position
+  (in all language modes). In particular:
+  - For C, this implies that ``return async_f();`` (``async_f`` is another

I don't think the "must be in tail position" here is true.  Allow me to suggest 
an alternative way of saying this:

> Within a `swiftasynccall` function, a call to a `swiftasynccall` function 
> that is the immediate operand of a `return` statement is guaranteed to be 
> performed as a tail call.  This syntax is allowed even in C as an extension 
> (a call to a `void`-returning function cannot be a `return` operand in 
> standard C).  If something in the calling function would semantically be 
> performed after a guaranteed tail call, such as the non-trivial destruction 
> of a local variable or temporary, then the program is ill-formed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95561

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


[PATCH] D96070: [clang] [driver] Enable static linking to libc++

2021-02-04 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: rsmith, EricWF, ldionne, tstellar, hfinkel.
tbaeder requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Hi,

currently the following fails:

  clang++ -stdlib=libc++ -static ./test.cpp

because libc++ needs libc++abi and pthreads.

This change has already been proposed in a different version, using 
`-static-libc++` in https://reviews.llvm.org/D63329

And https://reviews.llvm.org/D60794 tried to do it in libc++ instead of clang.

This version makes both linking with `-static` as above work, as well as 
`-static-libstdc++ -stdlib=libc++`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96070

Files:
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/test/Driver/libcxx-link.cpp
  clang/test/Driver/netbsd.cpp


Index: clang/test/Driver/netbsd.cpp
===
--- clang/test/Driver/netbsd.cpp
+++ clang/test/Driver/netbsd.cpp
@@ -250,7 +250,7 @@
 // S-ARM-7: clang{{.*}}" "-cc1" "-triple" "armv5e-unknown-netbsd7.0.0-eabi"
 // S-ARM-7: ld{{.*}}" "--eh-frame-hdr" "-Bstatic"
 // S-ARM-7: "-o" "a.out" "{{.*}}/usr/lib{{/|}}crt0.o" 
"{{.*}}/usr/lib{{/|}}eabi{{/|}}crti.o"
-// S-ARM-7: "{{.*}}/usr/lib{{/|}}crtbegin.o" "{{.*}}.o" "-lc++" "-lm" "-lc"
+// S-ARM-7: "{{.*}}/usr/lib{{/|}}crtbegin.o" "{{.*}}.o" "-lc++" "-lc++abi" 
"-lm" "-lc"
 // S-ARM-7: "{{.*}}/usr/lib{{/|}}crtend.o" "{{.*}}/usr/lib{{/|}}crtn.o"
 
 // S-AARCH64: clang{{.*}}" "-cc1" "-triple" "aarch64-unknown-netbsd"
Index: clang/test/Driver/libcxx-link.cpp
===
--- /dev/null
+++ clang/test/Driver/libcxx-link.cpp
@@ -0,0 +1,20 @@
+
+
+// Regular shared link
+// RUN: %clang++ %s -stdlib=libc++
+
+// Static link via -static-libstdc++
+// RUN: %clang++ %s -stdlib=libc++ -static-libstdc++
+
+// Static link via -static
+// RUN: %clang++ %s -stdlib=libc++ -static
+
+// Both
+// RUN: %clang++ %s -stdlib=libc++ -static-libstdc++ -static
+
+#include 
+int main(int argc, char **argv) {
+  std::cout << "Hello Word\n";
+
+  return 0;
+}
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -613,6 +613,14 @@
 // FIXME: Does this really make sense for all GNU toolchains?
 WantPthread = true;
 
+  // libc++ links against pthreads so for static links we need
+  // to supply this manually
+  if (!WantPthread &&
+  getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx &&
+  (Args.hasArg(options::OPT_static) ||
+   Args.hasArg(options::OPT_static_libstdcxx)))
+WantPthread = true;
+
   AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
 
   if (WantPthread && !isAndroid)
Index: clang/lib/Driver/ToolChain.cpp
===
--- clang/lib/Driver/ToolChain.cpp
+++ clang/lib/Driver/ToolChain.cpp
@@ -1041,6 +1041,9 @@
   switch (Type) {
   case ToolChain::CST_Libcxx:
 CmdArgs.push_back("-lc++");
+if (Args.hasArg(options::OPT_static) ||
+Args.hasArg(options::OPT_static_libstdcxx))
+  CmdArgs.push_back("-lc++abi");
 break;
 
   case ToolChain::CST_Libstdcxx:


Index: clang/test/Driver/netbsd.cpp
===
--- clang/test/Driver/netbsd.cpp
+++ clang/test/Driver/netbsd.cpp
@@ -250,7 +250,7 @@
 // S-ARM-7: clang{{.*}}" "-cc1" "-triple" "armv5e-unknown-netbsd7.0.0-eabi"
 // S-ARM-7: ld{{.*}}" "--eh-frame-hdr" "-Bstatic"
 // S-ARM-7: "-o" "a.out" "{{.*}}/usr/lib{{/|}}crt0.o" "{{.*}}/usr/lib{{/|}}eabi{{/|}}crti.o"
-// S-ARM-7: "{{.*}}/usr/lib{{/|}}crtbegin.o" "{{.*}}.o" "-lc++" "-lm" "-lc"
+// S-ARM-7: "{{.*}}/usr/lib{{/|}}crtbegin.o" "{{.*}}.o" "-lc++" "-lc++abi" "-lm" "-lc"
 // S-ARM-7: "{{.*}}/usr/lib{{/|}}crtend.o" "{{.*}}/usr/lib{{/|}}crtn.o"
 
 // S-AARCH64: clang{{.*}}" "-cc1" "-triple" "aarch64-unknown-netbsd"
Index: clang/test/Driver/libcxx-link.cpp
===
--- /dev/null
+++ clang/test/Driver/libcxx-link.cpp
@@ -0,0 +1,20 @@
+
+
+// Regular shared link
+// RUN: %clang++ %s -stdlib=libc++
+
+// Static link via -static-libstdc++
+// RUN: %clang++ %s -stdlib=libc++ -static-libstdc++
+
+// Static link via -static
+// RUN: %clang++ %s -stdlib=libc++ -static
+
+// Both
+// RUN: %clang++ %s -stdlib=libc++ -static-libstdc++ -static
+
+#include 
+int main(int argc, char **argv) {
+  std::cout << "Hello Word\n";
+
+  return 0;
+}
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -613,6 +613,14 @@
 // FIXME: Does this 

[PATCH] D95691: Implement P2173 for attributes on lambdas

2021-02-04 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticGroups.td:269
+def CXXPre2BCompatPedantic :
+  DiagGroup<"c++98-c++11-c++14-c++17-c++20-compat-pedantic", [CXXPre2BCompat]>;
 

Quuxplusone wrote:
> aaron.ballman wrote:
> > rjmccall wrote:
> > > Uh, I think we're a couple standard releases past the point at which we 
> > > should have reconsidered this schema.  I guess the problem is that we 
> > > can't say `-Wpre-c++23-compat` without jumping the gun.  Is there a 
> > > problem with `-Wc++20-compat` and then having the earlier warning groups 
> > > imply the later ones?  That seems to be what we do with `-Wc++98-compat`; 
> > > did we abandon that approach intentionally?
> > @rsmith may have more background here. I was following the pattern already 
> > in the file, but I tend to agree that this pattern is not leading us 
> > somewhere good. FWIW, I ran into a similar situation with this on the C 
> > side of things in D95396, so we should probably be consistent there too.
> My understanding is that the //command-line user// is expected to pass
> - `clang++ -std=c++20 -Wc++11-compat` to indicate "I want //actually// to 
> compile in C++20 mode, but give me warnings about anything that would prevent 
> compiling in C++11 mode"
> - `clang++ -std=c++17 -Wc++14-compat` to indicate "I want //actually// to 
> compile in C++17 mode, but give me warnings about anything that would prevent 
> compiling in C++14 mode"
> - `clang++ -std=c++14 -Wc++20-compat` to indicate "I want //actually// to 
> compile in C++14 mode, but give me warnings about anything that would prevent 
> compiling in C++20 mode" — EXCEPT that I think this is not supported. My 
> impression is that forward-compatibility warnings are generally just rolled 
> into `-Wall` and not handled separately beyond that?
> 
> I don't think any human user is expected to pass 
> `-Wc++98-c++11-c++14-c++17-c++20-compat` by hand; it's just an internal name 
> for a particular subset of `-Wc++98-compat`.
> 
> IOW, we could choose a new naming scheme for it, but that would be a purely 
> internal change that won't affect how command-line users interact with Clang 
> at all (for better and for worse).
Diagnostic groups can both directly contain diagnostics and imply other 
diagnostic groups, so I don't think there's any reason to make a dedicated 
group just to contain the new diagnostics in e.g. `-Wc++14-compat` except to 
allow someone turn on those warnings separately.  And it does show up to users 
as the warning group under `-fdiagnostics-show-option` (which is the default).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95691

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


[PATCH] D94627: [PowerPC][PC Rel] Implement option to omit Power10 instructions from stubs

2021-02-04 Thread Stefan Pintilie via Phabricator via cfe-commits
stefanp added a comment.

Just nits this time around.




Comment at: lld/ELF/Driver.cpp:765
+// instructions in stubs.
+static bool getP10StubOpt(opt::InputArgList ) {
+

Conanap wrote:
> For this function here, I realize we can inline all the ifs into a giant 
> return statement - is there any opinions on this? I thought the if statements 
> might make this a bit more readable, but if it is preferred that there is 
> only 1 return statement I can make that change as well.
Personally I'm happy with it like this. I'm not a fan of huge if statements but 
I could be persuaded otherwise depending on what other reviewers have to say...



Comment at: lld/ELF/Options.td:451
+  J<"power10-stubs=">, HelpText<
+ "Enables Power10 instsructions in all stubs without 
options, "
+ "options override previous flags."

nit:
instsructions -> instructions 



Comment at: lld/ELF/Thunks.cpp:936
+const uint64_t addi = ADDI_R12_TO_R2_NO_DISP | (tocOffset & 0x);
+write32(buf + 4, addi); // addi r12, 2, offset
+nextInstOffset = 8;

nit:
addi r12, 2, offset -> addi r12, r2, offset



Comment at: lld/test/ELF/ppc64-pcrel-call-to-extern.s:110
+
+## .plt[2] - 0x10010010 = 0x10030158 - 0x10010010 = 0x20148 = 131416
 # CHECK-LABEL: <__plt_pcrel_callee_global_stother0>:

nit:
Same thing here. Please fix the comment.
`0x20148 = 131400` and not `131416`



Comment at: lld/test/ELF/ppc64-pcrel-call-to-extern.s:135
+
+## .plt[3] - 0x10020010 = 0x10030160 - 0x10020010 = 0x10150 = 65888
 # CHECK-LABEL: <__plt_pcrel_callee_global_stother1>:

nit:
Please fix these comments.
`0x10150` does not equal `65888`.



Comment at: lld/test/ELF/ppc64-pcrel-call-to-extern.s:160
+
+## .plt[4] - 0x10030010 = 0x10030168 - 0x10030010 = 0x150 = 360
 # CHECK-LABEL: <__plt_pcrel_callee_global_TOC>:

nit:
This comment too.
```
0x10030168 - 0x10030010 = 0x158
0x150 = 336
```
I'm not going to comment on all of these. Please take a look at the comments 
where numbers have changed and make sure that they are correct.



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

https://reviews.llvm.org/D94627

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


[PATCH] D95849: [FileCheck] Default --allow-unused-prefixes to false

2021-02-04 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added subscribers: pengfei, RKSimon.
MaskRay added a comment.

@nikic D95849  has already changed 
`llvm/test/` to default to `--allow-unused-prefixes`.  I updated a few 
directories to be `--allow-unused-prefixes` clean (this uncovered improvement 
to many tests).

Some `update{,_llc,_analyzer}_test_checks.py` use cases may find 
`--allow-unused-prefixes=false` mode better, but such use cases still appear to 
be a minority (e.g. @RKSimon/@pengfei/my/others' fixes to test/CodeGen 
directories).
https://lists.llvm.org/pipermail/llvm-dev/2021-February/148331.html


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95849

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


[PATCH] D95948: Stop traping on sNaN in __builtin_isnan

2021-02-04 Thread Kevin P. Neal via Phabricator via cfe-commits
kpn added a comment.

In D95948#2542884 , @mibintc wrote:

> Should we add tests for mlong-double-64, -80, -128?

Assuming Ty->getScalarSizeInBits() returns 64, 80, or 128 in those cases, I 
think it's good enough to just add an AArch64 (or some other 128-bit long 
double host) and call it a day. We're testing isnan(), not that command line 
option, after all.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95948

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


[PATCH] D95849: [FileCheck] Default --allow-unused-prefixes to false

2021-02-04 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 321524.
MaskRay edited the summary of this revision.
MaskRay added a comment.

Rebase to re-cycle bots


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95849

Files:
  clang/test/Driver/crash-report-null.test
  clang/test/OpenMP/lit.local.cfg
  clang/test/lit.cfg.py
  llvm/test/FileCheck/allow-unused-prefixes.txt
  llvm/test/FileCheck/lit.local.cfg
  llvm/test/Other/opt-bisect-legacy-pass-manager.ll
  llvm/test/Reduce/lit.local.cfg
  llvm/test/Transforms/Attributor/lit.local.cfg
  llvm/test/lit.cfg.py
  llvm/utils/FileCheck/FileCheck.cpp

Index: llvm/utils/FileCheck/FileCheck.cpp
===
--- llvm/utils/FileCheck/FileCheck.cpp
+++ llvm/utils/FileCheck/FileCheck.cpp
@@ -78,7 +78,7 @@
  "checks that some error message does not occur, for example."));
 
 static cl::opt AllowUnusedPrefixes(
-"allow-unused-prefixes", cl::init(true), cl::ZeroOrMore,
+"allow-unused-prefixes", cl::init(false), cl::ZeroOrMore,
 cl::desc("Allow prefixes to be specified but not appear in the test."));
 
 static cl::opt MatchFullLines(
Index: llvm/test/lit.cfg.py
===
--- llvm/test/lit.cfg.py
+++ llvm/test/lit.cfg.py
@@ -83,20 +83,6 @@
 return found_dylibs[0]
 
 
-
-# FIXME: remove this when we flip the default value for --allow-unused-prefixes
-# to false.
-fc = ToolSubst('FileCheck', unresolved='fatal')
-# Insert this first. Then, we'll first update the blank FileCheck command; then,
-# the default substitution of FileCheck will replace it to its full path.
-config.substitutions.insert(0, (fc.regex,
-'FileCheck --allow-unused-prefixes=false'))
-# When addressing this fixme, replace %FileCheckRaw% with just FileCheck.
-config.substitutions.append(('%FileCheckRaw%', 'FileCheck'))
-# Also remove the lit.local.cfg under llvm/test/Reduce
-# and the pertinent FIXME in llvm/test/FileCheck
-
-
 llvm_config.use_default_substitutions()
 
 # Add site-specific substitutions.
@@ -162,8 +148,8 @@
 # FIXME: Why do we have both `lli` and `%lli` that do slightly different things?
 tools.extend([
 'dsymutil', 'lli', 'lli-child-target', 'llvm-ar', 'llvm-as',
-'llvm-addr2line', 'llvm-bcanalyzer', 'llvm-bitcode-strip', 'llvm-config', 
-'llvm-cov', 'llvm-cxxdump', 'llvm-cvtres', 'llvm-diff', 'llvm-dis', 
+'llvm-addr2line', 'llvm-bcanalyzer', 'llvm-bitcode-strip', 'llvm-config',
+'llvm-cov', 'llvm-cxxdump', 'llvm-cvtres', 'llvm-diff', 'llvm-dis',
 'llvm-dwarfdump', 'llvm-dlltool', 'llvm-exegesis', 'llvm-extract',
 'llvm-isel-fuzzer', 'llvm-ifs',
 'llvm-install-name-tool', 'llvm-jitlink', 'llvm-opt-fuzzer', 'llvm-lib',
Index: llvm/test/Transforms/Attributor/lit.local.cfg
===
--- llvm/test/Transforms/Attributor/lit.local.cfg
+++ llvm/test/Transforms/Attributor/lit.local.cfg
@@ -2,10 +2,4 @@
 from lit.llvm.subst import ToolSubst
 
 fc = ToolSubst('FileCheck', unresolved='fatal')
-# the parent introduced the opposite rule, so we replace it if we see it.
-if len(config.substitutions) > 0 and config.substitutions[0] == (fc.regex, 'FileCheck --allow-unused-prefixes=false'):
-config.substitutions[0] = (
-fc.regex, 'FileCheck --allow-unused-prefixes=true')
-else:
-config.substitutions.insert(0, (fc.regex, 
-'FileCheck --allow-unused-prefixes=true'))
+config.substitutions.insert(0, (fc.regex, 'FileCheck --allow-unused-prefixes'))
Index: llvm/test/Reduce/lit.local.cfg
===
--- llvm/test/Reduce/lit.local.cfg
+++ /dev/null
@@ -1,8 +0,0 @@
-# -*- Python -*- vim: set ft=python ts=4 sw=4 expandtab tw=79:
-# FIXME: remove this file when we flip the default for --allow-unused-prefixes.
-from lit.llvm.subst import ToolSubst
-
-fc = ToolSubst('FileCheck', unresolved='fatal')
-# the parent introduced the opposite rule, so we replace it if we see it.
-if len(config.substitutions) > 0 and config.substitutions[0] == (fc.regex, 'FileCheck --allow-unused-prefixes=false'):
-del config.substitutions[0]
Index: llvm/test/Other/opt-bisect-legacy-pass-manager.ll
===
--- llvm/test/Other/opt-bisect-legacy-pass-manager.ll
+++ llvm/test/Other/opt-bisect-legacy-pass-manager.ll
@@ -39,7 +39,7 @@
 ; f2() in f3().
 
 ; RUN: %python %S/opt-bisect-helper.py --start=0 --end=256 --optcmd=opt \
-; RUN: --filecheckcmd=%FileCheckRaw% --test=%s \
+; RUN: --filecheckcmd=FileCheck --test=%s \
 ; RUN: --prefix=CHECK-BISECT-INLINE-HELPER \
 ; RUN: | FileCheck %s --check-prefix=CHECK-BISECT-INLINE-RESULT
 ; The helper script 

[PATCH] D96058: [CodeComplete] Guess type for designated initializers

2021-02-04 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

Thanks! LG with a small concern around possible effects on member completions 
for uninstantiated templates.




Comment at: clang/lib/Parse/ParseInit.cpp:163
+DesignatorCompletionInfo DesignatorCompletion) {
+  if (!getPreprocessor().isCodeCompletionEnabled())
+DesignatorCompletion.PreferredBaseType = QualType(); // skip field lookup

it might be nice to make the whole preferredtypebuilder a no-op on construction 
when codecompletion is disabled. but that can be an adventure for another day.



Comment at: clang/lib/Sema/SemaCodeComplete.cpp:4803
+  if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared)
+RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
+}

i think this means we are going to offer completion for uninstantiated 
specializations using the primary template now (through 
`Sema::CodeCompleteMemberReferenceExpr`), which i am not sure is possible, but 
should be an improvement in either case.

but not having any tests (especially failing) makes me a little anxious.



Comment at: clang/lib/Sema/SemaCodeComplete.cpp:5790
+  if (const FieldDecl *FD = llvm::dyn_cast(Member))
+NextType = FD->getType();
+  }

why don't we break after the first one ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96058

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


[PATCH] D95948: Stop traping on sNaN in __builtin_isnan

2021-02-04 Thread Melanie Blower via Phabricator via cfe-commits
mibintc added a comment.

Should we add tests for mlong-double-64, -80, -128?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95948

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


[PATCH] D96000: Don't emit coverage mapping for excluded functions

2021-02-04 Thread Vedant Kumar via Phabricator via cfe-commits
vsk added inline comments.



Comment at: clang/test/CodeGen/profile-filter.c:27
+// EXCLUDE: @__covrec_{{[0-9A-F]+}}u = linkonce_odr hidden constant <{ i64, 
i32, i64, i64, [{{.*}} x i8] }> <{ {{.*}} }>, section "__llvm_covfun"
+// EXCLUDE-NOT: @__covrec_{{[0-9A-F]+}}u = linkonce_odr hidden constant <{ 
i64, i32, i64, i64, [{{.*}} x i8] }> <{ {{.*}} }>, section "__llvm_covfun"
+

This is somewhat difficult to interpret. Would you be open to specifying 
-dump-coverage-mapping (e.g. https://godbolt.org/z/5PvvEv), in a separate cc1 
invocation if needed, and checking that instead?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96000

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


[PATCH] D95948: Stop traping on sNaN in __builtin_isnan

2021-02-04 Thread Kevin P. Neal via Phabricator via cfe-commits
kpn added a comment.

This looks like a definite step forward. Thank you!

Can you do an AArch64 test case showing long double? Right now there's no 
128-bit test case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95948

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


[PATCH] D94367: [Clang][Driver] Add -ffinite-loops flags

2021-02-04 Thread Florian Hahn via Phabricator via cfe-commits
fhahn added a comment.

In D94367#2542809 , @atmnpatel wrote:

> Wait actually, we're gonna need D94366  
> anyways, I'll get address @xbolva00's comments by eod.

FWIW I think we should sort this one (D94367 ) 
first, because it may simplify D94366 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94367

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


[PATCH] D94367: [Clang][Driver] Add -ffinite-loops flags

2021-02-04 Thread Atmn Patel via Phabricator via cfe-commits
atmnpatel added a comment.

Wait actually, we're gonna need D94366  
anyways, I'll get address @xbolva00's comments by eod.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94367

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


[PATCH] D94367: [Clang][Driver] Add -ffinite-loops flags

2021-02-04 Thread Atmn Patel via Phabricator via cfe-commits
atmnpatel added a comment.

@fhahn  Sorry for the hold up, I don't think I'll get to this relatively soon, 
I'll abandon this one and D94366  to sweep the 
board.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94367

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


[PATCH] D94367: [Clang][Driver] Add -ffinite-loops flags

2021-02-04 Thread Florian Hahn via Phabricator via cfe-commits
fhahn added a comment.
Herald added a reviewer: jansvoboda11.

@atmnpatel reverse ping. Just curious if you think you'll have time to follow 
up on this patch soonish?

Otherwise I'm probably going to add at least the `-fno-finite-loops` option, 
because we have users which code breaks due to the `mustprogress` loop deletion 
changes (because of problems in the source code, but they need a way to disable 
until they can fix all sources)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94367

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


[PATCH] D95691: Implement P2173 for attributes on lambdas

2021-02-04 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticGroups.td:269
+def CXXPre2BCompatPedantic :
+  DiagGroup<"c++98-c++11-c++14-c++17-c++20-compat-pedantic", [CXXPre2BCompat]>;
 

aaron.ballman wrote:
> rjmccall wrote:
> > Uh, I think we're a couple standard releases past the point at which we 
> > should have reconsidered this schema.  I guess the problem is that we can't 
> > say `-Wpre-c++23-compat` without jumping the gun.  Is there a problem with 
> > `-Wc++20-compat` and then having the earlier warning groups imply the later 
> > ones?  That seems to be what we do with `-Wc++98-compat`; did we abandon 
> > that approach intentionally?
> @rsmith may have more background here. I was following the pattern already in 
> the file, but I tend to agree that this pattern is not leading us somewhere 
> good. FWIW, I ran into a similar situation with this on the C side of things 
> in D95396, so we should probably be consistent there too.
My understanding is that the //command-line user// is expected to pass
- `clang++ -std=c++20 -Wc++11-compat` to indicate "I want //actually// to 
compile in C++20 mode, but give me warnings about anything that would prevent 
compiling in C++11 mode"
- `clang++ -std=c++17 -Wc++14-compat` to indicate "I want //actually// to 
compile in C++17 mode, but give me warnings about anything that would prevent 
compiling in C++14 mode"
- `clang++ -std=c++14 -Wc++20-compat` to indicate "I want //actually// to 
compile in C++14 mode, but give me warnings about anything that would prevent 
compiling in C++20 mode" — EXCEPT that I think this is not supported. My 
impression is that forward-compatibility warnings are generally just rolled 
into `-Wall` and not handled separately beyond that?

I don't think any human user is expected to pass 
`-Wc++98-c++11-c++14-c++17-c++20-compat` by hand; it's just an internal name 
for a particular subset of `-Wc++98-compat`.

IOW, we could choose a new naming scheme for it, but that would be a purely 
internal change that won't affect how command-line users interact with Clang at 
all (for better and for worse).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95691

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


[PATCH] D95691: Implement P2173 for attributes on lambdas

2021-02-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticGroups.td:269
+def CXXPre2BCompatPedantic :
+  DiagGroup<"c++98-c++11-c++14-c++17-c++20-compat-pedantic", [CXXPre2BCompat]>;
 

rjmccall wrote:
> Uh, I think we're a couple standard releases past the point at which we 
> should have reconsidered this schema.  I guess the problem is that we can't 
> say `-Wpre-c++23-compat` without jumping the gun.  Is there a problem with 
> `-Wc++20-compat` and then having the earlier warning groups imply the later 
> ones?  That seems to be what we do with `-Wc++98-compat`; did we abandon that 
> approach intentionally?
@rsmith may have more background here. I was following the pattern already in 
the file, but I tend to agree that this pattern is not leading us somewhere 
good. FWIW, I ran into a similar situation with this on the C side of things in 
D95396, so we should probably be consistent there too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95691

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


[PATCH] D95691: Implement P2173 for attributes on lambdas

2021-02-04 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticGroups.td:269
+def CXXPre2BCompatPedantic :
+  DiagGroup<"c++98-c++11-c++14-c++17-c++20-compat-pedantic", [CXXPre2BCompat]>;
 

Uh, I think we're a couple standard releases past the point at which we should 
have reconsidered this schema.  I guess the problem is that we can't say 
`-Wpre-c++23-compat` without jumping the gun.  Is there a problem with 
`-Wc++20-compat` and then having the earlier warning groups imply the later 
ones?  That seems to be what we do with `-Wc++98-compat`; did we abandon that 
approach intentionally?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95691

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


[PATCH] D95561: [Clang] Introduce Swift async calling convention.

2021-02-04 Thread Varun Gandhi via Phabricator via cfe-commits
varungandhi-apple updated this revision to Diff 321501.
varungandhi-apple added a comment.

1. Update whitespace and add documentation for swiftasynccall.
2. Update commit message.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95561

Files:
  clang/include/clang-c/Index.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/Specifiers.h
  clang/include/clang/CodeGen/SwiftCallingConv.h
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/MicrosoftMangle.cpp
  clang/lib/AST/Type.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/Basic/Targets/AArch64.cpp
  clang/lib/Basic/Targets/ARM.cpp
  clang/lib/Basic/Targets/PPC.h
  clang/lib/Basic/Targets/SystemZ.h
  clang/lib/Basic/Targets/WebAssembly.h
  clang/lib/Basic/Targets/X86.h
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/CodeGen/arm-swiftcall.c
  clang/test/CodeGen/debug-info-cc.c
  clang/test/Sema/attr-c2x.c
  clang/test/Sema/attr-swiftcall.c
  clang/test/Sema/no_callconv.cpp
  clang/test/SemaCXX/attr-swiftcall.cpp
  clang/tools/libclang/CXType.cpp
  llvm/include/llvm/Demangle/MicrosoftDemangleNodes.h
  llvm/lib/Demangle/MicrosoftDemangle.cpp
  llvm/lib/Demangle/MicrosoftDemangleNodes.cpp
  llvm/test/Demangle/ms-mangle.test

Index: llvm/test/Demangle/ms-mangle.test
===
--- llvm/test/Demangle/ms-mangle.test
+++ llvm/test/Demangle/ms-mangle.test
@@ -341,6 +341,9 @@
 ?swift_func@@YSXXZ
 ; CHECK: void __attribute__((__swiftcall__)) swift_func(void)
 
+?swift_async_func@@YTXXZ
+; CHECK: void __attribute__((__swiftasynccall__)) swift_async_func(void)
+
 ??$fn_tmpl@$1?extern_c_func@@YAXXZ@@YAXXZ
 ; CHECK: void __cdecl fn_tmpl< __cdecl extern_c_func(void)>(void)
 
Index: llvm/lib/Demangle/MicrosoftDemangleNodes.cpp
===
--- llvm/lib/Demangle/MicrosoftDemangleNodes.cpp
+++ llvm/lib/Demangle/MicrosoftDemangleNodes.cpp
@@ -110,6 +110,9 @@
   case CallingConv::Swift:
 OS << "__attribute__((__swiftcall__)) ";
 break;
+  case CallingConv::SwiftAsync:
+OS << "__attribute__((__swiftasynccall__)) ";
+break;
   default:
 break;
   }
Index: llvm/lib/Demangle/MicrosoftDemangle.cpp
===
--- llvm/lib/Demangle/MicrosoftDemangle.cpp
+++ llvm/lib/Demangle/MicrosoftDemangle.cpp
@@ -1713,6 +1713,8 @@
 return CallingConv::Vectorcall;
   case 'S':
 return CallingConv::Swift;
+  case 'T':
+return CallingConv::SwiftAsync;
   }
 
   return CallingConv::None;
Index: llvm/include/llvm/Demangle/MicrosoftDemangleNodes.h
===
--- llvm/include/llvm/Demangle/MicrosoftDemangleNodes.h
+++ llvm/include/llvm/Demangle/MicrosoftDemangleNodes.h
@@ -67,7 +67,8 @@
   Eabi,
   Vectorcall,
   Regcall,
-  Swift, // Clang-only
+  Swift,  // Clang-only
+  SwiftAsync, // Clang-only
 };
 
 enum class ReferenceKind : uint8_t { None, LValueRef, RValueRef };
Index: clang/tools/libclang/CXType.cpp
===
--- clang/tools/libclang/CXType.cpp
+++ clang/tools/libclang/CXType.cpp
@@ -664,6 +664,7 @@
   TCALLINGCONV(AAPCS_VFP);
   TCALLINGCONV(IntelOclBicc);
   TCALLINGCONV(Swift);
+  TCALLINGCONV(SwiftAsync);
   TCALLINGCONV(PreserveMost);
   TCALLINGCONV(PreserveAll);
 case CC_SpirFunction: return CXCallingConv_Unexposed;
Index: clang/test/SemaCXX/attr-swiftcall.cpp
===
--- clang/test/SemaCXX/attr-swiftcall.cpp
+++ clang/test/SemaCXX/attr-swiftcall.cpp
@@ -1,14 +1,20 @@
 // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -fsyntax-only -verify %s
 
 #define SWIFTCALL __attribute__((swiftcall))
+#define SWIFTASYNCCALL __attribute__((swiftasynccall))
 #define INDIRECT_RESULT __attribute__((swift_indirect_result))
 #define ERROR_RESULT __attribute__((swift_error_result))
 #define CONTEXT __attribute__((swift_context))
+#define ASYNC_CONTEXT __attribute__((swift_async_context))
 
 int notAFunction SWIFTCALL; // expected-warning {{'swiftcall' only applies to function types; type here is 'int'}}
+int notAnAsyncFunction SWIFTASYNCCALL; // expected-warning {{'swiftasynccall' only applies to function types; type here is 'int'}}
 void variadic(int x, ...) SWIFTCALL; // expected-error {{variadic function cannot use swiftcall calling convention}}
+void variadic_async(int x, ...) SWIFTASYNCCALL; // expected-error {{variadic function cannot use swiftasynccall calling convention}}
 void multiple_ccs(int x) SWIFTCALL __attribute__((vectorcall)); // expected-error {{vectorcall and swiftcall attributes are not compatible}}
+void 

[PATCH] D96058: [CodeComplete] Guess type for designated initializers

2021-02-04 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: kadircet.
sammccall requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This enables:

- completion in { .x.^ }
- completion in { .x = { .^ } }
- type-based ranking of candidates for { .x = ^ }


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96058

Files:
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseInit.cpp
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/CodeCompletion/desig-init.cpp

Index: clang/test/CodeCompletion/desig-init.cpp
===
--- clang/test/CodeCompletion/desig-init.cpp
+++ clang/test/CodeCompletion/desig-init.cpp
@@ -16,8 +16,8 @@
   // CHECK-CC1-NOT: foo
   // CHECK-CC1-NOT: t
 
-  // FIXME: Handle nested designators
-  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:11:20 %s -o - | count 0
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:11:20 %s -o - | FileCheck -check-prefix=CHECK-NESTED %s
+  // CHECK-NESTED: COMPLETION: t : [#int#]t
 
   Base B = {.t = 2};
   auto z = [](Base B) {};
@@ -29,6 +29,14 @@
   // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:25:11 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC2 %s
   // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:26:13 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC2 %s
   // CHECK-CC2: COMPLETION: t : [#int#]t
+
+  Foo G1{.b = {.t = 0}};
+  Foo G2{.b{.t = 0}};
+  Foo G3{b: {.t = 0}};
+  // RUN: %clang_cc1 -code-completion-at=%s:33:17 -fsyntax-only -code-completion-patterns %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-NESTED-2 %s
+  // RUN: %clang_cc1 -code-completion-at=%s:34:14 -fsyntax-only -code-completion-patterns %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-NESTED-2 %s
+  // RUN: %clang_cc1 -code-completion-at=%s:35:15 -fsyntax-only -code-completion-patterns %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-NESTED-2 %s
+  // CHECK-NESTED-2: COMPLETION: t : [#int#]t
 }
 
 // Handle templates
@@ -41,10 +49,10 @@
 };
 void bar() {
   Test T{.x = 2};
-  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:43:17 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC3 %s
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:51:17 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC3 %s
   // CHECK-CC3: COMPLETION: x : [#T#]x
   Test X{.x = 2};
-  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:46:16 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC4 %s
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:54:16 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC4 %s
   // CHECK-CC4: COMPLETION: x : [#int#]x
   // CHECK-CC4-NEXT: COMPLETION: y : [#char#]y
 }
@@ -52,5 +60,5 @@
 template 
 void aux() {
   Test X{.x = T(2)};
-  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:54:14 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC3 %s
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:62:14 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC3 %s
 }
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -405,6 +405,16 @@
   ExpectedLoc = Tok;
 }
 
+static QualType getDesignatedType(QualType BaseType, const Designation );
+
+void PreferredTypeBuilder::enterDesignatedInitializer(SourceLocation Tok,
+  QualType BaseType,
+  const Designation ) {
+  ComputeType = nullptr;
+  Type = getDesignatedType(BaseType, D);
+  ExpectedLoc = Tok;
+}
+
 void PreferredTypeBuilder::enterFunctionArgument(
 SourceLocation Tok, llvm::function_ref ComputeType) {
   this->ComputeType = ComputeType;
@@ -4784,8 +4794,16 @@
 // in case of specializations. Since we might not have a decl for the
 // instantiation/specialization yet, e.g. dependent code.
 static RecordDecl *getAsRecordDecl(const QualType BaseType) {
-  if (auto *RD = BaseType->getAsRecordDecl())
+  if (auto *RD = BaseType->getAsRecordDecl()) {
+if (const auto *CTSD =
+llvm::dyn_cast(RD)) {
+  // Template might not be instantiated yet, fall back to primary template
+  // in such cases.
+  if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared)
+RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
+}
 return RD;
+  }
 
   if (const auto *TST = BaseType->getAs()) {
 if (const auto *TD = dyn_cast_or_null(
@@ -5754,25 +5772,37 @@
   return QualType();
 }
 
-void Sema::CodeCompleteDesignator(const QualType 

[PATCH] D96056: [clang][cli] Generate and round-trip CodeGen options

2021-02-04 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: Bigcheese, dexonsmith.
Herald added a subscriber: dang.
jansvoboda11 requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

This patch implements generation of remaining codegen options and tests it by 
performing parse-generate-parse round trip.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96056

Files:
  clang/include/clang/Basic/XRayInstr.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Basic/XRayInstr.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  llvm/include/llvm/Option/OptParser.td

Index: llvm/include/llvm/Option/OptParser.td
===
--- llvm/include/llvm/Option/OptParser.td
+++ llvm/include/llvm/Option/OptParser.td
@@ -175,7 +175,7 @@
 class MarshallingInfoStringInt
   : MarshallingInfo {
   code Normalizer = "normalizeStringIntegral<"#type#">";
-  code Denormalizer = "denormalizeString";
+  code Denormalizer = "denormalizeString<"#type#">";
 }
 
 class MarshallingInfoStringVector
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -54,6 +54,7 @@
 #include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
@@ -620,14 +621,17 @@
   // Run the first parse on the original arguments with dummy options and
   // diagnostics.
   SwapOpts(Res);
-  if (!Parse(Res, OriginalArgs, DummyDiags)) {
+  if (!Parse(Res, OriginalArgs, DummyDiags) ||
+  DummyDiags.getNumWarnings() != 0) {
 // If the first parse did not succeed, it must be user mistake (invalid
 // command line arguments). We won't be able to generate arguments that
 // would reproduce the same result. Let's fail again with the original
 // options and diagnostics, so all side-effects of parsing are visible.
+unsigned NumWarningsBefore = Diags.getNumWarnings();
 SwapOpts(Res);
-if (!Parse(Res, OriginalArgs, Diags))
-  return false;
+auto Success = Parse(Res, OriginalArgs, Diags);
+if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
+  return Success;
 
 // Parse with original options and diagnostics succeeded even though it
 // shouldn't have. Something is off.
@@ -744,16 +748,11 @@
 
 static void getAllNoBuiltinFuncValues(ArgList ,
   std::vector ) {
-  SmallVector Values;
-  for (const auto  : Args) {
-const Option  = Arg->getOption();
-if (O.matches(options::OPT_fno_builtin_)) {
-  const char *FuncName = Arg->getValue();
-  if (Builtin::Context::isBuiltinFunc(FuncName))
-Values.push_back(FuncName);
-}
-  }
-  Funcs.insert(Funcs.end(), Values.begin(), Values.end());
+  std::vector Values = Args.getAllArgValues(OPT_fno_builtin_);
+  auto BuiltinEnd = llvm::partition(Values, [](const std::string FuncName) {
+return Builtin::Context::isBuiltinFunc(FuncName);
+  });
+  Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
 }
 
 static void GenerateAnalyzerArgs(AnalyzerOptions ,
@@ -1234,6 +1233,15 @@
   }
 }
 
+static std::string serializeXRayInstrumentationBundle(const XRayInstrSet ) {
+  llvm::SmallVector BundleParts;
+  serializeXRayInstrValue(S, BundleParts);
+  std::string Buffer;
+  llvm::raw_string_ostream OS(Buffer);
+  llvm::interleave(BundleParts, OS, [](StringRef Part) { OS << Part; }, ",");
+  return OS.str();
+}
+
 // Set the profile kind using fprofile-instrument-use-path.
 static void setPGOUseInstrumentor(CodeGenOptions ,
   const Twine ) {
@@ -1255,12 +1263,258 @@
 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
 }
 
-bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions , ArgList ,
-  InputKind IK,
-  DiagnosticsEngine ,
-  const llvm::Triple ,
-  const std::string ,
-  const LangOptions ) {
+void CompilerInvocation::GenerateCodeGenArgs(
+const CodeGenOptions , SmallVectorImpl ,
+StringAllocator SA, const llvm::Triple , const std::string ,
+const LangOptions *LangOpts) {
+  const CodeGenOptions  = Opts;
+
+  if (Opts.OptimizationLevel == 0)
+GenerateArg(Args, OPT_O0, SA);
+  else
+GenerateArg(Args, OPT_O, Twine(Opts.OptimizationLevel), SA);
+
+#define CODEGEN_OPTION_WITH_MARSHALLING(   \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, 

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

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

@vsavchenko, after some experimentation, I found out that handling 
reinterpret_cast will be a real pain. Consider the following:

  struct Base {
int field;
  };
  
  struct Derived : public Base {};
  
  struct DoubleDerived : public Derived {};
  
  struct Some {};
  
  void f() {
int DoubleDerived::* ddf = ::field;
int Base::* bf = reinterpret_cast(reinterpret_cast(reinterpret_cast(ddf)));
int Some::* sf = reinterpret_cast(ddf);
Base base;
base.*bf;
  }

The definition of `bf` can be handled I guess by manually discovering when to 
insert a sub-class or when to remove. It will require a bit of code but I guess 
is doable.
As for the next one, also it has to be manually worked out whether it makes 
sense to process this statement further and add a node to the Exploded Graph. 
For the example I gave I don't think it makes a lot of sense. Multiple 
inheritance will make the task a lot worse as far as I can tell.
Should I try to achieve this in another commit? What are your thoughts on this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95877

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


[PATCH] D95745: Support unwinding from inline assembly

2021-02-04 Thread Paul via Phabricator via cfe-commits
cynecx updated this revision to Diff 321479.
cynecx added a comment.

clang-format changes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95745

Files:
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/Sema/SemaStmtAsm.cpp
  llvm/bindings/go/llvm/ir.go
  llvm/include/llvm-c/Core.h
  llvm/include/llvm/Bitcode/LLVMBitCodes.h
  llvm/include/llvm/IR/InlineAsm.h
  llvm/lib/AsmParser/LLParser.cpp
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h
  llvm/lib/IR/AsmWriter.cpp
  llvm/lib/IR/ConstantsContext.h
  llvm/lib/IR/Core.cpp
  llvm/lib/IR/InlineAsm.cpp
  llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
  llvm/lib/Transforms/Utils/InlineFunction.cpp

Index: llvm/lib/Transforms/Utils/InlineFunction.cpp
===
--- llvm/lib/Transforms/Utils/InlineFunction.cpp
+++ llvm/lib/Transforms/Utils/InlineFunction.cpp
@@ -28,7 +28,6 @@
 #include "llvm/Analysis/EHPersonalities.h"
 #include "llvm/Analysis/InstructionSimplify.h"
 #include "llvm/Analysis/ProfileSummaryInfo.h"
-#include "llvm/Transforms/Utils/Local.h"
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Analysis/VectorUtils.h"
 #include "llvm/IR/Argument.h"
@@ -44,6 +43,7 @@
 #include "llvm/IR/Dominators.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/InlineAsm.h"
 #include "llvm/IR/InstrTypes.h"
 #include "llvm/IR/Instruction.h"
 #include "llvm/IR/Instructions.h"
@@ -61,6 +61,7 @@
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
 #include "llvm/Transforms/Utils/Cloning.h"
+#include "llvm/Transforms/Utils/Local.h"
 #include "llvm/Transforms/Utils/ValueMapper.h"
 #include 
 #include 
@@ -543,9 +544,16 @@
 // instructions require no special handling.
 CallInst *CI = dyn_cast(I);
 
-if (!CI || CI->doesNotThrow() || CI->isInlineAsm())
+if (!CI || CI->doesNotThrow())
   continue;
 
+if (CI->isInlineAsm()) {
+  InlineAsm *IA = cast(CI->getCalledOperand());
+  if (!IA->canThrow()) {
+continue;
+  }
+}
+
 // We do not need to (and in fact, cannot) convert possibly throwing calls
 // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into
 // invokes.  The caller's "segment" of the deoptimization continuation
Index: llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
===
--- llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
+++ llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
@@ -39,6 +39,7 @@
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/GlobalVariable.h"
+#include "llvm/IR/InlineAsm.h"
 #include "llvm/IR/InstrTypes.h"
 #include "llvm/IR/Instruction.h"
 #include "llvm/IR/Instructions.h"
@@ -2139,9 +2140,13 @@
   }
 
   if (isa(Callee) && !Call.doesNotThrow()) {
-// Inline asm calls cannot throw - mark them 'nounwind'.
-Call.setDoesNotThrow();
-Changed = true;
+InlineAsm *IA = cast(Callee);
+if (!IA->canThrow()) {
+  // Normal inline asm calls cannot throw - mark them
+  // 'nounwind'.
+  Call.setDoesNotThrow();
+  Changed = true;
+}
   }
 
   // Try to optimize the call if possible, we require DataLayout for most of
Index: llvm/lib/IR/InlineAsm.cpp
===
--- llvm/lib/IR/InlineAsm.cpp
+++ llvm/lib/IR/InlineAsm.cpp
@@ -29,11 +29,11 @@
 
 InlineAsm::InlineAsm(FunctionType *FTy, const std::string ,
  const std::string , bool hasSideEffects,
- bool isAlignStack, AsmDialect asmDialect)
+ bool isAlignStack, AsmDialect asmDialect, bool canThrow)
 : Value(PointerType::getUnqual(FTy), Value::InlineAsmVal),
   AsmString(asmString), Constraints(constraints), FTy(FTy),
   HasSideEffects(hasSideEffects), IsAlignStack(isAlignStack),
-  Dialect(asmDialect) {
+  Dialect(asmDialect), CanThrow(canThrow) {
   // Do various checks on the constraint string and type.
   assert(Verify(getFunctionType(), constraints) &&
  "Function type not legal for constraints!");
@@ -41,9 +41,10 @@
 
 InlineAsm *InlineAsm::get(FunctionType *FTy, StringRef AsmString,
   StringRef Constraints, bool hasSideEffects,
-  bool isAlignStack, AsmDialect asmDialect) {
+  bool isAlignStack, AsmDialect asmDialect,
+  bool canThrow) {
   InlineAsmKeyType Key(AsmString, Constraints, FTy, hasSideEffects,
-   isAlignStack, asmDialect);
+   isAlignStack, asmDialect, 

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

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

Updated to use new function


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95877

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

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

[PATCH] D95396: Improve static_assert/_Static_assert diagnostics

2021-02-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman marked an inline comment as not done.
aaron.ballman added inline comments.



Comment at: clang/lib/Parse/ParseDeclCXX.cpp:874-876
+if (!getLangOpts().CPlusPlus)
+  Diag(Tok, diag::warn_cxx_static_assert_in_c)
+  << FixItHint::CreateReplacement(Tok.getLocation(), "_Static_assert");

aaron.ballman wrote:
> rsmith wrote:
> > I don't think this diagnostic is useful as-is: on Windows, including 
> > `` doesn't help because it doesn't `#define static_assert`. And 
> > people hitting this also can't switch to using `_Static_assert`, because 
> > MSVC doesn't provide it, only `static_assert`.
> > 
> > If we want to warn here, we could perhaps check whether `` has 
> > been included, but getting that check correct across PCH / modules is not 
> > straightforward. (If we knew what include guard the CRT's `assert.h` used 
> > (if any), I guess we could check whether that's defined, but that'd be a 
> > bit of a hack.) But I'm somewhat inclined to think we don't have a good way 
> > to distinguish between the good cases and the bad ones, so we shouldn't 
> > warn. Hopefully MS will fix their CRT at some point and we can stop 
> > providing this compatibility hack entirely (or start warning on it by 
> > default).
> Are you sure they don't support `_Static_assert` yet? I seem to be able to 
> use it fine: https://godbolt.org/z/vG47he
> 
> That said, this does appear to be only available in newer versions of MSVC, 
> so perhaps you're correct about the diagnostic being a bit unhelpful. My 
> primary concern is that use of `static_assert` in C is a nonconforming 
> extension and we default to `-fms-compatibility` on Windows when Clang is 
> built by MSVC. So it's not difficult to accidentally run into this, but the 
> only warning we give on it with `-Weverything -pedantic` is how it's not 
> compatible with C++98.
> 
> WDYT?
I suppose one option would be to look at what version of MSVC we're trying to 
be compatible with to see if that's a version that supports `/std:c11` and only 
emit this diagnostic in that case, but tbh, that feels like it'll lead to 
confusing diagnostic behavior (esp given that we default to ms compatibility 
mode silently when you build Clang with MSVC on Windows).

Given that MSVC does support `_Static_assert` when you enable C11 or later 
language mode, I'm inclined to warn on this construct by default.

WDYT?


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

https://reviews.llvm.org/D95396

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


[PATCH] D96054: Support unwinding from inline assembly

2021-02-04 Thread Paul via Phabricator via cfe-commits
cynecx created this revision.
cynecx requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96054

Files:
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/Sema/SemaStmtAsm.cpp

Index: clang/lib/Sema/SemaStmtAsm.cpp
===
--- clang/lib/Sema/SemaStmtAsm.cpp
+++ clang/lib/Sema/SemaStmtAsm.cpp
@@ -228,7 +228,7 @@
 StringRef Clobber = Clobbers[i]->getString();
 // We only check registers, therefore we don't check cc and memory
 // clobbers
-if (Clobber == "cc" || Clobber == "memory")
+if (Clobber == "cc" || Clobber == "memory" || Clobber == "unwind")
   continue;
 Clobber = Target.getNormalizedGCCRegisterName(Clobber, true);
 // Go over the output's registers we collected
Index: clang/lib/CodeGen/CGStmt.cpp
===
--- clang/lib/CodeGen/CGStmt.cpp
+++ clang/lib/CodeGen/CGStmt.cpp
@@ -2115,13 +2115,15 @@
 }
 
 static void UpdateAsmCallInst(llvm::CallBase , bool HasSideEffect,
-  bool ReadOnly, bool ReadNone, bool NoMerge,
-  const AsmStmt ,
+  bool HasUnwindClobber, bool ReadOnly,
+  bool ReadNone, bool NoMerge, const AsmStmt ,
   const std::vector ,
   CodeGenFunction ,
   std::vector ) {
-  Result.addAttribute(llvm::AttributeList::FunctionIndex,
-  llvm::Attribute::NoUnwind);
+  if (!HasUnwindClobber)
+Result.addAttribute(llvm::AttributeList::FunctionIndex,
+llvm::Attribute::NoUnwind);
+
   if (NoMerge)
 Result.addAttribute(llvm::AttributeList::FunctionIndex,
 llvm::Attribute::NoMerge);
@@ -2468,13 +2470,18 @@
   }
   Constraints += InOutConstraints;
 
+  bool HasUnwindClobber = false;
+
   // Clobbers
   for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
 StringRef Clobber = S.getClobber(i);
 
 if (Clobber == "memory")
   ReadOnly = ReadNone = false;
-else if (Clobber != "cc") {
+else if (Clobber == "unwind") {
+  HasUnwindClobber = true;
+  continue;
+} else if (Clobber != "cc") {
   Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
   if (CGM.getCodeGenOpts().StackClashProtector &&
   getTarget().isSPRegName(Clobber)) {
@@ -2508,6 +2515,9 @@
 Constraints += '}';
   }
 
+  assert(!(HasUnwindClobber && IsGCCAsmGoto) &&
+ "unwind clobber can't be used with asm goto");
+
   // Add machine specific clobbers
   std::string MachineClobbers = getTarget().getClobbers();
   if (!MachineClobbers.empty()) {
@@ -2530,23 +2540,28 @@
   bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
   llvm::InlineAsm::AsmDialect AsmDialect = isa() ?
 llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
-  llvm::InlineAsm *IA =
-llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
- /* IsAlignStack */ false, AsmDialect);
+  llvm::InlineAsm *IA = llvm::InlineAsm::get(
+  FTy, AsmString, Constraints, HasSideEffect,
+  /* IsAlignStack */ false, AsmDialect, HasUnwindClobber);
   std::vector RegResults;
   if (IsGCCAsmGoto) {
 llvm::CallBrInst *Result =
 Builder.CreateCallBr(IA, Fallthrough, Transfer, Args);
 EmitBlock(Fallthrough);
-UpdateAsmCallInst(cast(*Result), HasSideEffect, ReadOnly,
-  ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes,
-  *this, RegResults);
+UpdateAsmCallInst(cast(*Result), HasSideEffect, false,
+  ReadOnly, ReadNone, InNoMergeAttributedStmt, S,
+  ResultRegTypes, *this, RegResults);
+  } else if (HasUnwindClobber) {
+llvm::CallBase *Result = EmitCallOrInvoke(IA, Args, "");
+UpdateAsmCallInst(*Result, HasSideEffect, true, ReadOnly, ReadNone,
+  InNoMergeAttributedStmt, S, ResultRegTypes, *this,
+  RegResults);
   } else {
 llvm::CallInst *Result =
 Builder.CreateCall(IA, Args, getBundlesForFunclet(IA));
-UpdateAsmCallInst(cast(*Result), HasSideEffect, ReadOnly,
-  ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes,
-  *this, RegResults);
+UpdateAsmCallInst(cast(*Result), HasSideEffect, false,
+  ReadOnly, ReadNone, InNoMergeAttributedStmt, S,
+  ResultRegTypes, *this, RegResults);
   }
 
   assert(RegResults.size() == ResultRegTypes.size());
Index: clang/lib/Basic/TargetInfo.cpp
===
--- clang/lib/Basic/TargetInfo.cpp
+++ clang/lib/Basic/TargetInfo.cpp
@@ -475,8 +475,8 @@
 /// a valid clobber in an 

[PATCH] D96049: [Timer] On macOS count number of executed instructions

2021-02-04 Thread Alex Hoppen via Phabricator via cfe-commits
ahoppen updated this revision to Diff 321467.
ahoppen added a comment.

Fixed an issue caused by me using an old revions as the commit's base.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96049

Files:
  
clang-tools-extra/test/clang-tidy/infrastructure/clang-tidy-store-check-profile-one-tu.cpp
  llvm/CMakeLists.txt
  llvm/include/llvm/Config/config.h.cmake
  llvm/include/llvm/Support/Timer.h
  llvm/lib/Support/Timer.cpp

Index: llvm/lib/Support/Timer.cpp
===
--- llvm/lib/Support/Timer.cpp
+++ llvm/lib/Support/Timer.cpp
@@ -13,6 +13,7 @@
 #include "llvm/Support/Timer.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/ADT/StringMap.h"
+#include "llvm/Config/config.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Format.h"
@@ -24,6 +25,14 @@
 #include "llvm/Support/raw_ostream.h"
 #include 
 
+#if HAVE_UNISTD_H
+#include 
+#endif
+
+#ifdef HAVE_PROC_PID_RUSAGE
+#include 
+#endif
+
 using namespace llvm;
 
 // This ugly hack is brought to you courtesy of constructor/destructor ordering
@@ -120,6 +129,17 @@
   return sys::Process::GetMallocUsage();
 }
 
+static uint64_t getCurInstructionsExecuted() {
+#if defined(HAVE_UNISTD_H) && defined(HAVE_PROC_PID_RUSAGE) && \
+defined(RUSAGE_INFO_V4)
+  struct rusage_info_v4 ru;
+  if (proc_pid_rusage(getpid(), RUSAGE_INFO_V4, (rusage_info_t *)) == 0) {
+return ru.ri_instructions;
+  }
+#endif
+  return 0;
+}
+
 TimeRecord TimeRecord::getCurrentTime(bool Start) {
   using Seconds = std::chrono::duration>;
   TimeRecord Result;
@@ -128,9 +148,11 @@
 
   if (Start) {
 Result.MemUsed = getMemUsage();
+Result.InstructionsExecuted = getCurInstructionsExecuted();
 sys::Process::GetTimeUsage(now, user, sys);
   } else {
 sys::Process::GetTimeUsage(now, user, sys);
+Result.InstructionsExecuted = getCurInstructionsExecuted();
 Result.MemUsed = getMemUsage();
   }
 
@@ -180,6 +202,8 @@
 
   if (Total.getMemUsed())
 OS << format("%9" PRId64 "  ", (int64_t)getMemUsed());
+  if (Total.getInstructionsExecuted())
+OS << format("%9" PRId64 "  ", (int64_t)getInstructionsExecuted());
 }
 
 
@@ -339,6 +363,8 @@
   OS << "   ---Wall Time---";
   if (Total.getMemUsed())
 OS << "  ---Mem---";
+  if (Total.getInstructionsExecuted())
+OS << "  ---Instr---";
   OS << "  --- Name ---\n";
 
   // Loop through all of the timing data, printing it out.
@@ -433,6 +459,10 @@
   OS << delim;
   printJSONValue(OS, R, ".mem", T.getMemUsed());
 }
+if (T.getInstructionsExecuted()) {
+  OS << delim;
+  printJSONValue(OS, R, ".instr", T.getInstructionsExecuted());
+}
   }
   TimersToPrint.clear();
   return delim;
Index: llvm/include/llvm/Support/Timer.h
===
--- llvm/include/llvm/Support/Timer.h
+++ llvm/include/llvm/Support/Timer.h
@@ -24,12 +24,15 @@
 class raw_ostream;
 
 class TimeRecord {
-  double WallTime;   ///< Wall clock time elapsed in seconds.
-  double UserTime;   ///< User time elapsed.
-  double SystemTime; ///< System time elapsed.
-  ssize_t MemUsed;   ///< Memory allocated (in bytes).
+  double WallTime;   ///< Wall clock time elapsed in seconds.
+  double UserTime;   ///< User time elapsed.
+  double SystemTime; ///< System time elapsed.
+  ssize_t MemUsed;   ///< Memory allocated (in bytes).
+  uint64_t InstructionsExecuted; ///< Number of instructions executed
 public:
-  TimeRecord() : WallTime(0), UserTime(0), SystemTime(0), MemUsed(0) {}
+  TimeRecord()
+  : WallTime(0), UserTime(0), SystemTime(0), MemUsed(0),
+InstructionsExecuted(0) {}
 
   /// Get the current time and memory usage.  If Start is true we get the memory
   /// usage before the time, otherwise we get time before memory usage.  This
@@ -42,6 +45,7 @@
   double getSystemTime() const { return SystemTime; }
   double getWallTime() const { return WallTime; }
   ssize_t getMemUsed() const { return MemUsed; }
+  uint64_t getInstructionsExecuted() const { return InstructionsExecuted; }
 
   bool operator<(const TimeRecord ) const {
 // Sort by Wall Time elapsed, as it is the only thing really accurate
@@ -49,16 +53,18 @@
   }
 
   void operator+=(const TimeRecord ) {
-WallTime   += RHS.WallTime;
-UserTime   += RHS.UserTime;
+WallTime += RHS.WallTime;
+UserTime += RHS.UserTime;
 SystemTime += RHS.SystemTime;
-MemUsed+= RHS.MemUsed;
+MemUsed += RHS.MemUsed;
+InstructionsExecuted += RHS.InstructionsExecuted;
   }
   void operator-=(const TimeRecord ) {
-WallTime   -= RHS.WallTime;
-UserTime   -= RHS.UserTime;
+WallTime -= RHS.WallTime;
+UserTime -= RHS.UserTime;
 SystemTime -= RHS.SystemTime;
-MemUsed-= RHS.MemUsed;
+MemUsed -= 

[PATCH] D95691: Implement P2173 for attributes on lambdas

2021-02-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D95691#2540667 , @rjmccall wrote:

> In D95691#2540619 , @rsmith wrote:
>
>> In D95691#2540450 , @rjmccall wrote:
>>
>>> The warning is a bit weird.  If we don't think it's certain that the 
>>> committee will adopt this syntax, I don't think we should add this patch at 
>>> all; it is not really acceptable to add it and then treat it as a Clang 
>>> extension if the committee rejects it.  If we do think it's certain, we 
>>> should go ahead and consider this a feature of the next major standard.
>>
>> I think it's quite unlikely that the committee would reject the feature at 
>> this stage. Seems OK to me to jump the gun slightly and call this a C++23 
>> extension.
>
> SGTM, then.

That works for me as well -- I'd also be very surprised if the committee 
rejected the feature at this point. When I originally worked on the patch, the 
paper hadn't started its polling in Evolution yet and so it was less clear how 
it would be received.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95691

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


[PATCH] D95691: Implement P2173 for attributes on lambdas

2021-02-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman updated this revision to Diff 321465.
aaron.ballman set the repository for this revision to rG LLVM Github Monorepo.
aaron.ballman added a comment.
Herald added a project: clang.

Updating based on review feedback.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95691

Files:
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/lib/Parse/ParseExprCXX.cpp
  clang/test/AST/ast-dump-lambda.cpp
  clang/test/Parser/cxx0x-lambda-expressions.cpp

Index: clang/test/Parser/cxx0x-lambda-expressions.cpp
===
--- clang/test/Parser/cxx0x-lambda-expressions.cpp
+++ clang/test/Parser/cxx0x-lambda-expressions.cpp
@@ -101,7 +101,6 @@
   }
 
   void attributes() {
-[] [[]] {}; // expected-error {{lambda requires '()' before attribute specifier}}
 [] __attribute__((noreturn)) {}; // expected-error {{lambda requires '()' before attribute specifier}}
 []() [[]]
   mutable {}; // expected-error {{expected body of lambda expression}}
@@ -116,6 +115,14 @@
 []() __attribute__((noreturn)) mutable { while(1); };
 []() mutable
   __attribute__((noreturn)) { while(1); }; // expected-error {{expected body of lambda expression}}
+
+// Testing support for P2173 on adding attributes to the declaration
+// rather than the type.
+[] [[]] () {}; // expected-warning {{an attribute specifier sequence in this position is a C++2b extension}}
+#if __cplusplus > 201703L
+[]  [[]] () {};  // expected-warning {{an attribute specifier sequence in this position is a C++2b extension}}
+#endif
+[] [[]] {}; // expected-warning {{an attribute specifier sequence in this position is a C++2b extension}}
   }
 };
 
Index: clang/test/AST/ast-dump-lambda.cpp
===
--- clang/test/AST/ast-dump-lambda.cpp
+++ clang/test/AST/ast-dump-lambda.cpp
@@ -33,13 +33,14 @@
   []() mutable {};
   []() noexcept {};
   []() -> int { return 0; };
+  [] [[noreturn]] () {};
 }
 // CHECK:Dumping test:
-// CHECK-NEXT:FunctionTemplateDecl {{.*}} <{{.*}}ast-dump-lambda.cpp:15:1, line:36:1> line:15:32{{( imported)?}} test
+// CHECK-NEXT:FunctionTemplateDecl {{.*}} <{{.*}}ast-dump-lambda.cpp:15:1, line:37:1> line:15:32{{( imported)?}} test
 // CHECK-NEXT:|-TemplateTypeParmDecl {{.*}}  col:23{{( imported)?}} referenced typename depth 0 index 0 ... Ts
-// CHECK-NEXT:`-FunctionDecl {{.*}}  line:15:32{{( imported)?}} test 'void (Ts...)'
+// CHECK-NEXT:`-FunctionDecl {{.*}}  line:15:32{{( imported)?}} test 'void (Ts...)'
 // CHECK-NEXT:  |-ParmVarDecl {{.*}}  col:43{{( imported)?}} referenced a 'Ts...' pack
-// CHECK-NEXT:  `-CompoundStmt {{.*}} 
+// CHECK-NEXT:  `-CompoundStmt {{.*}} 
 // CHECK-NEXT:|-DeclStmt {{.*}} 
 // CHECK-NEXT:| `-CXXRecordDecl {{.*}}  line:16:10{{( imported)?}}{{( )?}} struct V definition
 // CHECK-NEXT:|   |-DefinitionData empty aggregate standard_layout trivially_copyable pod trivial literal has_constexpr_non_copy_move_ctor can_const_default_init
@@ -275,7 +276,25 @@
 // CHECK-NEXT:| | |-CXXConversionDecl {{.*}}  col:3{{( imported)?}} implicit constexpr operator auto (*)() noexcept 'auto (*() const noexcept)() noexcept' inline
 // CHECK-NEXT:| | `-CXXMethodDecl {{.*}}  col:3{{( imported)?}} implicit __invoke 'auto () noexcept' static inline
 // CHECK-NEXT:| `-CompoundStmt {{.*}} 
-// CHECK-NEXT:`-LambdaExpr {{.*}}  '(lambda at {{.*}}ast-dump-lambda.cpp:35:3)'
+// CHECK-NEXT:|-LambdaExpr {{.*}}  '(lambda at {{.*}}ast-dump-lambda.cpp:35:3)'
+// CHECK-NEXT:| |-CXXRecordDecl {{.*}}  col:3{{( imported)?}} implicit{{( )?}} class definition
+// CHECK-NEXT:| | |-DefinitionData lambda empty standard_layout trivially_copyable literal can_const_default_init
+// CHECK-NEXT:| | | |-DefaultConstructor defaulted_is_constexpr
+// CHECK-NEXT:| | | |-CopyConstructor simple trivial has_const_param needs_implicit implicit_has_const_param
+// CHECK-NEXT:| | | |-MoveConstructor exists simple trivial needs_implicit
+// CHECK-NEXT:| | | |-CopyAssignment trivial has_const_param needs_implicit implicit_has_const_param
+// CHECK-NEXT:| | | |-MoveAssignment
+// CHECK-NEXT:| | | `-Destructor simple irrelevant trivial needs_implicit
+// CHECK-NEXT:| | |-CXXMethodDecl {{.*}}  col:3{{( imported)?}} operator() 'auto () const -> int' inline
+// CHECK-NEXT:| | | `-CompoundStmt {{.*}} 
+// CHECK-NEXT:| | |   `-ReturnStmt {{.*}} 
+// CHECK-NEXT:| | | `-IntegerLiteral {{.*}}  'int' 0
+// CHECK-NEXT:| | |-CXXConversionDecl {{.*}}  col:3{{( imported)?}} implicit constexpr operator int (*)() 'auto (*() const noexcept)() -> int' inline
+// CHECK-NEXT:| | `-CXXMethodDecl {{.*}}  col:3{{( imported)?}} implicit __invoke 'auto () -> int' static inline
+// CHECK-NEXT:| `-CompoundStmt {{.*}} 

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

2021-02-04 Thread Michael Spencer via Phabricator via cfe-commits
Bigcheese added inline comments.



Comment at: clang/docs/InternalsManual.rst:711
+required for parsing or generating the command line argument.
+
+**Positive Flag**

You should create a separate section here for listing the classes.



Comment at: clang/docs/InternalsManual.rst:770
+The key path defaults to an empty ``std::vector``. Values 
specified
+with each appearance of the option on command line are appended to the vector.
+





Comment at: clang/docs/InternalsManual.rst:843
+implementation is still possible.
+
 The Lexer and Preprocessor Library

Past this you should add a section providing instructions on how to actually 
add marshaling for an option, and cover what to do if the automatic 
infrastructure isn't enough.



Comment at: clang/docs/InternalsManual.rst:590
+the driver options in ``clang/Driver/Options.td``. The information making up an
+option definition include the name and prefix (for example ``-std=``), form and
+position of the option value, help text, aliases and more. Each option may




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95790

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


[PATCH] D96053: [clang] add new unwind inline asm clobber which lowers to throwable inline assembly

2021-02-04 Thread Paul via Phabricator via cfe-commits
cynecx created this revision.
cynecx requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96053

Files:
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/Sema/SemaStmtAsm.cpp

Index: clang/lib/Sema/SemaStmtAsm.cpp
===
--- clang/lib/Sema/SemaStmtAsm.cpp
+++ clang/lib/Sema/SemaStmtAsm.cpp
@@ -228,7 +228,7 @@
 StringRef Clobber = Clobbers[i]->getString();
 // We only check registers, therefore we don't check cc and memory
 // clobbers
-if (Clobber == "cc" || Clobber == "memory")
+if (Clobber == "cc" || Clobber == "memory" || Clobber == "unwind")
   continue;
 Clobber = Target.getNormalizedGCCRegisterName(Clobber, true);
 // Go over the output's registers we collected
Index: clang/lib/CodeGen/CGStmt.cpp
===
--- clang/lib/CodeGen/CGStmt.cpp
+++ clang/lib/CodeGen/CGStmt.cpp
@@ -2115,13 +2115,15 @@
 }
 
 static void UpdateAsmCallInst(llvm::CallBase , bool HasSideEffect,
-  bool ReadOnly, bool ReadNone, bool NoMerge,
-  const AsmStmt ,
+  bool HasUnwindClobber, bool ReadOnly,
+  bool ReadNone, bool NoMerge, const AsmStmt ,
   const std::vector ,
   CodeGenFunction ,
   std::vector ) {
-  Result.addAttribute(llvm::AttributeList::FunctionIndex,
-  llvm::Attribute::NoUnwind);
+  if (!HasUnwindClobber)
+Result.addAttribute(llvm::AttributeList::FunctionIndex,
+llvm::Attribute::NoUnwind);
+
   if (NoMerge)
 Result.addAttribute(llvm::AttributeList::FunctionIndex,
 llvm::Attribute::NoMerge);
@@ -2468,13 +2470,18 @@
   }
   Constraints += InOutConstraints;
 
+  bool HasUnwindClobber = false;
+
   // Clobbers
   for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
 StringRef Clobber = S.getClobber(i);
 
 if (Clobber == "memory")
   ReadOnly = ReadNone = false;
-else if (Clobber != "cc") {
+else if (Clobber == "unwind") {
+  HasUnwindClobber = true;
+  continue;
+} else if (Clobber != "cc") {
   Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
   if (CGM.getCodeGenOpts().StackClashProtector &&
   getTarget().isSPRegName(Clobber)) {
@@ -2508,6 +2515,9 @@
 Constraints += '}';
   }
 
+  assert(!(HasUnwindClobber && IsGCCAsmGoto) &&
+ "unwind clobber can't be used with asm goto");
+
   // Add machine specific clobbers
   std::string MachineClobbers = getTarget().getClobbers();
   if (!MachineClobbers.empty()) {
@@ -2530,23 +2540,28 @@
   bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
   llvm::InlineAsm::AsmDialect AsmDialect = isa() ?
 llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
-  llvm::InlineAsm *IA =
-llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
- /* IsAlignStack */ false, AsmDialect);
+  llvm::InlineAsm *IA = llvm::InlineAsm::get(
+  FTy, AsmString, Constraints, HasSideEffect,
+  /* IsAlignStack */ false, AsmDialect, HasUnwindClobber);
   std::vector RegResults;
   if (IsGCCAsmGoto) {
 llvm::CallBrInst *Result =
 Builder.CreateCallBr(IA, Fallthrough, Transfer, Args);
 EmitBlock(Fallthrough);
-UpdateAsmCallInst(cast(*Result), HasSideEffect, ReadOnly,
-  ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes,
-  *this, RegResults);
+UpdateAsmCallInst(cast(*Result), HasSideEffect, false,
+  ReadOnly, ReadNone, InNoMergeAttributedStmt, S,
+  ResultRegTypes, *this, RegResults);
+  } else if (HasUnwindClobber) {
+llvm::CallBase *Result = EmitCallOrInvoke(IA, Args, "");
+UpdateAsmCallInst(*Result, HasSideEffect, true, ReadOnly, ReadNone,
+  InNoMergeAttributedStmt, S, ResultRegTypes, *this,
+  RegResults);
   } else {
 llvm::CallInst *Result =
 Builder.CreateCall(IA, Args, getBundlesForFunclet(IA));
-UpdateAsmCallInst(cast(*Result), HasSideEffect, ReadOnly,
-  ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes,
-  *this, RegResults);
+UpdateAsmCallInst(cast(*Result), HasSideEffect, false,
+  ReadOnly, ReadNone, InNoMergeAttributedStmt, S,
+  ResultRegTypes, *this, RegResults);
   }
 
   assert(RegResults.size() == ResultRegTypes.size());
Index: clang/lib/Basic/TargetInfo.cpp
===
--- clang/lib/Basic/TargetInfo.cpp
+++ clang/lib/Basic/TargetInfo.cpp
@@ -475,8 +475,8 @@
 /// a valid clobber in an 

[PATCH] D96036: [clang][codegen] Remember string used to create llvm::Regex for optimization remarks

2021-02-04 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith accepted this revision.
dexonsmith added a comment.

LGTM! I also have a couple of optional suggestions to consider.




Comment at: clang/include/clang/Basic/CodeGenOptions.h:286
+
+bool isEnabled() const { return Regex != nullptr; }
+

This could also be:
```
explicit operator bool() const { return Regex != nullptr }
```




Comment at: clang/include/clang/Basic/CodeGenOptions.h:288-291
+bool match(StringRef String, SmallVectorImpl *Matches = nullptr,
+   std::string *Error = nullptr) const {
+  return isEnabled() && Regex->match(String, Matches, Error);
+}

Another option would be:
```
llvm::Regex *operator->() const { return Regex.get(); }
```
treating `RemarkPattern` as a pointer wrapper (that also knows the 
`std::string`). WDYT?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96036

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


[PATCH] D96052: [clang] add new unwind inline asm clobber which lowers to throwable inline assembly

2021-02-04 Thread Paul via Phabricator via cfe-commits
cynecx created this revision.
cynecx requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96052

Files:
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/Sema/SemaStmtAsm.cpp

Index: clang/lib/Sema/SemaStmtAsm.cpp
===
--- clang/lib/Sema/SemaStmtAsm.cpp
+++ clang/lib/Sema/SemaStmtAsm.cpp
@@ -228,7 +228,7 @@
 StringRef Clobber = Clobbers[i]->getString();
 // We only check registers, therefore we don't check cc and memory
 // clobbers
-if (Clobber == "cc" || Clobber == "memory")
+if (Clobber == "cc" || Clobber == "memory" || Clobber == "unwind")
   continue;
 Clobber = Target.getNormalizedGCCRegisterName(Clobber, true);
 // Go over the output's registers we collected
Index: clang/lib/CodeGen/CGStmt.cpp
===
--- clang/lib/CodeGen/CGStmt.cpp
+++ clang/lib/CodeGen/CGStmt.cpp
@@ -2115,13 +2115,15 @@
 }
 
 static void UpdateAsmCallInst(llvm::CallBase , bool HasSideEffect,
-  bool ReadOnly, bool ReadNone, bool NoMerge,
-  const AsmStmt ,
+  bool HasUnwindClobber, bool ReadOnly,
+  bool ReadNone, bool NoMerge, const AsmStmt ,
   const std::vector ,
   CodeGenFunction ,
   std::vector ) {
-  Result.addAttribute(llvm::AttributeList::FunctionIndex,
-  llvm::Attribute::NoUnwind);
+  if (!HasUnwindClobber)
+Result.addAttribute(llvm::AttributeList::FunctionIndex,
+llvm::Attribute::NoUnwind);
+
   if (NoMerge)
 Result.addAttribute(llvm::AttributeList::FunctionIndex,
 llvm::Attribute::NoMerge);
@@ -2468,13 +2470,18 @@
   }
   Constraints += InOutConstraints;
 
+  bool HasUnwindClobber = false;
+
   // Clobbers
   for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
 StringRef Clobber = S.getClobber(i);
 
 if (Clobber == "memory")
   ReadOnly = ReadNone = false;
-else if (Clobber != "cc") {
+else if (Clobber == "unwind") {
+  HasUnwindClobber = true;
+  continue;
+} else if (Clobber != "cc") {
   Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
   if (CGM.getCodeGenOpts().StackClashProtector &&
   getTarget().isSPRegName(Clobber)) {
@@ -2508,6 +2515,9 @@
 Constraints += '}';
   }
 
+  assert(!(HasUnwindClobber && IsGCCAsmGoto) &&
+ "unwind clobber can't be used with asm goto");
+
   // Add machine specific clobbers
   std::string MachineClobbers = getTarget().getClobbers();
   if (!MachineClobbers.empty()) {
@@ -2530,23 +2540,28 @@
   bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
   llvm::InlineAsm::AsmDialect AsmDialect = isa() ?
 llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
-  llvm::InlineAsm *IA =
-llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
- /* IsAlignStack */ false, AsmDialect);
+  llvm::InlineAsm *IA = llvm::InlineAsm::get(
+  FTy, AsmString, Constraints, HasSideEffect,
+  /* IsAlignStack */ false, AsmDialect, HasUnwindClobber);
   std::vector RegResults;
   if (IsGCCAsmGoto) {
 llvm::CallBrInst *Result =
 Builder.CreateCallBr(IA, Fallthrough, Transfer, Args);
 EmitBlock(Fallthrough);
-UpdateAsmCallInst(cast(*Result), HasSideEffect, ReadOnly,
-  ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes,
-  *this, RegResults);
+UpdateAsmCallInst(cast(*Result), HasSideEffect, false,
+  ReadOnly, ReadNone, InNoMergeAttributedStmt, S,
+  ResultRegTypes, *this, RegResults);
+  } else if (HasUnwindClobber) {
+llvm::CallBase *Result = EmitCallOrInvoke(IA, Args, "");
+UpdateAsmCallInst(*Result, HasSideEffect, true, ReadOnly, ReadNone,
+  InNoMergeAttributedStmt, S, ResultRegTypes, *this,
+  RegResults);
   } else {
 llvm::CallInst *Result =
 Builder.CreateCall(IA, Args, getBundlesForFunclet(IA));
-UpdateAsmCallInst(cast(*Result), HasSideEffect, ReadOnly,
-  ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes,
-  *this, RegResults);
+UpdateAsmCallInst(cast(*Result), HasSideEffect, false,
+  ReadOnly, ReadNone, InNoMergeAttributedStmt, S,
+  ResultRegTypes, *this, RegResults);
   }
 
   assert(RegResults.size() == ResultRegTypes.size());
Index: clang/lib/Basic/TargetInfo.cpp
===
--- clang/lib/Basic/TargetInfo.cpp
+++ clang/lib/Basic/TargetInfo.cpp
@@ -475,8 +475,8 @@
 /// a valid clobber in an 

[PATCH] D96051: [OpenCL] Support enum and typedef args in TableGen BIFs

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

Add enum and typedef argument support to `-fdeclare-opencl-builtins`,
which was the last major missing feature.

Adding the remaining missing builtins is left as future work.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96051

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/OpenCLBuiltins.td
  clang/lib/Sema/SemaLookup.cpp
  clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
  clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp

Index: clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
===
--- clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
+++ clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
@@ -715,6 +715,30 @@
 void BuiltinNameEmitter::EmitQualTypeFinder() {
   OS << R"(
 
+// Lookup an OpenCL enum type.
+static QualType getOpenCLEnumType(Sema , llvm::StringRef Name) {
+  LookupResult Result(S, (Name), SourceLocation(),
+  Sema::LookupTagName);
+  S.LookupName(Result, S.TUScope);
+  if (Result.empty()) {
+S.Diag(SourceLocation(), diag::err_opencl_type_not_found) << Name;
+return S.Context.VoidTy;
+  }
+  return S.Context.getEnumType(Result.getAsSingle());
+}
+
+// Lookup an OpenCL typedef type.
+static QualType getOpenCLTypedefType(Sema , llvm::StringRef Name) {
+  LookupResult Result(S, (Name), SourceLocation(),
+  Sema::LookupOrdinaryName);
+  S.LookupName(Result, S.TUScope);
+  if (Result.empty()) {
+S.Diag(SourceLocation(), diag::err_opencl_type_not_found) << Name;
+return S.Context.VoidTy;
+  }
+  return S.Context.getTypedefType(Result.getAsSingle());
+}
+
 // Convert an OpenCLTypeStruct type to a list of QualTypes.
 // Generic types represent multiple types and vector sizes, thus a vector
 // is returned. The conversion is done in two steps:
@@ -723,8 +747,9 @@
 // or a single scalar type for non generic types.
 // Step 2: Qualifiers and other type properties such as vector size are
 // applied.
-static void OCL2Qual(ASTContext , const OpenCLTypeStruct ,
+static void OCL2Qual(Sema , const OpenCLTypeStruct ,
  llvm::SmallVectorImpl ) {
+  ASTContext  = S.Context;
   // Number of scalar types in the GenType.
   unsigned GenTypeNumTypes;
   // Pointer to the list of vector sizes for the GenType.
Index: clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
===
--- clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -34,6 +34,9 @@
 typedef uint uint4 __attribute__((ext_vector_type(4)));
 typedef long long2 __attribute__((ext_vector_type(2)));
 
+typedef uint cl_mem_fence_flags;
+#define CLK_GLOBAL_MEM_FENCE   0x02
+
 // Enable extensions that are enabled in opencl-c-base.h.
 #if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 200)
 #define cl_khr_subgroup_ballot 1
@@ -52,6 +55,18 @@
   atom_cmpxchg((volatile __global unsigned int *)global_p, ui, ui);
 }
 
+// Only test enum arguments when the base header is included, because we need
+// the enum declarations.
+#if !defined(NO_HEADER) && (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 200)
+kernel void test_enum_args(volatile global atomic_int *global_p, global int* expected) {
+  int desired;
+  atomic_compare_exchange_strong_explicit(global_p, expected, desired,
+  memory_order_acq_rel,
+  memory_order_relaxed,
+  memory_scope_work_group);
+}
+#endif
+
 kernel void basic_conversion() {
   double d;
   float f;
@@ -180,6 +195,8 @@
 kernel void basic_work_item() {
   uint ui;
 
+  barrier(CLK_GLOBAL_MEM_FENCE);
+
   get_enqueued_local_size(ui);
 #if !defined(__OPENCL_CPP_VERSION__) && __OPENCL_C_VERSION__ < CL_VERSION_2_0
 // expected-error@-2{{implicit declaration of function 'get_enqueued_local_size' is invalid in OpenCL}}
Index: clang/lib/Sema/SemaLookup.cpp
===
--- clang/lib/Sema/SemaLookup.cpp
+++ clang/lib/Sema/SemaLookup.cpp
@@ -679,7 +679,7 @@
 
 /// Get the QualType instances of the return type and arguments for an OpenCL
 /// builtin function signature.
-/// \param Context (in) The Context instance.
+/// \param S (in) The Sema instance.
 /// \param OpenCLBuiltin (in) The signature currently handled.
 /// \param GenTypeMaxCnt (out) Maximum number of types contained in a generic
 ///type used as return type or as argument.
@@ -689,20 +689,20 @@
 ///argument, ArgTypes contains QualTypes for the Cartesian product
 ///of (vector sizes) x (types) .
 static void 

[PATCH] D96050: [OpenCL] Do not enforce ASTContext for OCL2Qual

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

Do not enforce that the expression to obtain the `QualType` for an
OpenCL type starts with an `ASTContext`.  This adds the required
flexibility for handling enum types.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96050

Files:
  clang/lib/Sema/OpenCLBuiltins.td
  clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp

Index: clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
===
--- clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
+++ clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
@@ -778,8 +778,9 @@
 .Case("RO", "case OCLAQ_ReadOnly:\n")
 .Case("WO", "case OCLAQ_WriteOnly:\n")
 .Case("RW", "case OCLAQ_ReadWrite:\n")
- << "  QT.push_back(Context."
- << Image->getValueAsDef("QTName")->getValueAsString("Name") << ");\n"
+ << "  QT.push_back("
+ << Image->getValueAsDef("QTExpr")->getValueAsString("TypeExpr")
+ << ");\n"
  << "  break;\n";
 }
 OS << "  }\n"
@@ -800,8 +801,7 @@
  I++) {
   for (const auto *T :
GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List")) {
-OS << "Context."
-   << T->getValueAsDef("QTName")->getValueAsString("Name") << ", ";
+OS << T->getValueAsDef("QTExpr")->getValueAsString("TypeExpr") << ", ";
   }
 }
 OS << "});\n";
@@ -835,14 +835,13 @@
 TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
 
 // Check the Type does not have an "abstract" QualType
-auto QT = T->getValueAsDef("QTName");
+auto QT = T->getValueAsDef("QTExpr");
 if (QT->getValueAsBit("IsAbstract") == 1)
   continue;
 // Emit the cases for non generic, non image types.
-OS << "case OCLT_" << T->getValueAsString("Name") << ":\n";
-OS << "  QT.push_back(Context." << QT->getValueAsString("Name")
-   << ");\n";
-OS << "  break;\n";
+OS << "case OCLT_" << T->getValueAsString("Name") << ":\n"
+   << "  QT.push_back(" << QT->getValueAsString("TypeExpr") << ");\n"
+   << "  break;\n";
   }
 
   // End of switch statement.
Index: clang/lib/Sema/OpenCLBuiltins.td
===
--- clang/lib/Sema/OpenCLBuiltins.td
+++ clang/lib/Sema/OpenCLBuiltins.td
@@ -79,10 +79,10 @@
 def ArmIntegerDotProductAccumulateSaturateInt8 : FunctionExtension<"cl_arm_integer_dot_product_accumulate_saturate_int8">;
 
 // Qualified Type.  These map to ASTContext::QualType.
-class QualType {
-  // Name of the field or function in a clang::ASTContext
-  // E.g. Name="IntTy" for the int type, and "getIntPtrType()" for an intptr_t
-  string Name = _Name;
+class QualType {
+  // Expression to obtain the QualType inside OCL2Qual.
+  // E.g. TypeExpr="Context.IntTy" for the int type.
+  string TypeExpr = _TypeExpr;
   // Some QualTypes in this file represent an abstract type for which there is
   // no corresponding AST QualType, e.g. a GenType or an `image2d_t` type
   // without access qualifiers.
@@ -101,11 +101,11 @@
 // OpenCL C basic data types (int, float, image2d_t, ...).
 // Its child classes can represent concrete types (e.g. VectorType) or
 // abstract types (e.g. GenType).
-class Type {
+class Type {
   // Name of the Type.
   string Name = _Name;
   // QualType associated with this type.
-  QualType QTName = _QTName;
+  QualType QTExpr = _QTExpr;
   // Size of the vector (if applicable).
   int VecWidth = 1;
   // Is a pointer.
@@ -121,7 +121,7 @@
 }
 
 // OpenCL vector types (e.g. int2, int3, int16, float8, ...).
-class VectorType : Type<_Ty.Name, _Ty.QTName> {
+class VectorType : Type<_Ty.Name, _Ty.QTExpr> {
   let VecWidth = _VecWidth;
   let AccessQualifier = "";
   // Inherited fields
@@ -133,7 +133,7 @@
 
 // OpenCL pointer types (e.g. int*, float*, ...).
 class PointerType :
-Type<_Ty.Name, _Ty.QTName> {
+Type<_Ty.Name, _Ty.QTExpr> {
   let AddrSpace = _AS.Name;
   // Inherited fields
   let VecWidth = _Ty.VecWidth;
@@ -144,7 +144,7 @@
 }
 
 // OpenCL const types (e.g. const int).
-class ConstType : Type<_Ty.Name, _Ty.QTName> {
+class ConstType : Type<_Ty.Name, _Ty.QTExpr> {
   let IsConst = 1;
   // Inherited fields
   let VecWidth = _Ty.VecWidth;
@@ -155,7 +155,7 @@
 }
 
 // OpenCL volatile types (e.g. volatile int).
-class VolatileType : Type<_Ty.Name, _Ty.QTName> {
+class VolatileType : Type<_Ty.Name, _Ty.QTExpr> {
   let IsVolatile = 1;
   // Inherited fields
   let VecWidth = _Ty.VecWidth;
@@ -167,7 +167,7 @@
 
 // OpenCL image types (e.g. image2d).
 class ImageType :
-Type<_Ty.Name, QualType<_Ty.QTName.Name#_AccessQualifier#"Ty", 0>> {
+

[PATCH] D96033: [clang-repl] Land initial infrastructure for incremental parsing

2021-02-04 Thread Raphael Isemann via Phabricator via cfe-commits
teemperor added a comment.

A more general comment: You have to `std::move` your `llvm::Error` variables 
when the result is `llvm::Expected` (otherwise this won't compile).




Comment at: clang/include/clang/Interpreter/Transaction.h:1
+//===--- Transaction.h - Incremental Compilation and Execution---*- C++ 
-*-===//
+//

Could this whole file just be part of `IncrementalParser.h` which is the only 
user ? `clang::Transaction` seems anyway a bit of a generic name, so maybe this 
could become `clang::IncrementalParser::Transaction` then.



Comment at: clang/include/clang/Interpreter/Transaction.h:10
+// This file defines utilities tracking the incrementally processed pieces of
+// code
+//

missing `.`.



Comment at: clang/include/clang/Parse/Parser.h:2403
   }
-
+private:
   /// isForInitDeclaration - Disambiguates between a declaration or an

This doesn't seem to be needed for anything?



Comment at: clang/lib/Interpreter/IncrementalParser.cpp:175
+  memcpy(MBStart, input.data(), InputSize);
+  memcpy(MBStart + InputSize, "\n", 2);
+

I think overwriting the \0 in the buffer isn't necessary. So 
`MBStart[InputSize] = '\n';` should be enough.



Comment at: clang/lib/Interpreter/Interpreter.cpp:43
+#include "llvm/Support/Host.h"
+//
+

I think the comment here/above and some of the empty lines aren't really needed 
here.



Comment at: clang/lib/Interpreter/Interpreter.cpp:140
+
+  if (std::find(ClangArgv.begin(), ClangArgv.end(), " -x") == ClangArgv.end()) 
{
+// We do C++ by default; append right after argv[0] if no "-x" given

`llvm::find(ClangArgv, " -x")`



Comment at: clang/tools/clang-repl/CMakeLists.txt:3
+#  ${LLVM_TARGETS_TO_BUILD}
+#  Option
+  Support

Commented out by mistake?



Comment at: clang/unittests/CodeGen/IncrementalProcessingTest.cpp:56-59
+  std::vector ClangArgs = {"-Xclang", "-emit-llvm-only"};
+  std::vector ClangArgv(ClangArgs.size());
+  std::transform(ClangArgs.begin(), ClangArgs.end(), ClangArgv.begin(),
+ [](const std::string ) -> const char * { return s.data(); 
});





Comment at: clang/unittests/Interpreter/InterpreterTest.cpp:69
+
+  EXPECT_DEATH((void)Interp->Parse("int var1 = 42;"), "");
+}

I think that's usually used for testing asserts but here it's an invalid memory 
access (which might even work out just if the stars align correctly).

What about either:
1. Shutting down clang-repl cleanly after we hit a diagnostic.
2. Making an assert that we can't codegen a TU that already had any error 
diagnostic (in which case you can surround it with the following):

```
#if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
```


Repository:
  rC Clang

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

https://reviews.llvm.org/D96033

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


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

2021-02-04 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld added inline comments.



Comment at: clang/include/clang/Driver/ToolChain.h:169-177
+  mutable bool isCXXStdlibTypeCached;
+  mutable CXXStdlibType cxxStdlibType;
+
+  mutable bool isRuntimeLibTypeCached;
+  mutable RuntimeLibType runtimeLibType;
+
+  mutable bool isUnwindLibTypeCached;

Maybe `llvm::Optional` for each type instead of having two members?


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

https://reviews.llvm.org/D95915

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


[PATCH] D68682: format::cleanupAroundReplacements removes whole line when Removals leave previously non-blank line blank

2021-02-04 Thread Conrad Poelman via Phabricator via cfe-commits
poelmanc updated this revision to Diff 321451.
poelmanc added a comment.
Herald added a subscriber: nullptr.cpp.

Change loop end condition in `findLineEnd` and add several `assert` statements.


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

https://reviews.llvm.org/D68682

Files:
  clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/modernize-redundant-void-arg.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-control-flow.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-declaration.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-member-init.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
  clang-tools-extra/unittests/clang-change-namespace/ChangeNamespaceTests.cpp
  clang/include/clang/Basic/CharInfo.h
  clang/include/clang/Format/Format.h
  clang/lib/AST/CommentLexer.cpp
  clang/lib/AST/CommentParser.cpp
  clang/lib/Format/Format.cpp
  clang/unittests/Format/CMakeLists.txt
  clang/unittests/Format/CleanupTest.cpp

Index: clang/unittests/Format/CleanupTest.cpp
===
--- clang/unittests/Format/CleanupTest.cpp
+++ clang/unittests/Format/CleanupTest.cpp
@@ -12,6 +12,7 @@
 #include "clang/Tooling/Core/Replacement.h"
 
 #include "gtest/gtest.h"
+#include "llvm/Testing/Support/Annotations.h"
 
 using clang::tooling::ReplacementTest;
 using clang::tooling::toReplacements;
@@ -320,6 +321,11 @@
 return tooling::Replacement(FileName, Offset, Length, Text);
   }
 
+  tooling::Replacement createReplacement(llvm::Annotations::Range Range,
+ StringRef Text) {
+return createReplacement(Range.Begin, Range.End - Range.Begin, Text);
+  }
+
   tooling::Replacement createInsertion(StringRef IncludeDirective) {
 return createReplacement(UINT_MAX, 0, IncludeDirective);
   }
@@ -373,10 +379,12 @@
  "namespace C {\n"
  "namespace D { int i; }\n"
  "inline namespace E { namespace { int y; } }\n"
+ "\n"
  "int x= 0;"
  "}";
-  std::string Expected = "\n\nnamespace C {\n"
- "namespace D { int i; }\n\n"
+  std::string Expected = "\nnamespace C {\n"
+ "namespace D { int i; }\n"
+ "\n"
  "int x= 0;"
  "}";
   tooling::Replacements Replaces =
@@ -386,6 +394,104 @@
   EXPECT_EQ(Expected, formatAndApply(Code, Replaces));
 }
 
+TEST_F(CleanUpReplacementsTest, RemoveLineWhenAllNonWhitespaceRemoved) {
+  llvm::Annotations Code = "namespace A {$r1[[ // Useless comment]]\n"
+   "  $r2[[int]] $r3[[x]]\t $r4[[=]] $r5[[0;]]\t\n"
+   "  int y\t = 0;$r6[[\t]]\n"
+   "} // namespace A\n";
+  std::string Expected = "namespace A {\n"
+ "  int y\t = 0;\n"
+ "} // namespace A\n";
+  tooling::Replacements Replaces =
+  toReplacements({createReplacement(Code.range("r1"), ""),
+  createReplacement(Code.range("r2"), ""),
+  createReplacement(Code.range("r3"), ""),
+  createReplacement(Code.range("r4"), ""),
+  createReplacement(Code.range("r5"), ""),
+  createReplacement(Code.range("r6"), "")});
+
+  EXPECT_EQ(Expected, apply(Code.code(), Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, RemoveLinesWhenAllNonWhitespaceRemoved) {
+  llvm::Annotations Code = R"cpp(struct A {
+  A()
+  $r3[[:]] $r1[[f()]]$r2[[,]]
+$r4[[g()]]
+  {}
+  int f = 0;
+  int g = 0;
+};)cpp";
+  std::string Expected = R"cpp(struct A {
+  A()
+  {}
+  int f = 0;
+  int g = 0;
+};)cpp";
+  tooling::Replacements Replaces =
+  toReplacements({createReplacement(Code.range("r1"), ""),
+  createReplacement(Code.range("r2"), ""),
+  createReplacement(Code.range("r3"), ""),
+  createReplacement(Code.range("r4"), "")});
+
+  EXPECT_EQ(Expected, apply(Code.code(), Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, KeepLinesWithInsertsOrReplacesEvenIfBlank) {
+  // Not using raw string literals so newlines and spaces are clear and explicit
+  llvm::Annotations Code = "struct A {\n"
+ "  A() {}\n"
+ "$r3[[]]  $r1[[int]] $r2[[f;]]\n" // "  int f;\n"
+ "  \n"
+ "$r4[[  ]]\n"
+ "};";
+  std::string Expected = "struct A {\n"
+ "  A() {}\n"
+ "\n"
+ "\n"
+ "  \n"
+ "\t\n"
+ "};";
+  tooling::Replacements Replaces =
+  

[PATCH] D96049: [Timer] On macOS count number of executed instructions

2021-02-04 Thread Alex Hoppen via Phabricator via cfe-commits
ahoppen created this revision.
Herald added subscribers: dexonsmith, hiraditya, mgorny.
ahoppen requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

In addition to wall time etc. this should allow us to get less noisy
values for time measurements.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96049

Files:
  
clang-tools-extra/test/clang-tidy/infrastructure/clang-tidy-store-check-profile-one-tu.cpp
  llvm/CMakeLists.txt
  llvm/include/llvm/Config/config.h.cmake
  llvm/include/llvm/Support/Timer.h
  llvm/lib/Support/Timer.cpp

Index: llvm/lib/Support/Timer.cpp
===
--- llvm/lib/Support/Timer.cpp
+++ llvm/lib/Support/Timer.cpp
@@ -13,6 +13,7 @@
 #include "llvm/Support/Timer.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/ADT/StringMap.h"
+#include "llvm/Config/config.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Format.h"
@@ -24,6 +25,14 @@
 #include "llvm/Support/raw_ostream.h"
 #include 
 
+#if HAVE_UNISTD_H
+#include 
+#endif
+
+#ifdef HAVE_PROC_PID_RUSAGE
+#include 
+#endif
+
 using namespace llvm;
 
 // This ugly hack is brought to you courtesy of constructor/destructor ordering
@@ -120,6 +129,17 @@
   return sys::Process::GetMallocUsage();
 }
 
+static uint64_t getCurInstructionsExecuted() {
+#if defined(HAVE_UNISTD_H) && defined(HAVE_PROC_PID_RUSAGE) && \
+defined(RUSAGE_INFO_V4)
+  struct rusage_info_v4 ru;
+  if (proc_pid_rusage(getpid(), RUSAGE_INFO_V4, (rusage_info_t *)) == 0) {
+return ru.ri_instructions;
+  }
+#endif
+  return 0;
+}
+
 TimeRecord TimeRecord::getCurrentTime(bool Start) {
   using Seconds = std::chrono::duration>;
   TimeRecord Result;
@@ -128,9 +148,11 @@
 
   if (Start) {
 Result.MemUsed = getMemUsage();
+Result.InstructionsExecuted = getCurInstructionsExecuted();
 sys::Process::GetTimeUsage(now, user, sys);
   } else {
 sys::Process::GetTimeUsage(now, user, sys);
+Result.InstructionsExecuted = getCurInstructionsExecuted();
 Result.MemUsed = getMemUsage();
   }
 
@@ -180,6 +202,8 @@
 
   if (Total.getMemUsed())
 OS << format("%9" PRId64 "  ", (int64_t)getMemUsed());
+  if (Total.getInstructionsExecuted())
+OS << format("%9" PRId64 "  ", (int64_t)getInstructionsExecuted());
 }
 
 
@@ -339,6 +363,8 @@
   OS << "   ---Wall Time---";
   if (Total.getMemUsed())
 OS << "  ---Mem---";
+  if (Total.getInstructionsExecuted())
+OS << "  ---Instr---";
   OS << "  --- Name ---\n";
 
   // Loop through all of the timing data, printing it out.
@@ -433,6 +459,10 @@
   OS << delim;
   printJSONValue(OS, R, ".mem", T.getMemUsed());
 }
+if (T.getInstructionsExecuted()) {
+  OS << delim;
+  printJSONValue(OS, R, ".instr", T.getInstructionsExecuted());
+}
   }
   TimersToPrint.clear();
   return delim;
Index: llvm/include/llvm/Support/Timer.h
===
--- llvm/include/llvm/Support/Timer.h
+++ llvm/include/llvm/Support/Timer.h
@@ -24,12 +24,15 @@
 class raw_ostream;
 
 class TimeRecord {
-  double WallTime;   ///< Wall clock time elapsed in seconds.
-  double UserTime;   ///< User time elapsed.
-  double SystemTime; ///< System time elapsed.
-  ssize_t MemUsed;   ///< Memory allocated (in bytes).
+  double WallTime;   ///< Wall clock time elapsed in seconds.
+  double UserTime;   ///< User time elapsed.
+  double SystemTime; ///< System time elapsed.
+  ssize_t MemUsed;   ///< Memory allocated (in bytes).
+  uint64_t InstructionsExecuted; ///< Number of instructions executed
 public:
-  TimeRecord() : WallTime(0), UserTime(0), SystemTime(0), MemUsed(0) {}
+  TimeRecord()
+  : WallTime(0), UserTime(0), SystemTime(0), MemUsed(0),
+InstructionsExecuted(0) {}
 
   /// Get the current time and memory usage.  If Start is true we get the memory
   /// usage before the time, otherwise we get time before memory usage.  This
@@ -42,6 +45,7 @@
   double getSystemTime() const { return SystemTime; }
   double getWallTime() const { return WallTime; }
   ssize_t getMemUsed() const { return MemUsed; }
+  uint64_t getInstructionsExecuted() const { return InstructionsExecuted; }
 
   bool operator<(const TimeRecord ) const {
 // Sort by Wall Time elapsed, as it is the only thing really accurate
@@ -49,16 +53,18 @@
   }
 
   void operator+=(const TimeRecord ) {
-WallTime   += RHS.WallTime;
-UserTime   += RHS.UserTime;
+WallTime += RHS.WallTime;
+UserTime += RHS.UserTime;
 SystemTime += RHS.SystemTime;
-MemUsed+= RHS.MemUsed;
+MemUsed += RHS.MemUsed;
+InstructionsExecuted += RHS.InstructionsExecuted;
   }
   void operator-=(const TimeRecord ) {
-WallTime   -= RHS.WallTime;
-UserTime   -= RHS.UserTime;
+WallTime -= RHS.WallTime;
+  

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

2021-02-04 Thread David Spickett via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
DavidSpickett marked an inline comment as done.
Closed by commit rG1d51c699b9e2: [clang][Arm] Fix handling of -Wa,-march= 
(authored by DavidSpickett).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95872

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

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

[clang] 1d51c69 - [clang][Arm] Fix handling of -Wa,-march=

2021-02-04 Thread David Spickett via cfe-commits

Author: David Spickett
Date: 2021-02-04T16:36:15Z
New Revision: 1d51c699b9e2ebc5bcfdbe85c74cc871426333d4

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

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

This fixes Bugzilla #48894 for Arm, where it
was reported that -Wa,-march was not being handled
by the integrated assembler.

This was previously fixed for -Wa,-mthumb by
parsing the argument in ToolChain::ComputeLLVMTriple
instead of CollectArgsForIntegratedAssembler.
It has to be done in the former because the Triple
is read only by the time we get to the latter.

Previously only mcpu would work via -Wa but only because
"-target-cpu" is it's own option to cc1, which we were
able to modify. Target architecture is part of "-target-triple".

This change applies the same workaround to -march and cleans up
handling of -Wa,-mcpu at the same time. There were some
places where we were not using the last instance of an argument.

The existing -Wa,-mthumb code was doing this correctly,
so I've just added tests to confirm that.

Now the same rules will apply to -Wa,-march/-mcpu as would
if you just passed them to the compiler:
* -Wa/-Xassembler options only apply to assembly files.
* Architecture derived from mcpu beats any march options.
* When there are multiple mcpu or multiple march, the last
  one wins.
* If there is a compiler option and an assembler option of
  the same type, we prefer the one that fits the input type.
* If there is an applicable mcpu option but it is overruled
  by an march, the cpu value is still used for the "-target-cpu"
  cc1 option.

Reviewed By: nickdesaulniers

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

Added: 
clang/test/Driver/arm-target-as-march-mcpu.s

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

Removed: 




diff  --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index b2ddef141a75..c83638086048 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -786,15 +786,26 @@ std::string ToolChain::ComputeLLVMTriple(const ArgList 
,
 else {
   // Ideally we would check for these flags in
   // CollectArgsForIntegratedAssembler but we can't change the ArchName at
-  // that point. There is no assembler equivalent of -mno-thumb, -marm, or
-  // -mno-arm.
+  // that point.
+  llvm::StringRef WaMArch, WaMCPU;
   for (const auto *A :
Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
 for (StringRef Value : A->getValues()) {
+  // There is no assembler equivalent of -mno-thumb, -marm, or 
-mno-arm.
   if (Value == "-mthumb")
 IsThumb = true;
+  else if (Value.startswith("-march="))
+WaMArch = Value.substr(7);
+  else if (Value.startswith("-mcpu="))
+WaMCPU = Value.substr(6);
 }
   }
+
+  if (WaMCPU.size() || WaMArch.size()) {
+// The way this works means that we prefer -Wa,-mcpu's architecture
+// over -Wa,-march. Which matches the compiler behaviour.
+Suffix = tools::arm::getLLVMArchSuffixForARM(WaMCPU, WaMArch, Triple);
+  }
 }
 // Assembly files should start in ARM mode, unless arch is M-profile, or
 // -mthumb has been passed explicitly to the assembler. Windows is always

diff  --git a/clang/lib/Driver/ToolChains/Arch/ARM.cpp 
b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
index ef590db1eecd..d0606eb882f1 100644
--- a/clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -50,11 +50,14 @@ void arm::getARMArchCPUFromArgs(const ArgList , 
llvm::StringRef ,
 
   for (const Arg *A :
Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
-StringRef Value = A->getValue();
-if (Value.startswith("-mcpu="))
-  CPU = Value.substr(6);
-if (Value.startswith("-march="))
-  Arch = Value.substr(7);
+// Use getValues because -Wa can have multiple arguments
+// e.g. -Wa,-mcpu=foo,-mcpu=bar
+for (StringRef Value : A->getValues()) {
+  if (Value.startswith("-mcpu="))
+CPU = Value.substr(6);
+  if (Value.startswith("-march="))
+Arch = Value.substr(7);
+}
   }
 }
 
@@ -290,8 +293,8 @@ void arm::getARMTargetFeatures(const Driver , const 
llvm::Triple ,
   Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
   arm::FloatABI ABI = arm::getARMFloatABI(D, Triple, Args);
   arm::ReadTPMode ThreadPointer = arm::getReadTPMode(D, Args);
-  const Arg *WaCPU = nullptr, *WaFPU = nullptr;
-  const Arg *WaHDiv = nullptr, *WaArch = nullptr;
+  llvm::Optional> WaCPU, WaFPU, WaHDiv,
+  WaArch;
 
   // This vector will accumulate 

[PATCH] D95448: [flang][driver] Add support for `-J/-module-dir`

2021-02-04 Thread Andrzej Warzynski via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG985a42fdf8ae: [flang][driver] Add support for 
`-J/-module-dir` (authored by arnamoy10, committed by awarzynski).

Changed prior to commit:
  https://reviews.llvm.org/D95448?vs=320617=321448#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95448

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  clang/lib/Driver/ToolChains/Flang.h
  flang/include/flang/Frontend/CompilerInstance.h
  flang/include/flang/Frontend/CompilerInvocation.h
  flang/lib/Frontend/CompilerInstance.cpp
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/test/Flang-Driver/driver-help-hidden.f90
  flang/test/Flang-Driver/driver-help.f90
  flang/test/Flang-Driver/include-module.f90
  flang/test/Flang-Driver/write-module.f90

Index: flang/test/Flang-Driver/write-module.f90
===
--- /dev/null
+++ flang/test/Flang-Driver/write-module.f90
@@ -0,0 +1,10 @@
+! RUN: mkdir -p %t/dir-f18 && %f18 -fparse-only -I tools/flang/include/flang -module %t/dir-f18 %s  2>&1
+! RUN: ls %t/dir-f18/testmodule.mod && not ls %t/testmodule.mod
+
+! RUN: mkdir -p %t/dir-flang-new && %flang-new -fsyntax-only -module-dir %t/dir-flang-new %s  2>&1
+! RUN: ls %t/dir-flang-new/testmodule.mod && not ls %t/testmodule.mod
+
+module testmodule
+  type::t2
+  end type
+end
Index: flang/test/Flang-Driver/include-module.f90
===
--- flang/test/Flang-Driver/include-module.f90
+++ flang/test/Flang-Driver/include-module.f90
@@ -7,12 +7,26 @@
 !--
 ! RUN: not %flang-new -fsyntax-only -I %S/Inputs -I %S/Inputs/module-dir %s  2>&1 | FileCheck %s --check-prefix=INCLUDED
 ! RUN: not %flang-new -fsyntax-only -I %S/Inputs %s  2>&1 | FileCheck %s --check-prefix=SINGLEINCLUDE
+! RUN: not %flang-new -fsyntax-only -I %S/Inputs -J %S/Inputs/module-dir %s 2>&1 | FileCheck %s --check-prefix=INCLUDED
+! RUN: not %flang-new -fsyntax-only -J %S/Inputs %s  2>&1 | FileCheck %s --check-prefix=SINGLEINCLUDE
+! RUN: not %flang-new -fsyntax-only -I %S/Inputs -module-dir %S/Inputs/module-dir %s  2>&1 | FileCheck %s --check-prefix=INCLUDED
+! RUN: not %flang-new -fsyntax-only -module-dir %S/Inputs %s  2>&1 | FileCheck %s --check-prefix=SINGLEINCLUDE
+! RUN: not %flang-new -fsyntax-only -J %S/Inputs/module-dir -J %S/Inputs/ %s  2>&1 | FileCheck %s --check-prefix=DOUBLEINCLUDE
+! RUN: not %flang-new -fsyntax-only -J %S/Inputs/module-dir -module-dir %S/Inputs/ %s 2>&1 | FileCheck %s --check-prefix=DOUBLEINCLUDE
+! RUN: not %flang-new -fsyntax-only -module-dir %S/Inputs/module-dir -J%S/Inputs/ %s 2>&1 | FileCheck %s --check-prefix=DOUBLEINCLUDE
 
 !-
 ! FRONTEND FLANG DRIVER (flang-new -fc1)
 !-
 ! RUN: not %flang-new -fc1 -fsyntax-only -I %S/Inputs -I %S/Inputs/module-dir %s  2>&1 | FileCheck %s --check-prefix=INCLUDED
 ! RUN: not %flang-new -fc1 -fsyntax-only -I %S/Inputs %s  2>&1 | FileCheck %s --check-prefix=SINGLEINCLUDE
+! RUN: not %flang-new -fc1 -fsyntax-only -I %S/Inputs -J %S/Inputs/module-dir %s 2>&1 | FileCheck %s --check-prefix=INCLUDED
+! RUN: not %flang-new -fc1 -fsyntax-only -J %S/Inputs %s  2>&1 | FileCheck %s --check-prefix=SINGLEINCLUDE
+! RUN: not %flang-new -fc1 -fsyntax-only -I %S/Inputs -module-dir %S/Inputs/module-dir %s  2>&1 | FileCheck %s --check-prefix=INCLUDED
+! RUN: not %flang-new -fc1 -fsyntax-only -module-dir %S/Inputs %s  2>&1 | FileCheck %s --check-prefix=SINGLEINCLUDE
+! RUN: not %flang-new -fc1 -fsyntax-only -J %S/Inputs/module-dir -J %S/Inputs/ %s 2>&1 | FileCheck %s --check-prefix=DOUBLEINCLUDE
+! RUN: not %flang-new -fc1 -fsyntax-only -J %S/Inputs/module-dir -module-dir %S/Inputs/ %s 2>&1 | FileCheck %s --check-prefix=DOUBLEINCLUDE
+! RUN: not %flang-new -fc1 -fsyntax-only -module-dir %S/Inputs/module-dir -J%S/Inputs/ %s 2>&1 | FileCheck %s --check-prefix=DOUBLEINCLUDE
 
 !-
 ! EXPECTED OUTPUT FOR MISSING MODULE FILE
@@ -22,6 +36,11 @@
 ! SINGLEINCLUDE-NOT:error: Derived type 't1' not found
 ! SINGLEINCLUDE:error: Derived type 't2' not found
 
+!-
+! EXPECTED OUTPUT FOR MISSING MODULE FILE
+!-
+! DOUBLEINCLUDE:error: Only one '-module-dir/-J' option allowed
+
 !---
 ! EXPECTED OUTPUT FOR ALL MODULES FOUND
 !---
Index: flang/test/Flang-Driver/driver-help.f90
===
--- flang/test/Flang-Driver/driver-help.f90
+++ flang/test/Flang-Driver/driver-help.f90
@@ -30,6 +30,7 @@
 ! HELP-NEXT: -fno-color-diagnostics Disable colors in diagnostics
 ! 

[clang] 985a42f - [flang][driver] Add support for `-J/-module-dir`

2021-02-04 Thread Andrzej Warzynski via cfe-commits

Author: Arnamoy Bhattacharyya
Date: 2021-02-04T16:31:40Z
New Revision: 985a42fdf8ae3117442ea129b684569fa6942a71

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

LOG: [flang][driver] Add support for `-J/-module-dir`

Add support for option -J/-module-dir in the new Flang driver.  This
will allow for including module files in other directories, as the
default search path is currently the working folder. This also provides
an option of storing the output module in the specified folder.

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

Added: 
flang/test/Flang-Driver/write-module.f90

Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Flang.cpp
clang/lib/Driver/ToolChains/Flang.h
flang/include/flang/Frontend/CompilerInstance.h
flang/include/flang/Frontend/CompilerInvocation.h
flang/lib/Frontend/CompilerInstance.cpp
flang/lib/Frontend/CompilerInvocation.cpp
flang/lib/Frontend/FrontendActions.cpp
flang/test/Flang-Driver/driver-help-hidden.f90
flang/test/Flang-Driver/driver-help.f90
flang/test/Flang-Driver/include-module.f90

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index a700cab350b7..7bd9a8ab40dc 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -949,6 +949,11 @@ def dependency_dot : Separate<["-"], "dependency-dot">, 
Flags<[CC1Option]>,
 def module_dependency_dir : Separate<["-"], "module-dependency-dir">,
   Flags<[CC1Option]>, HelpText<"Directory to dump module dependencies to">,
   MarshallingInfoString>;
+def module_dir : Separate<["-"], "module-dir">, 
Flags<[FlangOption,FC1Option]>, MetaVarName<"">,
+  HelpText<"Put MODULE files in ">,
+  DocBrief<[{This option specifies where to put .mod files for compiled 
modules.
+It is also added to the list of directories to be searched by an USE statement.
+The default is the current directory.}]>;
 def dsym_dir : JoinedOrSeparate<["-"], "dsym-dir">,
   Flags<[NoXarchOption, RenderAsInput]>,
   HelpText<"Directory to output dSYM's (if any) to">, MetaVarName<"">;
@@ -4121,7 +4126,7 @@ defm devirtualize_speculatively : 
BooleanFFlag<"devirtualize-speculatively">,
 
 // Generic gfortran options.
 def A_DASH : Joined<["-"], "A-">, Group;
-def J : JoinedOrSeparate<["-"], "J">, Flags<[RenderJoined]>, 
Group;
+def J : JoinedOrSeparate<["-"], "J">, 
Flags<[RenderJoined,FlangOption,FC1Option]>, Group, 
Alias;
 def cpp : Flag<["-"], "cpp">, Group;
 def nocpp : Flag<["-"], "nocpp">, Group;
 def static_libgfortran : Flag<["-"], "static-libgfortran">, 
Group;

diff  --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 1b8d03406f30..dee2148c231c 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -30,6 +30,10 @@ void Flang::AddPreprocessingOptions(const ArgList ,
   Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
 }
 
+void Flang::AddOtherOptions(const ArgList , ArgStringList ) const 
{
+  Args.AddAllArgs(CmdArgs, options::OPT_module_dir);
+}
+
 void Flang::ConstructJob(Compilation , const JobAction ,
  const InputInfo , const InputInfoList ,
  const ArgList , const char *LinkingOutput) const 
{
@@ -87,6 +91,9 @@ void Flang::ConstructJob(Compilation , const JobAction ,
 
   AddFortranDialectOptions(Args, CmdArgs);
 
+  // Add other compile options
+  AddOtherOptions(Args, CmdArgs);
+
   if (Output.isFilename()) {
 CmdArgs.push_back("-o");
 CmdArgs.push_back(Output.getFilename());

diff  --git a/clang/lib/Driver/ToolChains/Flang.h 
b/clang/lib/Driver/ToolChains/Flang.h
index a6efa9ae9bda..efbdbe854e24 100644
--- a/clang/lib/Driver/ToolChains/Flang.h
+++ b/clang/lib/Driver/ToolChains/Flang.h
@@ -39,6 +39,13 @@ class LLVM_LIBRARY_VISIBILITY Flang : public Tool {
   /// \param [out] CmdArgs The list of output command arguments
   void AddPreprocessingOptions(const llvm::opt::ArgList ,
llvm::opt::ArgStringList ) const;
+  /// Extract other compilation options from the driver arguments and add them
+  /// to the command arguments.
+  ///
+  /// \param [in] Args The list of input driver arguments
+  /// \param [out] CmdArgs The list of output command arguments
+  void AddOtherOptions(const llvm::opt::ArgList ,
+   llvm::opt::ArgStringList ) const;
 
 public:
   Flang(const ToolChain );

diff  --git a/flang/include/flang/Frontend/CompilerInstance.h 
b/flang/include/flang/Frontend/CompilerInstance.h
index 79a05c0ddbbe..a6f5fa970ddb 100644
--- a/flang/include/flang/Frontend/CompilerInstance.h
+++ b/flang/include/flang/Frontend/CompilerInstance.h
@@ -30,6 

[clang] a83475d - [Hexagon] Add -mv68 option to driver

2021-02-04 Thread Krzysztof Parzyszek via cfe-commits

Author: Krzysztof Parzyszek
Date: 2021-02-04T10:29:34-06:00
New Revision: a83475d34b4550ff5bd40430d6537e630eb761f1

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

LOG: [Hexagon] Add -mv68 option to driver

Added: 


Modified: 
clang/include/clang/Driver/Options.td

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 920b6c0adf89..a700cab350b7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3774,6 +3774,8 @@ def mv67 : Flag<["-"], "mv67">, 
Group,
   Alias, AliasArgs<["hexagonv67"]>;
 def mv67t : Flag<["-"], "mv67t">, Group,
   Alias, AliasArgs<["hexagonv67t"]>;
+def mv68 : Flag<["-"], "mv68">, Group,
+  Alias, AliasArgs<["hexagonv68"]>;
 def mhexagon_hvx : Flag<["-"], "mhvx">, Group,
   HelpText<"Enable Hexagon Vector eXtensions">;
 def mhexagon_hvx_EQ : Joined<["-"], "mhvx=">,



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


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

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

Test still missing.


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

https://reviews.llvm.org/D95915

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


[PATCH] D94952: [clangd] Take into account what is in the index (symbols, references, etc.) at indexes merge

2021-02-04 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX marked 3 inline comments as done.
ArcsinX added a comment.

Thank you for review.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94952

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


[PATCH] D94952: [clangd] Take into account what is in the index (symbols, references, etc.) at indexes merge

2021-02-04 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX updated this revision to Diff 321442.
ArcsinX added a comment.

- Remove default value of `IdxContents` in `FileSymbols` constructor.
- Fix index contents for the preamble index (Symbols => Symbols|Relations).
- Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94952

Files:
  clang-tools-extra/clangd/index/Background.cpp
  clang-tools-extra/clangd/index/FileIndex.cpp
  clang-tools-extra/clangd/index/FileIndex.h
  clang-tools-extra/clangd/index/Index.cpp
  clang-tools-extra/clangd/index/Index.h
  clang-tools-extra/clangd/index/MemIndex.cpp
  clang-tools-extra/clangd/index/MemIndex.h
  clang-tools-extra/clangd/index/Merge.cpp
  clang-tools-extra/clangd/index/Merge.h
  clang-tools-extra/clangd/index/ProjectAware.cpp
  clang-tools-extra/clangd/index/dex/Dex.cpp
  clang-tools-extra/clangd/index/dex/Dex.h
  clang-tools-extra/clangd/index/remote/Client.cpp
  clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang-tools-extra/clangd/unittests/DexTests.cpp
  clang-tools-extra/clangd/unittests/FileIndexTests.cpp
  clang-tools-extra/clangd/unittests/IndexTests.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp

Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1269,7 +1269,7 @@
   std::string BarPath = testPath("bar.cc");
   // Build the index, the index has "Foo" references from foo.cc and "Bar"
   // references from bar.cc.
-  FileSymbols FSymbols;
+  FileSymbols FSymbols(IndexContents::All);
   FSymbols.update(FooPath, nullptr, buildRefSlab(FooCode, "Foo", FooPath),
   nullptr, false);
   FSymbols.update(BarPath, nullptr, buildRefSlab(BarCode, "Bar", BarPath),
@@ -1346,9 +1346,9 @@
llvm::function_ref
Callback) const override {}
 
-llvm::unique_function
+llvm::unique_function
 indexedFiles() const override {
-  return [](llvm::StringRef) { return false; };
+  return [](llvm::StringRef) { return IndexContents::None; };
 }
 
 size_t estimateMemoryUsage() const override { return 0; }
@@ -1400,9 +1400,9 @@
llvm::function_ref)
 const override {}
 
-llvm::unique_function
+llvm::unique_function
 indexedFiles() const override {
-  return [](llvm::StringRef) { return false; };
+  return [](llvm::StringRef) { return IndexContents::None; };
 }
 
 size_t estimateMemoryUsage() const override { return 0; }
Index: clang-tools-extra/clangd/unittests/IndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/IndexTests.cpp
+++ clang-tools-extra/clangd/unittests/IndexTests.cpp
@@ -231,11 +231,11 @@
   auto Data = std::make_pair(std::move(Symbols), std::move(Refs));
   llvm::StringSet<> Files = {testPath("foo.cc"), testPath("bar.cc")};
   MemIndex I(std::move(Data.first), std::move(Data.second), RelationSlab(),
- std::move(Files), std::move(Data), Size);
+ std::move(Files), IndexContents::All, std::move(Data), Size);
   auto ContainsFile = I.indexedFiles();
-  EXPECT_TRUE(ContainsFile("unittest:///foo.cc"));
-  EXPECT_TRUE(ContainsFile("unittest:///bar.cc"));
-  EXPECT_FALSE(ContainsFile("unittest:///foobar.cc"));
+  EXPECT_EQ(ContainsFile("unittest:///foo.cc"), IndexContents::All);
+  EXPECT_EQ(ContainsFile("unittest:///bar.cc"), IndexContents::All);
+  EXPECT_EQ(ContainsFile("unittest:///foobar.cc"), IndexContents::None);
 }
 
 TEST(MemIndexTest, TemplateSpecialization) {
@@ -508,23 +508,24 @@
   auto DynData = std::make_pair(std::move(DynSymbols), std::move(DynRefs));
   llvm::StringSet<> DynFiles = {testPath("foo.cc")};
   MemIndex DynIndex(std::move(DynData.first), std::move(DynData.second),
-RelationSlab(), std::move(DynFiles), std::move(DynData),
-DynSize);
+RelationSlab(), std::move(DynFiles), IndexContents::Symbols,
+std::move(DynData), DynSize);
   SymbolSlab StaticSymbols;
   RefSlab StaticRefs;
   auto StaticData =
   std::make_pair(std::move(StaticSymbols), std::move(StaticRefs));
-  llvm::StringSet<> StaticFiles = {testPath("bar.cc")};
-  MemIndex StaticIndex(std::move(StaticData.first),
-   std::move(StaticData.second), RelationSlab(),
-   std::move(StaticFiles), std::move(StaticData),
-   StaticSymbols.bytes() + StaticRefs.bytes());
+  llvm::StringSet<> StaticFiles = {testPath("foo.cc"), testPath("bar.cc")};
+  MemIndex StaticIndex(
+  std::move(StaticData.first), std::move(StaticData.second), RelationSlab(),
+  std::move(StaticFiles), IndexContents::References, 

[PATCH] D96044: DebugInfo: Emit "LocalToUnit" flag on local member function decls.

2021-02-04 Thread James Y Knight via Phabricator via cfe-commits
jyknight created this revision.
jyknight added a reviewer: dblaikie.
Herald added a subscriber: inglorion.
jyknight requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Previously, the definition was so-marked, but the declaration was
not. This resulted in LLVM's dwarf emission treating the function as
being external, and incorrectly emitting DW_AT_external.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96044

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGenCXX/debug-info-class.cpp


Index: clang/test/CodeGenCXX/debug-info-class.cpp
===
--- clang/test/CodeGenCXX/debug-info-class.cpp
+++ clang/test/CodeGenCXX/debug-info-class.cpp
@@ -24,12 +24,14 @@
 C::~C() {
 }
 
+namespace {
 struct D {
-  D();
-  virtual ~D();
+  D() {}
+  virtual ~D() {}
   void func() {
   }
 };
+} // namespace
 
 struct E {
   E();
@@ -135,11 +137,13 @@
 // CHECK-SAME: DIFlagStaticMember
 // CHECK: [[C_DTOR]] = !DISubprogram(name: "~C"
 
-// CHECK: [[D:![0-9]+]] = !DICompositeType(tag: DW_TAG_structure_type, name: 
"D"
+// CHECK: [[D:![0-9]+]] = distinct !DICompositeType(tag: 
DW_TAG_structure_type, name: "D"
 // CHECK-SAME: size:
-// CHECK-SAME: DIFlagFwdDecl
 // CHECK-NOT:  identifier:
 // CHECK-SAME: ){{$}}
+// CHECK: [[D_FUNC_DECL:![0-9]*]] = !DISubprogram(name: "func",{{.*}} scope: 
[[D]]
+// CHECK-SAME: DISPFlagLocalToUnit
+
 // CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "E"
 // CHECK-SAME: DIFlagFwdDecl
 // CHECK-NOT:  identifier:
@@ -150,11 +154,10 @@
 // CHECK-SAME: ){{$}}
 
 // CHECK: !DISubprogram(name: "func",{{.*}} scope: [[D]]
-// CHECK-SAME:  DISPFlagDefinition
-// CHECK-SAME:  declaration: [[D_FUNC_DECL:![0-9]*]]
-// CHECK: [[D_FUNC_DECL]] = !DISubprogram(name: "func",{{.*}} scope: [[D]]
+// CHECK-SAME:  DISPFlagLocalToUnit | DISPFlagDefinition
+// CHECK-SAME:  declaration: [[D_FUNC_DECL]]
 
-// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "inner",{{.*}} 
line: 50
+// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "inner",{{.*}} 
line: 52
 // CHECK-NOT: DIFlagFwdDecl
 // CHECK-SAME: elements: [[G_INNER_MEM:![0-9]*]]
 // CHECK-SAME: identifier: "_ZTSN1G5innerE"
@@ -170,5 +173,5 @@
 // CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "A"
 // CHECK: !DIDerivedType(tag: DW_TAG_member, name: "HdrSize"
 //
-// CHECK: ![[EXCEPTLOC]] = !DILocation(line: 91,
-// CHECK: ![[RETLOC]] = !DILocation(line: 90,
+// CHECK: ![[EXCEPTLOC]] = !DILocation(line: 93,
+// CHECK: ![[RETLOC]] = !DILocation(line: 92,
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1729,6 +1729,8 @@
 Flags |= llvm::DINode::FlagLValueReference;
   if (Method->getRefQualifier() == RQ_RValue)
 Flags |= llvm::DINode::FlagRValueReference;
+  if (!Method->isExternallyVisible())
+SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
   if (CGM.getLangOpts().Optimize)
 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
 


Index: clang/test/CodeGenCXX/debug-info-class.cpp
===
--- clang/test/CodeGenCXX/debug-info-class.cpp
+++ clang/test/CodeGenCXX/debug-info-class.cpp
@@ -24,12 +24,14 @@
 C::~C() {
 }
 
+namespace {
 struct D {
-  D();
-  virtual ~D();
+  D() {}
+  virtual ~D() {}
   void func() {
   }
 };
+} // namespace
 
 struct E {
   E();
@@ -135,11 +137,13 @@
 // CHECK-SAME: DIFlagStaticMember
 // CHECK: [[C_DTOR]] = !DISubprogram(name: "~C"
 
-// CHECK: [[D:![0-9]+]] = !DICompositeType(tag: DW_TAG_structure_type, name: "D"
+// CHECK: [[D:![0-9]+]] = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "D"
 // CHECK-SAME: size:
-// CHECK-SAME: DIFlagFwdDecl
 // CHECK-NOT:  identifier:
 // CHECK-SAME: ){{$}}
+// CHECK: [[D_FUNC_DECL:![0-9]*]] = !DISubprogram(name: "func",{{.*}} scope: [[D]]
+// CHECK-SAME: DISPFlagLocalToUnit
+
 // CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "E"
 // CHECK-SAME: DIFlagFwdDecl
 // CHECK-NOT:  identifier:
@@ -150,11 +154,10 @@
 // CHECK-SAME: ){{$}}
 
 // CHECK: !DISubprogram(name: "func",{{.*}} scope: [[D]]
-// CHECK-SAME:  DISPFlagDefinition
-// CHECK-SAME:  declaration: [[D_FUNC_DECL:![0-9]*]]
-// CHECK: [[D_FUNC_DECL]] = !DISubprogram(name: "func",{{.*}} scope: [[D]]
+// CHECK-SAME:  DISPFlagLocalToUnit | DISPFlagDefinition
+// CHECK-SAME:  declaration: [[D_FUNC_DECL]]
 
-// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "inner",{{.*}} line: 50
+// CHECK: !DICompositeType(tag: DW_TAG_structure_type, 

[PATCH] D96043: Treat opencl_unroll_hint subject errors as semantic rather than parse errors

2021-02-04 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman created this revision.
aaron.ballman added a reviewer: Anastasia.
Herald added subscribers: zzheng, yaxunl.
aaron.ballman requested review of this revision.
Herald added a project: clang.

While working on a downstream project, I noticed some issues with the 
`opencl_unroll_hint` implementation. The attribute definition claimed the 
attribute was inheritable (which only applies to declaration attributes) and 
not a statement attribute. Further, it treats subject appertainment errors as 
being parse errors rather than semantic errors, which leads to us accepting 
invalid code. For instance, we currently fail to reject:

  void foo() {
int i = 1000;
__attribute__((nomerge, opencl_unroll_hint(8)))
if (i) { foo(); }
  }

This patch address the issues by clarifying that `opencl_unroll_hint` is a 
statement attribute and handling its appertainment checks in the semantic layer 
instead of the parsing layer. This changes the output of the diagnostic text to 
be more consistent with other appertainment errors.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96043

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/include/clang/Parse/Parser.h
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Sema/SemaStmtAttr.cpp
  clang/test/Parser/opencl-unroll-hint.cl

Index: clang/test/Parser/opencl-unroll-hint.cl
===
--- clang/test/Parser/opencl-unroll-hint.cl
+++ clang/test/Parser/opencl-unroll-hint.cl
@@ -1,8 +1,21 @@
-//RUN: %clang_cc1 -O0 -cl-std=CL2.0 -fsyntax-only -verify %s
+//RUN: %clang_cc1 -cl-std=CL2.0 -fsyntax-only -verify %s
 
 kernel void B (global int *x) {
-  __attribute__((opencl_unroll_hint(42)))
-  if (x[0]) // expected-error {{OpenCL only supports 'opencl_unroll_hint' attribute on for, while, and do statements}}
+  __attribute__((opencl_unroll_hint(42))) // expected-error {{'opencl_unroll_hint' attribute only applies to 'for', 'while', and 'do' statements}}
+  if (x[0])
 x[0] = 15;
 }
 
+void parse_order_error() {
+  // Ensure we properly diagnose OpenCL loop attributes on the incorrect
+  // subject in the presence of other attributes.
+  int i = 1000;
+  __attribute__((nomerge, opencl_unroll_hint(8))) // expected-error {{'opencl_unroll_hint' attribute only applies to 'for', 'while', and 'do' statements}}
+  if (i) { parse_order_error(); } // Recursive call silences unrelated diagnostic about nomerge.
+
+  __attribute__((opencl_unroll_hint(8), nomerge)) // expected-error {{'opencl_unroll_hint' attribute only applies to 'for', 'while', and 'do' statements}}
+  if (i) { parse_order_error(); } // Recursive call silences unrelated diagnostic about nomerge.
+
+  __attribute__((nomerge, opencl_unroll_hint(8))) // OK
+  while (1) { parse_order_error(); } // Recursive call silences unrelated diagnostic about nomerge.
+}
Index: clang/lib/Sema/SemaStmtAttr.cpp
===
--- clang/lib/Sema/SemaStmtAttr.cpp
+++ clang/lib/Sema/SemaStmtAttr.cpp
@@ -378,6 +378,12 @@
   // determines unrolling factor) or 1 argument (the unroll factor provided
   // by the user).
 
+  if (!isa(St)) {
+S.Diag(A.getLoc(), diag::err_attribute_wrong_decl_type_str)
+<< A << "'for', 'while', and 'do' statements";
+return nullptr;
+  }
+
   unsigned NumArgs = A.getNumArgs();
 
   if (NumArgs > 1) {
Index: clang/lib/Parse/ParseStmt.cpp
===
--- clang/lib/Parse/ParseStmt.cpp
+++ clang/lib/Parse/ParseStmt.cpp
@@ -98,10 +98,15 @@
 
   ParenBraceBracketBalancer BalancerRAIIObj(*this);
 
+  // Because we're parsing either a statement or a declaration, the order of
+  // attribute parsing is important. [[]] attributes at the start of a
+  // statement are different from [[]] attributes that follow an __attribute__
+  // at the start of the statement. Thus, we're not using MaybeParseAttributes
+  // here because we don't want to allow arbitrary orderings.
   ParsedAttributesWithRange Attrs(AttrFactory);
   MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true);
-  if (!MaybeParseOpenCLUnrollHintAttribute(Attrs))
-return StmtError();
+  if (getLangOpts().OpenCL)
+MaybeParseGNUAttributes(Attrs);
 
   StmtResult Res = ParseStatementOrDeclarationAfterAttributes(
   Stmts, StmtCtx, TrailingElseLoc, Attrs);
@@ -2548,19 +2553,3 @@
   }
   Braces.consumeClose();
 }
-
-bool Parser::ParseOpenCLUnrollHintAttribute(ParsedAttributes ) {
-  MaybeParseGNUAttributes(Attrs);
-
-  if (Attrs.empty())
-return true;
-
-  if (Attrs.begin()->getKind() != ParsedAttr::AT_OpenCLUnrollHint)
-return true;
-
-  if (!(Tok.is(tok::kw_for) || Tok.is(tok::kw_while) || Tok.is(tok::kw_do))) {
-Diag(Tok, diag::err_opencl_unroll_hint_on_non_loop);
-return false;
-  }
-  return true;
-}
Index: 

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

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

LGTM. It also avoid redundant check.


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

https://reviews.llvm.org/D95915

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


  1   2   >