[PATCH] D120720: [clang][AVR] Implement standard calling convention for AVR and AVRTiny

2022-03-12 Thread Ben Shi via Phabricator via cfe-commits
benshi001 added a comment.

This patch fixes the issue https://github.com/llvm/llvm-project/issues/45485 .


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

https://reviews.llvm.org/D120720

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


[clang] 62bcfcb - [AMDGPU] Add llvm.amdgcn.s.setprio intrinsic

2022-03-12 Thread Austin Kerbow via cfe-commits

Author: Austin Kerbow
Date: 2022-03-12T22:15:42-08:00
New Revision: 62bcfcb5a588e5e844f8e4e42a2e4d15c907a746

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

LOG: [AMDGPU] Add llvm.amdgcn.s.setprio intrinsic

Reviewed By: rampitec, arsenm

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

Added: 
llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.setprio.ll

Modified: 
clang/include/clang/Basic/BuiltinsAMDGPU.def
clang/test/CodeGenOpenCL/builtins-amdgcn.cl
clang/test/SemaOpenCL/builtins-amdgcn-error.cl
llvm/include/llvm/IR/IntrinsicsAMDGPU.td
llvm/lib/Target/AMDGPU/SOPInstructions.td

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsAMDGPU.def 
b/clang/include/clang/Basic/BuiltinsAMDGPU.def
index 3b7ff75a9410a..d2e60f85b9feb 100644
--- a/clang/include/clang/Basic/BuiltinsAMDGPU.def
+++ b/clang/include/clang/Basic/BuiltinsAMDGPU.def
@@ -116,6 +116,7 @@ BUILTIN(__builtin_amdgcn_cubema, "", "nc")
 BUILTIN(__builtin_amdgcn_s_sleep, "vIi", "n")
 BUILTIN(__builtin_amdgcn_s_incperflevel, "vIi", "n")
 BUILTIN(__builtin_amdgcn_s_decperflevel, "vIi", "n")
+BUILTIN(__builtin_amdgcn_s_setprio, "vIs", "n")
 BUILTIN(__builtin_amdgcn_uicmp, "WUiUiUiIi", "nc")
 BUILTIN(__builtin_amdgcn_uicmpl, "WUiWUiWUiIi", "nc")
 BUILTIN(__builtin_amdgcn_sicmp, "WUiiiIi", "nc")

diff  --git a/clang/test/CodeGenOpenCL/builtins-amdgcn.cl 
b/clang/test/CodeGenOpenCL/builtins-amdgcn.cl
index b02e6308c343f..ee6d2e0589c5c 100644
--- a/clang/test/CodeGenOpenCL/builtins-amdgcn.cl
+++ b/clang/test/CodeGenOpenCL/builtins-amdgcn.cl
@@ -423,6 +423,15 @@ void test_s_decperflevel()
   __builtin_amdgcn_s_decperflevel(15);
 }
 
+// CHECK-LABEL: @test_s_setprio
+// CHECK: call void @llvm.amdgcn.s.setprio(i16 0)
+// CHECK: call void @llvm.amdgcn.s.setprio(i16 3)
+void test_s_setprio()
+{
+  __builtin_amdgcn_s_setprio(0);
+  __builtin_amdgcn_s_setprio(3);
+}
+
 // CHECK-LABEL: @test_cubeid(
 // CHECK: call float @llvm.amdgcn.cubeid(float %a, float %b, float %c)
 void test_cubeid(global float* out, float a, float b, float c) {

diff  --git a/clang/test/SemaOpenCL/builtins-amdgcn-error.cl 
b/clang/test/SemaOpenCL/builtins-amdgcn-error.cl
index 20a520812e3f3..af4fdf32c272f 100644
--- a/clang/test/SemaOpenCL/builtins-amdgcn-error.cl
+++ b/clang/test/SemaOpenCL/builtins-amdgcn-error.cl
@@ -54,6 +54,12 @@ void test_s_decperflevel(int x)
   __builtin_amdgcn_s_decperflevel(x); // expected-error {{argument to 
'__builtin_amdgcn_s_decperflevel' must be a constant integer}}
 }
 
+void test_s_setprio(int x)
+{
+  __builtin_amdgcn_s_setprio(x); // expected-error {{argument to 
'__builtin_amdgcn_s_setprio' must be a constant integer}}
+  __builtin_amdgcn_s_setprio(65536); // expected-warning {{implicit conversion 
from 'int' to 'short' changes value from 65536 to 0}}
+}
+
 void test_sicmp_i32(global ulong* out, int a, int b, uint c)
 {
   *out = __builtin_amdgcn_sicmp(a, b, c); // expected-error {{argument to 
'__builtin_amdgcn_sicmp' must be a constant integer}}

diff  --git a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td 
b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
index 2a351721e034a..0de25e20e7d0a 100644
--- a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
+++ b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
@@ -1329,6 +1329,11 @@ def int_amdgcn_s_sethalt :
   Intrinsic<[], [llvm_i32_ty], [ImmArg>, IntrNoMem,
 IntrHasSideEffects, IntrWillReturn]>;
 
+def int_amdgcn_s_setprio :
+  GCCBuiltin<"__builtin_amdgcn_s_setprio">,
+  Intrinsic<[], [llvm_i16_ty], [ImmArg>, IntrNoMem,
+IntrHasSideEffects, IntrWillReturn]>;
+
 def int_amdgcn_s_getreg :
   GCCBuiltin<"__builtin_amdgcn_s_getreg">,
   Intrinsic<[llvm_i32_ty], [llvm_i32_ty],

diff  --git a/llvm/lib/Target/AMDGPU/SOPInstructions.td 
b/llvm/lib/Target/AMDGPU/SOPInstructions.td
index 86d1feb183f44..16f747a285d6d 100644
--- a/llvm/lib/Target/AMDGPU/SOPInstructions.td
+++ b/llvm/lib/Target/AMDGPU/SOPInstructions.td
@@ -1278,7 +1278,10 @@ def S_SLEEP : SOPP_Pseudo <"s_sleep", (ins 
i32imm:$simm16),
   let hasSideEffects = 1;
 }
 
-def S_SETPRIO : SOPP_Pseudo <"s_setprio" , (ins i16imm:$simm16), "$simm16">;
+def S_SETPRIO : SOPP_Pseudo <"s_setprio", (ins i16imm:$simm16), "$simm16",
+  [(int_amdgcn_s_setprio timm:$simm16)]> {
+  let hasSideEffects = 1;
+}
 
 let Uses = [EXEC, M0] in {
 // FIXME: Should this be mayLoad+mayStore?

diff  --git a/llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.setprio.ll 
b/llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.setprio.ll
new file mode 100644
index 0..8dd414f78340b
--- /dev/null
+++ b/llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.setprio.ll
@@ -0,0 +1,49 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -march=amdgcn -mcpu=gfx90a -show-mc-encoding 

[PATCH] D120976: [AMDGPU] Add llvm.amdgcn.s.setprio intrinsic

2022-03-12 Thread Austin Kerbow 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 rG62bcfcb5a588: [AMDGPU] Add llvm.amdgcn.s.setprio intrinsic 
(authored by kerbowa).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120976

Files:
  clang/include/clang/Basic/BuiltinsAMDGPU.def
  clang/test/CodeGenOpenCL/builtins-amdgcn.cl
  clang/test/SemaOpenCL/builtins-amdgcn-error.cl
  llvm/include/llvm/IR/IntrinsicsAMDGPU.td
  llvm/lib/Target/AMDGPU/SOPInstructions.td
  llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.setprio.ll

Index: llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.setprio.ll
===
--- /dev/null
+++ llvm/test/CodeGen/AMDGPU/llvm.amdgcn.s.setprio.ll
@@ -0,0 +1,49 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -march=amdgcn -mcpu=gfx90a -show-mc-encoding -verify-machineinstrs < %s | FileCheck -check-prefix=GFX9 %s
+; RUN: llc -march=amdgcn -show-mc-encoding -verify-machineinstrs < %s | FileCheck -check-prefix=SI %s
+; RUN: llc -global-isel -march=amdgcn -show-mc-encoding -verify-machineinstrs < %s | FileCheck -check-prefix=SI %s
+; RUN: llc -global-isel -march=amdgcn -mcpu=gfx90a -show-mc-encoding -verify-machineinstrs < %s | FileCheck -check-prefix=GFX9 %s
+
+declare void @llvm.amdgcn.s.setprio(i16) #0
+
+define void @test_llvm_amdgcn_s_setprio() #0 {
+; GFX9-LABEL: test_llvm_amdgcn_s_setprio:
+; GFX9:   ; %bb.0:
+; GFX9-NEXT:s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0) ; encoding: [0x00,0x00,0x8c,0xbf]
+; GFX9-NEXT:s_setprio 0 ; encoding: [0x00,0x00,0x8f,0xbf]
+; GFX9-NEXT:s_setprio 1 ; encoding: [0x01,0x00,0x8f,0xbf]
+; GFX9-NEXT:s_setprio 2 ; encoding: [0x02,0x00,0x8f,0xbf]
+; GFX9-NEXT:s_setprio 3 ; encoding: [0x03,0x00,0x8f,0xbf]
+; GFX9-NEXT:s_setprio 10 ; encoding: [0x0a,0x00,0x8f,0xbf]
+; GFX9-NEXT:s_setprio -1 ; encoding: [0xff,0xff,0x8f,0xbf]
+; GFX9-NEXT:s_setprio 0 ; encoding: [0x00,0x00,0x8f,0xbf]
+; GFX9-NEXT:s_setprio 1 ; encoding: [0x01,0x00,0x8f,0xbf]
+; GFX9-NEXT:s_setprio -1 ; encoding: [0xff,0xff,0x8f,0xbf]
+; GFX9-NEXT:s_setpc_b64 s[30:31] ; encoding: [0x1e,0x1d,0x80,0xbe]
+;
+; SI-LABEL: test_llvm_amdgcn_s_setprio:
+; SI:   ; %bb.0:
+; SI-NEXT:s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0) ; encoding: [0x00,0x00,0x8c,0xbf]
+; SI-NEXT:s_setprio 0 ; encoding: [0x00,0x00,0x8f,0xbf]
+; SI-NEXT:s_setprio 1 ; encoding: [0x01,0x00,0x8f,0xbf]
+; SI-NEXT:s_setprio 2 ; encoding: [0x02,0x00,0x8f,0xbf]
+; SI-NEXT:s_setprio 3 ; encoding: [0x03,0x00,0x8f,0xbf]
+; SI-NEXT:s_setprio 10 ; encoding: [0x0a,0x00,0x8f,0xbf]
+; SI-NEXT:s_setprio -1 ; encoding: [0xff,0xff,0x8f,0xbf]
+; SI-NEXT:s_setprio 0 ; encoding: [0x00,0x00,0x8f,0xbf]
+; SI-NEXT:s_setprio 1 ; encoding: [0x01,0x00,0x8f,0xbf]
+; SI-NEXT:s_setprio -1 ; encoding: [0xff,0xff,0x8f,0xbf]
+; SI-NEXT:s_setpc_b64 s[30:31] ; encoding: [0x1e,0x20,0x80,0xbe]
+  call void @llvm.amdgcn.s.setprio(i16 0)
+  call void @llvm.amdgcn.s.setprio(i16 1)
+  call void @llvm.amdgcn.s.setprio(i16 2)
+  call void @llvm.amdgcn.s.setprio(i16 3)
+  call void @llvm.amdgcn.s.setprio(i16 10)
+  call void @llvm.amdgcn.s.setprio(i16 65535)
+  call void @llvm.amdgcn.s.setprio(i16 65536)
+  call void @llvm.amdgcn.s.setprio(i16 65537)
+  call void @llvm.amdgcn.s.setprio(i16 -1)
+  ret void
+}
+
+attributes #0 = { nounwind }
Index: llvm/lib/Target/AMDGPU/SOPInstructions.td
===
--- llvm/lib/Target/AMDGPU/SOPInstructions.td
+++ llvm/lib/Target/AMDGPU/SOPInstructions.td
@@ -1278,7 +1278,10 @@
   let hasSideEffects = 1;
 }
 
-def S_SETPRIO : SOPP_Pseudo <"s_setprio" , (ins i16imm:$simm16), "$simm16">;
+def S_SETPRIO : SOPP_Pseudo <"s_setprio", (ins i16imm:$simm16), "$simm16",
+  [(int_amdgcn_s_setprio timm:$simm16)]> {
+  let hasSideEffects = 1;
+}
 
 let Uses = [EXEC, M0] in {
 // FIXME: Should this be mayLoad+mayStore?
Index: llvm/include/llvm/IR/IntrinsicsAMDGPU.td
===
--- llvm/include/llvm/IR/IntrinsicsAMDGPU.td
+++ llvm/include/llvm/IR/IntrinsicsAMDGPU.td
@@ -1329,6 +1329,11 @@
   Intrinsic<[], [llvm_i32_ty], [ImmArg>, IntrNoMem,
 IntrHasSideEffects, IntrWillReturn]>;
 
+def int_amdgcn_s_setprio :
+  GCCBuiltin<"__builtin_amdgcn_s_setprio">,
+  Intrinsic<[], [llvm_i16_ty], [ImmArg>, IntrNoMem,
+IntrHasSideEffects, IntrWillReturn]>;
+
 def int_amdgcn_s_getreg :
   GCCBuiltin<"__builtin_amdgcn_s_getreg">,
   Intrinsic<[llvm_i32_ty], [llvm_i32_ty],
Index: clang/test/SemaOpenCL/builtins-amdgcn-error.cl
===
--- clang/test/SemaOpenCL/builtins-amdgcn-error.cl
+++ clang/test/SemaOpenCL/builtins-amdgcn-error.cl

[PATCH] D121076: [MLIR][Python] Add SCFIfOp Python binding

2022-03-12 Thread Mehdi AMINI via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG036088fd6ea2: [MLIR][Python] Add SCFIfOp Python binding 
(authored by chhzh123, committed by mehdi_amini).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121076

Files:
  mlir/python/mlir/dialects/_scf_ops_ext.py
  mlir/test/python/dialects/scf.py

Index: mlir/test/python/dialects/scf.py
===
--- mlir/test/python/dialects/scf.py
+++ mlir/test/python/dialects/scf.py
@@ -82,3 +82,58 @@
 # CHECK:   iter_args(%{{.*}} = %[[ARGS]]#0, %{{.*}} = %[[ARGS]]#1)
 # CHECK: scf.yield %{{.*}}, %{{.*}}
 # CHECK:   return
+
+
+@constructAndPrintInModule
+def testIfWithoutElse():
+  bool = IntegerType.get_signless(1)
+  i32 = IntegerType.get_signless(32)
+
+  @builtin.FuncOp.from_py_func(bool)
+  def simple_if(cond):
+if_op = scf.IfOp(cond)
+with InsertionPoint(if_op.then_block):
+  one = arith.ConstantOp(i32, 1)
+  add = arith.AddIOp(one, one)
+  scf.YieldOp([])
+return
+
+
+# CHECK: func @simple_if(%[[ARG0:.*]]: i1)
+# CHECK: scf.if %[[ARG0:.*]]
+# CHECK:   %[[ONE:.*]] = arith.constant 1
+# CHECK:   %[[ADD:.*]] = arith.addi %[[ONE]], %[[ONE]]
+# CHECK: return
+
+
+@constructAndPrintInModule
+def testIfWithElse():
+  bool = IntegerType.get_signless(1)
+  i32 = IntegerType.get_signless(32)
+
+  @builtin.FuncOp.from_py_func(bool)
+  def simple_if_else(cond):
+if_op = scf.IfOp(cond, [i32, i32], hasElse=True)
+with InsertionPoint(if_op.then_block):
+  x_true = arith.ConstantOp(i32, 0)
+  y_true = arith.ConstantOp(i32, 1)
+  scf.YieldOp([x_true, y_true])
+with InsertionPoint(if_op.else_block):
+  x_false = arith.ConstantOp(i32, 2)
+  y_false = arith.ConstantOp(i32, 3)
+  scf.YieldOp([x_false, y_false])
+add = arith.AddIOp(if_op.results[0], if_op.results[1])
+return
+
+
+# CHECK: func @simple_if_else(%[[ARG0:.*]]: i1)
+# CHECK: %[[RET:.*]]:2 = scf.if %[[ARG0:.*]]
+# CHECK:   %[[ZERO:.*]] = arith.constant 0
+# CHECK:   %[[ONE:.*]] = arith.constant 1
+# CHECK:   scf.yield %[[ZERO]], %[[ONE]]
+# CHECK: } else {
+# CHECK:   %[[TWO:.*]] = arith.constant 2
+# CHECK:   %[[THREE:.*]] = arith.constant 3
+# CHECK:   scf.yield %[[TWO]], %[[THREE]]
+# CHECK: arith.addi %[[RET]]#0, %[[RET]]#1
+# CHECK: return
Index: mlir/python/mlir/dialects/_scf_ops_ext.py
===
--- mlir/python/mlir/dialects/_scf_ops_ext.py
+++ mlir/python/mlir/dialects/_scf_ops_ext.py
@@ -64,3 +64,44 @@
 To obtain the loop-carried operands, use `iter_args`.
 """
 return self.body.arguments[1:]
+
+
+class IfOp:
+  """Specialization for the SCF if op class."""
+
+  def __init__(self,
+   cond,
+   results_=[],
+   *,
+   hasElse=False,
+   loc=None,
+   ip=None):
+"""Creates an SCF `if` operation.
+
+- `cond` is a MLIR value of 'i1' type to determine which regions of code will be executed.
+- `hasElse` determines whether the if operation has the else branch.
+"""
+operands = []
+operands.append(cond)
+results = []
+results.extend(results_)
+super().__init__(
+self.build_generic(
+regions=2,
+results=results,
+operands=operands,
+loc=loc,
+ip=ip))
+self.regions[0].blocks.append(*[])
+if hasElse:
+self.regions[1].blocks.append(*[])
+
+  @property
+  def then_block(self):
+"""Returns the then block of the if operation."""
+return self.regions[0].blocks[0]
+
+  @property
+  def else_block(self):
+"""Returns the else block of the if operation."""
+return self.regions[1].blocks[0]
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121076: [MLIR][Python] Add SCFIfOp Python binding

2022-03-12 Thread Hongzheng Chen via Phabricator via cfe-commits
chhzh123 added a comment.

Passed pre-merge checks. Should be able to be merged. Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121076

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


[PATCH] D121076: [MLIR][Python] Add SCFIfOp Python binding

2022-03-12 Thread Hongzheng Chen via Phabricator via cfe-commits
chhzh123 updated this revision to Diff 414900.
chhzh123 added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121076

Files:
  mlir/python/mlir/dialects/_scf_ops_ext.py
  mlir/test/python/dialects/scf.py

Index: mlir/test/python/dialects/scf.py
===
--- mlir/test/python/dialects/scf.py
+++ mlir/test/python/dialects/scf.py
@@ -82,3 +82,58 @@
 # CHECK:   iter_args(%{{.*}} = %[[ARGS]]#0, %{{.*}} = %[[ARGS]]#1)
 # CHECK: scf.yield %{{.*}}, %{{.*}}
 # CHECK:   return
+
+
+@constructAndPrintInModule
+def testIfWithoutElse():
+  bool = IntegerType.get_signless(1)
+  i32 = IntegerType.get_signless(32)
+
+  @builtin.FuncOp.from_py_func(bool)
+  def simple_if(cond):
+if_op = scf.IfOp(cond)
+with InsertionPoint(if_op.then_block):
+  one = arith.ConstantOp(i32, 1)
+  add = arith.AddIOp(one, one)
+  scf.YieldOp([])
+return
+
+
+# CHECK: func @simple_if(%[[ARG0:.*]]: i1)
+# CHECK: scf.if %[[ARG0:.*]]
+# CHECK:   %[[ONE:.*]] = arith.constant 1
+# CHECK:   %[[ADD:.*]] = arith.addi %[[ONE]], %[[ONE]]
+# CHECK: return
+
+
+@constructAndPrintInModule
+def testIfWithElse():
+  bool = IntegerType.get_signless(1)
+  i32 = IntegerType.get_signless(32)
+
+  @builtin.FuncOp.from_py_func(bool)
+  def simple_if_else(cond):
+if_op = scf.IfOp(cond, [i32, i32], hasElse=True)
+with InsertionPoint(if_op.then_block):
+  x_true = arith.ConstantOp(i32, 0)
+  y_true = arith.ConstantOp(i32, 1)
+  scf.YieldOp([x_true, y_true])
+with InsertionPoint(if_op.else_block):
+  x_false = arith.ConstantOp(i32, 2)
+  y_false = arith.ConstantOp(i32, 3)
+  scf.YieldOp([x_false, y_false])
+add = arith.AddIOp(if_op.results[0], if_op.results[1])
+return
+
+
+# CHECK: func @simple_if_else(%[[ARG0:.*]]: i1)
+# CHECK: %[[RET:.*]]:2 = scf.if %[[ARG0:.*]]
+# CHECK:   %[[ZERO:.*]] = arith.constant 0
+# CHECK:   %[[ONE:.*]] = arith.constant 1
+# CHECK:   scf.yield %[[ZERO]], %[[ONE]]
+# CHECK: } else {
+# CHECK:   %[[TWO:.*]] = arith.constant 2
+# CHECK:   %[[THREE:.*]] = arith.constant 3
+# CHECK:   scf.yield %[[TWO]], %[[THREE]]
+# CHECK: arith.addi %[[RET]]#0, %[[RET]]#1
+# CHECK: return
Index: mlir/python/mlir/dialects/_scf_ops_ext.py
===
--- mlir/python/mlir/dialects/_scf_ops_ext.py
+++ mlir/python/mlir/dialects/_scf_ops_ext.py
@@ -64,3 +64,44 @@
 To obtain the loop-carried operands, use `iter_args`.
 """
 return self.body.arguments[1:]
+
+
+class IfOp:
+  """Specialization for the SCF if op class."""
+
+  def __init__(self,
+   cond,
+   results_=[],
+   *,
+   hasElse=False,
+   loc=None,
+   ip=None):
+"""Creates an SCF `if` operation.
+
+- `cond` is a MLIR value of 'i1' type to determine which regions of code will be executed.
+- `hasElse` determines whether the if operation has the else branch.
+"""
+operands = []
+operands.append(cond)
+results = []
+results.extend(results_)
+super().__init__(
+self.build_generic(
+regions=2,
+results=results,
+operands=operands,
+loc=loc,
+ip=ip))
+self.regions[0].blocks.append(*[])
+if hasElse:
+self.regions[1].blocks.append(*[])
+
+  @property
+  def then_block(self):
+"""Returns the then block of the if operation."""
+return self.regions[0].blocks[0]
+
+  @property
+  def else_block(self):
+"""Returns the else block of the if operation."""
+return self.regions[1].blocks[0]
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D111400: [Clang] Implement P2242R3

2022-03-12 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added a comment.

Noting for myself:
Clang's status quo already has behaviours that are similar to P2242R3 in its 
C++20 mode despite those behaviours being non-conforming and contributing to 
binary compat breakage with GCC.
This patch is not responsible for those behaviours, and fixing that status quo 
is not within the scope of this patch.

Shorter test:

  struct NonLit {
NonLit();
  };
  template 
  constexpr int foo() {
return 42;
T t;
  }
  int (*f())() {
const int x = foo();
auto ff = [] { return x; }; // C++20 should error here; x is odr-used and 
not captured
return ff;
  }


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111400

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


[PATCH] D119599: [clang-format] Add option to align compound assignments like `+=`

2022-03-12 Thread sstwcw via Phabricator via cfe-commits
sstwcw added a comment.

How to get this revision committed?  I thought it would happen automatically 
now that it is accepted.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119599

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


[PATCH] D121512: [Support] Change zlib::compress to return void

2022-03-12 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 414896.
MaskRay retitled this revision from "[Support] zlib::compress: replace 
compress2 with iterative deflate" to "[Support] Change zlib::compress to return 
void".
MaskRay edited the summary of this revision.
MaskRay added a comment.
Herald added subscribers: cfe-commits, wenlei, usaxena95, kadircet, arphaman, 
emaste.
Herald added projects: clang, clang-tools-extra.

repurpose the patch to return void


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121512

Files:
  clang-tools-extra/clangd/index/Serialization.cpp
  clang/lib/Serialization/ASTWriter.cpp
  llvm/include/llvm/ProfileData/SampleProf.h
  llvm/include/llvm/Support/Compression.h
  llvm/lib/MC/ELFObjectWriter.cpp
  llvm/lib/ObjCopy/ELF/ELFObject.cpp
  llvm/lib/ProfileData/Coverage/CoverageMappingWriter.cpp
  llvm/lib/ProfileData/InstrProf.cpp
  llvm/lib/ProfileData/SampleProf.cpp
  llvm/lib/ProfileData/SampleProfWriter.cpp
  llvm/lib/Support/Compression.cpp
  llvm/unittests/Support/CompressionTest.cpp

Index: llvm/unittests/Support/CompressionTest.cpp
===
--- llvm/unittests/Support/CompressionTest.cpp
+++ llvm/unittests/Support/CompressionTest.cpp
@@ -27,13 +27,10 @@
   SmallString<32> Compressed;
   SmallString<32> Uncompressed;
 
-  Error E = zlib::compress(Input, Compressed, Level);
-  EXPECT_FALSE(E);
-  consumeError(std::move(E));
+  zlib::compress(Input, Compressed, Level);
 
   // Check that uncompressed buffer is the same as original.
-  E = zlib::uncompress(Compressed, Uncompressed, Input.size());
-  EXPECT_FALSE(E);
+  Error E = zlib::uncompress(Compressed, Uncompressed, Input.size());
   consumeError(std::move(E));
 
   EXPECT_EQ(Input, Uncompressed);
Index: llvm/lib/Support/Compression.cpp
===
--- llvm/lib/Support/Compression.cpp
+++ llvm/lib/Support/Compression.cpp
@@ -46,18 +46,20 @@
 
 bool zlib::isAvailable() { return true; }
 
-Error zlib::compress(StringRef InputBuffer,
- SmallVectorImpl , int Level) {
+void zlib::compress(StringRef InputBuffer,
+SmallVectorImpl , int Level) {
   unsigned long CompressedSize = ::compressBound(InputBuffer.size());
   CompressedBuffer.resize_for_overwrite(CompressedSize);
   int Res =
   ::compress2((Bytef *)CompressedBuffer.data(), ,
   (const Bytef *)InputBuffer.data(), InputBuffer.size(), Level);
+  if (Res == Z_MEM_ERROR)
+report_bad_alloc_error("Allocation failed");
+  assert(Res == Z_OK);
   // Tell MemorySanitizer that zlib output buffer is fully initialized.
   // This avoids a false report when running LLVM with uninstrumented ZLib.
   __msan_unpoison(CompressedBuffer.data(), CompressedSize);
   CompressedBuffer.truncate(CompressedSize);
-  return Res ? createError(convertZlibCodeToString(Res)) : Error::success();
 }
 
 Error zlib::uncompress(StringRef InputBuffer, char *UncompressedBuffer,
@@ -87,8 +89,8 @@
 
 #else
 bool zlib::isAvailable() { return false; }
-Error zlib::compress(StringRef InputBuffer,
- SmallVectorImpl , int Level) {
+void zlib::compress(StringRef InputBuffer,
+SmallVectorImpl , int Level) {
   llvm_unreachable("zlib::compress is unavailable");
 }
 Error zlib::uncompress(StringRef InputBuffer, char *UncompressedBuffer,
Index: llvm/lib/ProfileData/SampleProfWriter.cpp
===
--- llvm/lib/ProfileData/SampleProfWriter.cpp
+++ llvm/lib/ProfileData/SampleProfWriter.cpp
@@ -86,10 +86,8 @@
 return sampleprof_error::success;
   auto  = *OutputStream;
   SmallString<128> CompressedStrings;
-  llvm::Error E = zlib::compress(UncompressedStrings, CompressedStrings,
- zlib::BestSizeCompression);
-  if (E)
-return sampleprof_error::compress_failed;
+  zlib::compress(UncompressedStrings, CompressedStrings,
+ zlib::BestSizeCompression);
   encodeULEB128(UncompressedStrings.size(), OS);
   encodeULEB128(CompressedStrings.size(), OS);
   OS << CompressedStrings.str();
Index: llvm/lib/ProfileData/SampleProf.cpp
===
--- llvm/lib/ProfileData/SampleProf.cpp
+++ llvm/lib/ProfileData/SampleProf.cpp
@@ -85,8 +85,6 @@
   return "Counter overflow";
 case sampleprof_error::ostream_seek_unsupported:
   return "Ostream does not support seek";
-case sampleprof_error::compress_failed:
-  return "Compress failure";
 case sampleprof_error::uncompress_failed:
   return "Uncompress failure";
 case sampleprof_error::zlib_unavailable:
Index: llvm/lib/ProfileData/InstrProf.cpp
===
--- llvm/lib/ProfileData/InstrProf.cpp
+++ llvm/lib/ProfileData/InstrProf.cpp
@@ -467,12 +467,8 @@
   }

[PATCH] D121099: [C++20][Modules][HU 5/5] Add fdirectives-only mode for preprocessing output.

2022-03-12 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 414892.
iains added a comment.

rebased.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121099

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/PreprocessorOutputOptions.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/PrintPreprocessedOutput.cpp
  clang/test/Modules/cxx20-hu-05.cpp

Index: clang/test/Modules/cxx20-hu-05.cpp
===
--- /dev/null
+++ clang/test/Modules/cxx20-hu-05.cpp
@@ -0,0 +1,68 @@
+// Test check that consuming -E -fdirectives-only output produces the expected
+// header unit.
+
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+// RUN: cd %t
+
+// RUN: %clang_cc1 -std=c++20 -E -fdirectives-only -xc++-user-header hu-01.h \
+// RUN: -o hu-01.iih
+
+// RUN: %clang_cc1 -std=c++20 -emit-header-unit \
+// RUN: -xc++-user-header-cpp-output hu-01.iih -o hu-01.pcm
+
+// RUN: %clang_cc1 -std=c++20 -emit-header-unit -xc++-user-header hu-02.h \
+// RUN: -DFOO -fmodule-file=hu-01.pcm -o hu-02.pcm -Rmodule-import 2>&1 | \
+// RUN: FileCheck --check-prefix=CHECK-IMP %s -DTDIR=%t
+
+//--- hu-01.h
+#ifndef __GUARD
+#define __GUARD
+
+int baz(int);
+#define FORTYTWO 42
+
+#define SHOULD_NOT_BE_DEFINED -1
+#undef SHOULD_NOT_BE_DEFINED
+
+#endif // __GUARD
+// expected-no-diagnostics
+
+//--- hu-02.h
+export import "hu-01.h";
+#if !defined(FORTYTWO) || FORTYTWO != 42
+#error FORTYTWO missing in hu-02
+#endif
+
+#ifndef __GUARD
+#error __GUARD missing in hu-02
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED
+#error SHOULD_NOT_BE_DEFINED is visible
+#endif
+
+// Make sure that we have not discarded macros from the builtin file.
+#ifndef __cplusplus
+#error we dropped a defined macro
+#endif
+
+#define KAP 6174
+
+#ifdef FOO
+#define FOO_BRANCH(X) (X) + 1
+inline int foo(int x) {
+  if (x == FORTYTWO)
+return FOO_BRANCH(x);
+  return FORTYTWO;
+}
+#else
+#define BAR_BRANCH(X) (X) + 2
+inline int bar(int x) {
+  if (x == FORTYTWO)
+return BAR_BRANCH(x);
+  return FORTYTWO;
+}
+#endif
+// CHECK-IMP: remark: importing module './hu-01.h' from 'hu-01.pcm'
Index: clang/lib/Frontend/PrintPreprocessedOutput.cpp
===
--- clang/lib/Frontend/PrintPreprocessedOutput.cpp
+++ clang/lib/Frontend/PrintPreprocessedOutput.cpp
@@ -96,6 +96,7 @@
   bool UseLineDirectives;
   bool IsFirstFileEntered;
   bool MinimizeWhitespace;
+  bool DirectivesOnly;
 
   Token PrevTok;
   Token PrevPrevTok;
@@ -103,12 +104,13 @@
 public:
   PrintPPOutputPPCallbacks(Preprocessor , raw_ostream , bool lineMarkers,
bool defines, bool DumpIncludeDirectives,
-   bool UseLineDirectives, bool MinimizeWhitespace)
+   bool UseLineDirectives, bool MinimizeWhitespace,
+   bool DirectivesOnly)
   : PP(pp), SM(PP.getSourceManager()), ConcatInfo(PP), OS(os),
 DisableLineMarkers(lineMarkers), DumpDefines(defines),
 DumpIncludeDirectives(DumpIncludeDirectives),
 UseLineDirectives(UseLineDirectives),
-MinimizeWhitespace(MinimizeWhitespace) {
+MinimizeWhitespace(MinimizeWhitespace), DirectivesOnly(DirectivesOnly) {
 CurLine = 0;
 CurFilename += "";
 EmittedTokensOnThisLine = false;
@@ -467,12 +469,21 @@
 void PrintPPOutputPPCallbacks::MacroDefined(const Token ,
 const MacroDirective *MD) {
   const MacroInfo *MI = MD->getMacroInfo();
-  // Only print out macro definitions in -dD mode.
-  if (!DumpDefines ||
+  // Print out macro definitions in -dD mode and when we have -fdirectives-only
+  // for C++20 header units.
+  if ((!DumpDefines && !DirectivesOnly) ||
   // Ignore __FILE__ etc.
-  MI->isBuiltinMacro()) return;
+  MI->isBuiltinMacro())
+return;
 
-  MoveToLine(MI->getDefinitionLoc(), /*RequireStartOfLine=*/true);
+  SourceLocation DefLoc = MI->getDefinitionLoc();
+  if (DirectivesOnly && !MI->isUsed()) {
+SourceManager  = PP.getSourceManager();
+if (SM.isWrittenInBuiltinFile(DefLoc) ||
+SM.isWrittenInCommandLineFile(DefLoc))
+  return;
+  }
+  MoveToLine(DefLoc, /*RequireStartOfLine=*/true);
   PrintMacroDefinition(*MacroNameTok.getIdentifierInfo(), *MI, PP, OS);
   setEmittedDirectiveOnThisLine();
 }
@@ -480,8 +491,10 @@
 void PrintPPOutputPPCallbacks::MacroUndefined(const Token ,
   const MacroDefinition ,
   const MacroDirective *Undef) {
-  // Only print out macro definitions in -dD mode.
-  if (!DumpDefines) return;
+  // Print out macro definitions in -dD mode and when we have -fdirectives-only
+  // for C++20 header units.
+  if (!DumpDefines && !DirectivesOnly)
+return;
 
   MoveToLine(MacroNameTok.getLocation(), 

[PATCH] D121098: [C++20][Modules][HU 4/5] Handle pre-processed header units.

2022-03-12 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 414891.
iains added a comment.

rebased.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121098

Files:
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Sema/SemaModule.cpp


Index: clang/lib/Sema/SemaModule.cpp
===
--- clang/lib/Sema/SemaModule.cpp
+++ clang/lib/Sema/SemaModule.cpp
@@ -109,10 +109,18 @@
 const_cast(getLangOpts()).CurrentModule = HUName.str();
   }
 
-  auto  = PP.getHeaderSearchInfo().getModuleMap();
   // TODO: Make the C++20 header lookup independent.
-  Module::Header H{getLangOpts().CurrentModule, getLangOpts().CurrentModule,
-   SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())};
+  // When the input is pre-processed source, we need a file ref to the original
+  // file for the header map.
+  auto F = SourceMgr.getFileManager().getFile(HUName);
+  // For the sake of error recovery (if someone has moved the original header
+  // after creating the pre-processed output) fall back to obtaining the file
+  // ref for the input file, which must be present.
+  if (!F)
+F = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
+  assert(F && "failed to find the header unit source?");
+  Module::Header H{HUName.str(), HUName.str(), *F};
+  auto  = PP.getHeaderSearchInfo().getModuleMap();
   Module *Mod = Map.createHeaderUnit(StartOfTU, HUName, H);
   assert(Mod && "module creation should not fail");
   ModuleScopes.push_back({}); // No GMF
Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -843,6 +843,21 @@
   if (!CI.InitializeSourceManager(Input))
 return false;
 
+  if (CI.getLangOpts().CPlusPlusModules && Input.getKind().isHeaderUnit() &&
+  Input.getKind().isPreprocessed() && !usesPreprocessorOnly()) {
+// We have an input filename like foo.iih, but we want to find the right
+// module name (and original file, to build the map entry).
+// Check if the first line specifies the original source file name with a
+// linemarker.
+std::string PresumedInputFile = std::string(getCurrentFileOrBufferName());
+ReadOriginalFileName(CI, PresumedInputFile);
+// Unless the user overrides this, the module name is the name by which the
+// original file was known.
+if (CI.getLangOpts().ModuleName.empty())
+  CI.getLangOpts().ModuleName = std::string(PresumedInputFile);
+CI.getLangOpts().CurrentModule = CI.getLangOpts().ModuleName;
+  }
+
   // For module map files, we first parse the module map and synthesize a
   // "" buffer before more conventional processing.
   if (Input.getKind().getFormat() == InputKind::ModuleMap) {


Index: clang/lib/Sema/SemaModule.cpp
===
--- clang/lib/Sema/SemaModule.cpp
+++ clang/lib/Sema/SemaModule.cpp
@@ -109,10 +109,18 @@
 const_cast(getLangOpts()).CurrentModule = HUName.str();
   }
 
-  auto  = PP.getHeaderSearchInfo().getModuleMap();
   // TODO: Make the C++20 header lookup independent.
-  Module::Header H{getLangOpts().CurrentModule, getLangOpts().CurrentModule,
-   SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())};
+  // When the input is pre-processed source, we need a file ref to the original
+  // file for the header map.
+  auto F = SourceMgr.getFileManager().getFile(HUName);
+  // For the sake of error recovery (if someone has moved the original header
+  // after creating the pre-processed output) fall back to obtaining the file
+  // ref for the input file, which must be present.
+  if (!F)
+F = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
+  assert(F && "failed to find the header unit source?");
+  Module::Header H{HUName.str(), HUName.str(), *F};
+  auto  = PP.getHeaderSearchInfo().getModuleMap();
   Module *Mod = Map.createHeaderUnit(StartOfTU, HUName, H);
   assert(Mod && "module creation should not fail");
   ModuleScopes.push_back({}); // No GMF
Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -843,6 +843,21 @@
   if (!CI.InitializeSourceManager(Input))
 return false;
 
+  if (CI.getLangOpts().CPlusPlusModules && Input.getKind().isHeaderUnit() &&
+  Input.getKind().isPreprocessed() && !usesPreprocessorOnly()) {
+// We have an input filename like foo.iih, but we want to find the right
+// module name (and original file, to build the map entry).
+// Check if the first line specifies the original source file name with a
+// linemarker.
+std::string PresumedInputFile = std::string(getCurrentFileOrBufferName());
+ReadOriginalFileName(CI, PresumedInputFile);
+

[PATCH] D121097: [C++20][Modules][HU 3/5] Emit module macros for header units.

2022-03-12 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 414890.
iains added a comment.

rebased.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121097

Files:
  clang/include/clang/Serialization/ASTWriter.h
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/Modules/cxx20-hu-04.cpp

Index: clang/test/Modules/cxx20-hu-04.cpp
===
--- /dev/null
+++ clang/test/Modules/cxx20-hu-04.cpp
@@ -0,0 +1,105 @@
+// Test macro preservation in C++20 Header Units.
+
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+// RUN: cd %t
+
+// RUN: %clang_cc1 -std=c++20 -emit-header-unit -xc++-user-header hu-01.h \
+// RUN: -o hu-01.pcm
+
+// RUN: %clang_cc1 -std=c++20 -module-file-info hu-01.pcm | \
+// RUN: FileCheck --check-prefix=CHECK-HU %s -DTDIR=%t
+
+// RUN: %clang_cc1 -std=c++20 -emit-header-unit -xc++-user-header hu-02.h \
+// RUN: -DFOO -fmodule-file=hu-01.pcm -o hu-02.pcm  -Rmodule-import 2>&1 | \
+// RUN: FileCheck --check-prefix=CHECK-IMP %s -DTDIR=%t
+
+// RUN: %clang_cc1 -std=c++20 -module-file-info hu-02.pcm | \
+// RUN: FileCheck --check-prefix=CHECK-HU2 %s -DTDIR=%t
+
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface importer-01.cpp \
+// RUN:  -fmodule-file=hu-02.pcm -o B.pcm -DTDIR=%t -verify
+
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface importer-02.cpp \
+// RUN:  -fmodule-file=hu-02.pcm -o C.pcm -DTDIR=%t -Rmodule-import 2>&1 | \
+// RUN:  FileCheck --check-prefix=CHECK-IMP-HU2 %s -DTDIR=%t
+
+//--- hu-01.h
+#ifndef __GUARD
+#define __GUARD
+
+int baz(int);
+#define FORTYTWO 42
+
+#define SHOULD_NOT_BE_DEFINED -1
+#undef SHOULD_NOT_BE_DEFINED
+
+#endif // __GUARD
+// expected-no-diagnostics
+
+// CHECK-HU:  == C++20 Module structure ==
+// CHECK-HU-NEXT:  Header Unit './hu-01.h' is the Primary Module at index #1
+
+//--- hu-02.h
+export import "hu-01.h";
+#if !defined(FORTYTWO) || FORTYTWO != 42
+#error FORTYTWO missing in hu-02
+#endif
+
+#ifndef __GUARD
+#error __GUARD missing in hu-02
+#endif
+
+#ifdef SHOULD_NOT_BE_DEFINED
+#error SHOULD_NOT_BE_DEFINED is visible
+#endif
+
+#define KAP 6174
+
+#ifdef FOO
+#define FOO_BRANCH(X) (X) + 1
+inline int foo(int x) {
+  if (x == FORTYTWO)
+return FOO_BRANCH(x);
+  return FORTYTWO;
+}
+#else
+#define BAR_BRANCH(X) (X) + 2
+inline int bar(int x) {
+  if (x == FORTYTWO)
+return BAR_BRANCH(x);
+  return FORTYTWO;
+}
+#endif
+
+// CHECK-IMP: remark: importing module './hu-01.h' from 'hu-01.pcm'
+// CHECK-HU2:  == C++20 Module structure ==
+// CHECK-HU2-NEXT:  Header Unit './hu-02.h' is the Primary Module at index #2
+// CHECK-HU2-NEXT:   Exports:
+// CHECK-HU2-NEXT:Header Unit './hu-01.h' is at index #1
+// expected-no-diagnostics
+
+//--- importer-01.cpp
+export module B;
+import "hu-02.h";
+
+int success(int x) {
+  return foo(FORTYTWO + x + KAP);
+}
+
+int fail(int x) {
+  return bar(FORTYTWO + x + KAP); // expected-error {{use of undeclared identifier 'bar'}}
+  // expected-note@* {{'baz' declared here}}
+}
+
+//--- importer-02.cpp
+export module C;
+import "hu-02.h";
+
+int success(int x) {
+  return foo(FORTYTWO + x + KAP);
+}
+
+// CHECK-IMP-HU2: remark: importing module './hu-02.h' from 'hu-02.pcm'
+// CHECK-IMP-HU2: remark: importing module './hu-01.h' into './hu-02.h' from '[[TDIR]]/hu-01.pcm'
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -2284,7 +2284,8 @@
 
 /// Writes the block containing the serialized form of the
 /// preprocessor.
-void ASTWriter::WritePreprocessor(const Preprocessor , bool IsModule) {
+void ASTWriter::WritePreprocessor(const Preprocessor , bool IsModule,
+  Module *Mod) {
   uint64_t MacroOffsetsBase = Stream.GetCurrentBitNo();
 
   PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
@@ -2353,13 +2354,15 @@
 uint64_t StartOffset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
 assert((StartOffset >> 32) == 0 && "Macro identifiers offset too large");
 
-// Emit the macro directives in reverse source order.
-for (; MD; MD = MD->getPrevious()) {
-  // Once we hit an ignored macro, we're done: the rest of the chain
-  // will all be ignored macros.
-  if (shouldIgnoreMacro(MD, IsModule, PP))
-break;
-
+// Write out any exported module macros.
+bool EmittedModuleMacros = false;
+if (IsHeaderUnit) {
+  // This is for the main TU when it is a C++20 header unit.
+  // We preserve the final state of defined macros, and we do not emit ones
+  // that are undefined.
+  if (!MD || shouldIgnoreMacro(MD, IsModule, PP) ||
+  MD->getKind() == MacroDirective::MD_Undefine)
+continue;
   AddSourceLocation(MD->getLocation(), Record);
   Record.push_back(MD->getKind());
   if (auto *DefMD 

[PATCH] D121096: [C++20][Modules][HU 2/5] Support searching Header Units in user or system search paths.

2022-03-12 Thread Iain Sandoe via Phabricator via cfe-commits
iains added inline comments.



Comment at: clang/include/clang/Frontend/FrontendOptions.h:157
+  unsigned HeaderUnit : 3;
+  unsigned Header : 1;
 

ChuanqiXu wrote:
> I prefer `IsHeader`
OK.



Comment at: clang/include/clang/Frontend/FrontendOptions.h:252
+  bool isHeader() const { return Kind.isHeader(); }
+  InputKind::HeaderUnitKind getHeaderUnit() const {
+return Kind.getHeaderUnit();

ChuanqiXu wrote:
> How about `getHeaderUnitKind` ?
OK. I prefer more descriptive names, but they do get rather long sometimes.



Comment at: clang/lib/Frontend/CompilerInvocation.cpp:2788-2791
+  HUK =
+  XValue.consume_back("-header-unit") ? InputKind::HeaderUnit_Abs : 
HUK;
+  HUK = XValue.consume_back("-system") ? InputKind::HeaderUnit_System : 
HUK;
+  HUK = XValue.consume_back("-user") ? InputKind::HeaderUnit_User : HUK;

ChuanqiXu wrote:
> How do you think about the suggested changes? I feel it is less confusing.
OK, 



Comment at: clang/lib/Frontend/CompilerInvocation.cpp:2796-2797
+// not intended to be a module map or header unit.
+IsHeaderFile = IsHeader && !Preprocessed && !ModuleMap &&
+   HUK == InputKind::HeaderUnit_None;
 

ChuanqiXu wrote:
> Oh, now I find `Header` and `HeaderUnit` might be a little bit confusing. It 
> looks like `Header` should include `HeaderUnit` at the first sight. It is not 
> true. But I don't have only suggestions...
We have an amount of existing handling specific to "generic headers".
 (header unit = none, header = true)

The intention is that HeaderUnitKind is used to disambiguate the cases we are 
dealing with C+=20 header units.

I am not sure it would be worth the code churn to replace all uses of header 
with a HUK.



Comment at: clang/lib/Frontend/CompilerInvocation.cpp:2855-2857
+  assert((DashX.getHeaderUnit() == InputKind::HeaderUnit_None ||
+  Inputs.size() == 1) &&
+ "Expected only one input file for header unit");

ChuanqiXu wrote:
> So the compiler would crash if there is multiple inputs for header unit? I 
> feel it is not most friendly. How about emitting an error here?
well the driver is supposed to catch these problems (in the case of C++20 
modules mode it will generate several compile jobs, one per header).

I added an error for this tho.



Comment at: clang/lib/Frontend/FrontendAction.cpp:814-816
+  const DirectoryEntry *Dir = nullptr;
+  if (auto DirOrErr = CI.getFileManager().getDirectory("."))
+Dir = *DirOrErr;

ChuanqiXu wrote:
> Is it same as the suggested?
not quite because getDirectory() is "llvm::ErrorOr" ... 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121096

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


[PATCH] D121096: [C++20][Modules][HU 2/5] Support searching Header Units in user or system search paths.

2022-03-12 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 414889.
iains marked 6 inline comments as done.
iains added a comment.

rebased, address review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121096

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Frontend/FrontendOptions.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/FrontendAction.cpp
  clang/test/Modules/cxx20-hu-02.cpp
  clang/test/Modules/cxx20-hu-03.cpp

Index: clang/test/Modules/cxx20-hu-03.cpp
===
--- /dev/null
+++ clang/test/Modules/cxx20-hu-03.cpp
@@ -0,0 +1,57 @@
+// Test check that processing headers as C++20 units allows #pragma once.
+
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+// RUN: cd %t
+
+// RUN: %clang_cc1 -std=c++20 -emit-header-unit -xc++-user-header hu-01.h \
+// RUN: -Werror -o hu-01.pcm
+
+// RUN: %clang_cc1 -std=c++20 -emit-header-unit -xc++-user-header hu-02.h \
+// RUN: -fmodule-file=%t/hu-01.pcm -o hu-02.pcm
+
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only imports-01.cpp \
+// RUN: -fmodule-file=%t/hu-01.pcm
+
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only imports-02.cpp \
+// RUN: -fmodule-file=%t/hu-02.pcm
+
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only imports-03.cpp \
+// RUN: -fmodule-file=%t/hu-02.pcm
+
+//--- hu-01.h
+#pragma once
+struct HU {
+  int a;
+};
+// expected-no-diagnostics
+
+//--- hu-02.h
+export import "hu-01.h";
+// expected-no-diagnostics
+
+//--- imports-01.cpp
+import "hu-01.h";
+
+HU foo(int x) {
+  return {x};
+}
+// expected-no-diagnostics
+
+//--- imports-02.cpp
+import "hu-02.h";
+
+HU foo(int x) {
+  return {x};
+}
+// expected-no-diagnostics
+
+//--- imports-03.cpp
+import "hu-01.h";
+import "hu-02.h";
+
+HU foo(int x) {
+  return {x};
+}
+// expected-no-diagnostics
Index: clang/test/Modules/cxx20-hu-02.cpp
===
--- /dev/null
+++ clang/test/Modules/cxx20-hu-02.cpp
@@ -0,0 +1,77 @@
+// Test generation and import of user and system C++20 Header Units.
+
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+// RUN: cd %t
+
+// check user path
+// RUN: %clang_cc1 -std=c++20 -emit-header-unit -I user \
+// RUN: -xc++-user-header hu-01.h -o hu-01.pcm
+
+// RUN: %clang_cc1 -std=c++20 -module-file-info hu-01.pcm | \
+// RUN: FileCheck --check-prefix=CHECK-HU %s -DTDIR=%t
+
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface imp-hu-01.cpp \
+// RUN:  -I user -fmodule-file=hu-01.pcm -o B.pcm -Rmodule-import \
+// RUN: 2>&1  | FileCheck --check-prefix=CHECK-IMP %s -DTDIR=%t
+
+// check system path
+// RUN: %clang_cc1 -std=c++20 -emit-header-unit -isystem system \
+// RUN: -xc++-system-header hu-02.h -o hu-02.pcm
+
+// RUN: %clang_cc1 -std=c++20 -module-file-info hu-02.pcm | \
+// RUN: FileCheck --check-prefix=CHECK-HU2 %s -DTDIR=%t
+
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface imp-hu-02.cpp \
+// RUN:  -isystem system -fmodule-file=hu-02.pcm -o C.pcm \
+// RUN: -Rmodule-import 2>&1 | \
+// RUN: FileCheck --check-prefix=CHECK-SYS-IMP %s -DTDIR=%t
+
+// check absolute path
+// RUN: %clang_cc1 -std=c++20 -emit-header-unit  \
+// RUN: -xc++-header-unit-header %t/hu-03.h -o hu-03.pcm
+
+// RUN: %clang_cc1 -std=c++20 -module-file-info hu-03.pcm | \
+// RUN: FileCheck --check-prefix=CHECK-HU3 %s -DTDIR=%t
+
+//--- user/hu-01.h
+int foo(int);
+
+// CHECK-HU:  == C++20 Module structure ==
+// CHECK-HU-NEXT:  Header Unit 'user/hu-01.h' is the Primary Module at index #1
+
+//--- imp-hu-01.cpp
+export module B;
+import "hu-01.h";
+
+int bar(int x) {
+  return foo(x);
+}
+// CHECK-IMP: remark: importing module 'user/hu-01.h' from 'hu-01.pcm'
+// expected-no-diagnostics
+
+//--- system/hu-02.h
+int baz(int);
+
+// CHECK-HU2:  == C++20 Module structure ==
+// CHECK-HU2-NEXT:  Header Unit 'system/hu-02.h' is the Primary Module at index #1
+
+//--- imp-hu-02.cpp
+module;
+import ;
+
+export module C;
+
+int bar(int x) {
+  return baz(x);
+}
+// CHECK-SYS-IMP: remark: importing module 'system/hu-02.h' from 'hu-02.pcm'
+// expected-no-diagnostics
+
+//--- hu-03.h
+int curly(int);
+
+// CHECK-HU3:  == C++20 Module structure ==
+// CHECK-HU3-NEXT:  Header Unit '[[TDIR]]/hu-03.h' is the Primary Module at index #1
+// expected-no-diagnostics
Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -798,7 +798,48 @@
());
   HasBegunSourceFile = true;
 
-  // Initialize the main file entry.
+  // Handle C++20 header units.
+  // Here, the user has the option to specify that the header name should be
+  // looked up in the pre-processor search paths (and the main filename as
+  // passed by the driver might therefore be 

[PATCH] D121095: [C++20][Modules][HU 1/5] Introduce header units as a module type.

2022-03-12 Thread Iain Sandoe via Phabricator via cfe-commits
iains added inline comments.



Comment at: clang/include/clang/Sema/Sema.h:2978-2980
+  /// The parser has begun a translation unit to be compiled as a C++20
+  /// Header Unit.
+  void ActOnStartOfHeaderUnit();

ChuanqiXu wrote:
> From the implementation, I think it should be called only in 
> `ActOnStartOfTranslationUnit`. So it would be better to move this function to 
> private section to avoid accident calls. We should add such constraint as 
> assumption or at least comment to tell it should be called by 
> `ActOnStartOfTranslationUnit`.
> 
> ---
> 
> The name `ActOnStartOf*` implies there should be a corresponding 
> `ActOnEndOf*`  methods. But there isn't one. So I would suggest to give 
> another name to avoid ambiguity.
> From the implementation, I think it should be called only in 
> `ActOnStartOfTranslationUnit`. So it would be better to move this function to 
> private section to avoid accident calls. We should add such constraint as 
> assumption or at least comment to tell it should be called by 
> `ActOnStartOfTranslationUnit`.

OK, I've made this private and updated the comment to note that this is a 
helper for ActOnStartOfTranslationUnit

> ---
> 
> The name `ActOnStartOf*` implies there should be a corresponding 
> `ActOnEndOf*`  methods. But there isn't one. So I would suggest to give 
> another name to avoid ambiguity.

Is this a rule?

I think that the name `ActOnStartOfHeaderUnit()` says exactly what we are 
doing, of course, at some time we might need an `ActOnEndOfHeaderUnit()` - but 
we should not add an empty function for that reason.

(this is not a sticking point; if consensus is that the name is confusing, I 
will change it).




Comment at: clang/lib/AST/Decl.cpp:1573-1574
   InternalLinkage = isInAnonymousNamespace();
-return InternalLinkage ? M->Parent : nullptr;
+return InternalLinkage ? M->Kind == Module::ModuleHeaderUnit ? M : 
M->Parent
+   : nullptr;
   }

ChuanqiXu wrote:
> How about
> ```
> return InternalLinkage ? M->getTopLevelModule() : nullptr; 
> ```
that would alter the behaviour of the existing code.

getTopLevelModule() will return the ultimate parent:
```
  const Module *Result = this;
  while (Result->Parent)
Result = Result->Parent;
```
where the existing code only returns the immediate parent (perhaps that is 
unintended, but it should be fixed separately if so).




Comment at: clang/lib/Parse/Parser.cpp:2476
 // We can only have pre-processor directives in the global module
 // fragment.  We can, however have a header unit import here.
+if (!HeaderUnit || HeaderUnit->Kind != 
Module::ModuleKind::ModuleHeaderUnit)

ChuanqiXu wrote:
> The comment is not accurate. `header unit import` is pre-processor too. 
> http://eel.is/c++draft/cpp.import
> The comment is not accurate. `header unit import` is pre-processor too. 

the pre-processor 'import' is a pre-processor directive. 

https://eel.is/c++draft/cpp.pre#1

I amended to clarify that we cannot import a named module in this position - 
only a header unit.



Comment at: clang/lib/Sema/SemaModule.cpp:519
+ (ModuleScopes.back().ModuleInterface ||
+  ModuleScopes.back().Module->isGlobalModule())) {
 // Re-export the module if the imported module is exported.

ChuanqiXu wrote:
> I would feel better if we add an assertion below to assert 
> `ModuleScopes.back().Module->isGlobalModule()` is true only if Mod is Header 
> Unit.
> 
OK, done.
I also added a check for CPlusPlus modules, since modules-ts has an implicit 
GMF and slightly different rules.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121095

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


[PATCH] D121095: [C++20][Modules][HU 1/5] Introduce header units as a module type.

2022-03-12 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 414888.
iains marked 4 inline comments as done.
iains added a comment.

rebased, address review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121095

Files:
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Basic/Module.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/FrontendActions.h
  clang/include/clang/Frontend/FrontendOptions.h
  clang/include/clang/Lex/ModuleMap.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Decl.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/FrontendActions.cpp
  clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  clang/lib/Lex/ModuleMap.cpp
  clang/lib/Parse/Parser.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaModule.cpp
  clang/test/Modules/cxx20-hu-01.cpp

Index: clang/test/Modules/cxx20-hu-01.cpp
===
--- /dev/null
+++ clang/test/Modules/cxx20-hu-01.cpp
@@ -0,0 +1,104 @@
+// Test generation and import of simple C++20 Header Units.
+
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+
+// RUN: %clang_cc1 -std=c++20 -emit-header-unit -xc++-header %t/hu-01.h \
+// RUN:  -o %t/hu-01.pcm
+
+// RUN: %clang_cc1 -std=c++20 -module-file-info %t/hu-01.pcm | \
+// RUN: FileCheck --check-prefix=CHECK-HU %s -DTDIR=%t
+
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/imp-hu-01.cpp \
+// RUN:  -fmodule-file=%t/hu-01.pcm -o %t/B.pcm -Rmodule-import 2>&1  | \
+// RUN: FileCheck --check-prefix=CHECK-IMP %s -DTDIR=%t
+
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/imp-hu-02.cpp \
+// RUN:  -fmodule-file=%t/hu-01.pcm -o %t/C.pcm -Rmodule-import 2>&1  | \
+// RUN: FileCheck --check-prefix=CHECK-GMF-IMP %s -DTDIR=%t
+
+// RUN: %clang_cc1 -std=c++20 -emit-header-unit -xc++-header %t/hu-02.h \
+// RUN:  -o %t/hu-02.pcm
+
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/imp-hu-03.cpp \
+// RUN:  -fmodule-file=%t/hu-01.pcm -fmodule-file=%t/hu-02.pcm -o %t/D.pcm \
+// RUN: -Rmodule-import 2>&1 | \
+// RUN: FileCheck --check-prefix=CHECK-BOTH %s -DTDIR=%t
+
+// RUN: %clang_cc1 -std=c++20 -emit-header-unit -xc++-header %t/hu-03.h \
+// RUN: -fmodule-file=%t/hu-01.pcm  -o %t/hu-03.pcm
+
+// RUN: %clang_cc1 -std=c++20 -module-file-info %t/hu-03.pcm | \
+// RUN: FileCheck --check-prefix=CHECK-HU-HU %s -DTDIR=%t
+
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/imp-hu-04.cpp \
+// RUN:  -fmodule-file=%t/hu-03.pcm -o %t/E.pcm -Rmodule-import 2>&1 | \
+// RUN: FileCheck --check-prefix=CHECK-NESTED %s -DTDIR=%t
+
+//--- hu-01.h
+int foo(int);
+
+// CHECK-HU:  == C++20 Module structure ==
+// CHECK-HU-NEXT:  Header Unit '[[TDIR]]/hu-01.h' is the Primary Module at index #1
+
+//--- imp-hu-01.cpp
+export module B;
+import "hu-01.h";
+
+int bar(int x) {
+  return foo(x);
+}
+// CHECK-IMP: remark: importing module '[[TDIR]]/hu-01.h' from '[[TDIR]]/hu-01.pcm'
+// expected-no-diagnostics
+
+//--- imp-hu-02.cpp
+module;
+import "hu-01.h";
+
+export module C;
+
+int bar(int x) {
+  return foo(x);
+}
+// CHECK-GMF-IMP: remark: importing module '[[TDIR]]/hu-01.h' from '[[TDIR]]/hu-01.pcm'
+// expected-no-diagnostics
+
+//--- hu-02.h
+int baz(int);
+
+//--- imp-hu-03.cpp
+module;
+export import "hu-01.h";
+
+export module D;
+import "hu-02.h";
+
+int bar(int x) {
+  return foo(x) + baz(x);
+}
+// CHECK-BOTH: remark: importing module '[[TDIR]]/hu-01.h' from '[[TDIR]]/hu-01.pcm'
+// CHECK-BOTH: remark: importing module '[[TDIR]]/hu-02.h' from '[[TDIR]]/hu-02.pcm'
+// expected-no-diagnostics
+
+//--- hu-03.h
+export import "hu-01.h";
+int baz(int);
+// CHECK-HU-HU:  == C++20 Module structure ==
+// CHECK-HU-HU-NEXT:  Header Unit '[[TDIR]]/hu-03.h' is the Primary Module at index #2
+// CHECK-HU-HU-NEXT:   Exports:
+// CHECK-HU-HU-NEXT:Header Unit '[[TDIR]]/hu-01.h' is at index #1
+
+// expected-no-diagnostics
+
+//--- imp-hu-04.cpp
+module;
+import "hu-03.h";
+
+export module E;
+
+int bar(int x) {
+  return foo(x) + baz(x);
+}
+// CHECK-NESTED: remark: importing module '[[TDIR]]/hu-03.h' from '[[TDIR]]/hu-03.pcm'
+// expected-no-diagnostics
Index: clang/lib/Sema/SemaModule.cpp
===
--- clang/lib/Sema/SemaModule.cpp
+++ clang/lib/Sema/SemaModule.cpp
@@ -97,6 +97,38 @@
   return nullptr;
 }
 
+void Sema::ActOnStartOfHeaderUnit() {
+  assert(getLangOpts().CPlusPlusModules &&
+ "Header units are only valid for C++20 modules");
+  SourceLocation StartOfTU =
+  SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
+
+  StringRef HUName = getLangOpts().CurrentModule;
+  if (HUName.empty()) {
+HUName = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())->getName();
+const_cast(getLangOpts()).CurrentModule = HUName.str();
+  }
+
+  auto  = 

[PATCH] D120631: [clang-format][docs] Fix incorrect 'clang-format 12' option markers

2022-03-12 Thread Björn Schäpers 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 rG9106a07f1fcb: [clang-format][docs] Fix incorrect 
clang-format 12 option markers (authored by kuzkry, committed by 
HazardyKnusperkeks).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120631

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h

Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -503,7 +503,7 @@
 
   /// If ``true``, horizontally align operands of binary and ternary
   /// expressions.
-  /// \version 12
+  /// \version 3.5
   OperandAlignmentStyle AlignOperands;
 
   /// If ``true``, aligns trailing comments.
@@ -566,7 +566,7 @@
   /// B
   ///   } myEnum;
   /// \endcode
-  /// \version 12
+  /// \version 11
   bool AllowShortEnumsOnASingleLine;
 
   /// Different styles for merging short blocks containing at most one
@@ -991,7 +991,7 @@
   ///   //^ inserted
   ///   ]
   /// \endcode
-  /// \version 12
+  /// \version 11
   TrailingCommaStyle InsertTrailingCommas;
 
   /// If ``false``, a function declaration's or function definition's
@@ -2359,7 +2359,7 @@
   /// \endcode
   ///
   /// For example: BOOST_PP_STRINGIZE
-  /// \version 12
+  /// \version 11
   std::vector WhitespaceSensitiveMacros;
 
   tooling::IncludeStyle IncludeStyle;
@@ -2522,7 +2522,7 @@
   };
 
   /// IndentExternBlockStyle is the type of indenting of extern blocks.
-  /// \version 12
+  /// \version 11
   IndentExternBlockStyle IndentExternBlock;
 
   /// Indent the requires clause in a template. This only applies when
@@ -2922,7 +2922,7 @@
   ///}]
   ///}
   /// \endcode
-  /// \version 12
+  /// \version 11
   bool ObjCBreakBeforeNestedBlockParam;
 
   /// Add a space in front of an Objective-C protocol list, i.e. use
Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -606,7 +606,7 @@
 
 
 
-**AlignOperands** (``OperandAlignmentStyle``) :versionbadge:`clang-format 12`
+**AlignOperands** (``OperandAlignmentStyle``) :versionbadge:`clang-format 3.5`
   If ``true``, horizontally align operands of binary and ternary
   expressions.
 
@@ -749,7 +749,7 @@
   return;
 }
 
-**AllowShortEnumsOnASingleLine** (``Boolean``) :versionbadge:`clang-format 12`
+**AllowShortEnumsOnASingleLine** (``Boolean``) :versionbadge:`clang-format 11`
   Allow short enums on a single line.
 
   .. code-block:: c++
@@ -2606,7 +2606,7 @@
plop();  plop();
  }  }
 
-**IndentExternBlock** (``IndentExternBlockStyle``) :versionbadge:`clang-format 12`
+**IndentExternBlock** (``IndentExternBlockStyle``) :versionbadge:`clang-format 11`
   IndentExternBlockStyle is the type of indenting of extern blocks.
 
   Possible values:
@@ -2792,7 +2792,7 @@
   --i;  --i;
 while (i);} while (i);
 
-**InsertTrailingCommas** (``TrailingCommaStyle``) :versionbadge:`clang-format 12`
+**InsertTrailingCommas** (``TrailingCommaStyle``) :versionbadge:`clang-format 11`
   If set to ``TCS_Wrapped`` will insert trailing commas in container
   literals (arrays and objects) that wrap across multiple lines.
   It is currently only available for JavaScript
@@ -3150,7 +3150,7 @@
  [self onOperationDone];
  }];
 
-**ObjCBreakBeforeNestedBlockParam** (``Boolean``) :versionbadge:`clang-format 12`
+**ObjCBreakBeforeNestedBlockParam** (``Boolean``) :versionbadge:`clang-format 11`
   Break parameters list into lines when there is nested block
   parameters in a function call.
 
@@ -4358,7 +4358,7 @@
 
 
 
-**WhitespaceSensitiveMacros** (``List of Strings``) :versionbadge:`clang-format 12`
+**WhitespaceSensitiveMacros** (``List of Strings``) :versionbadge:`clang-format 11`
   A vector of macros which are whitespace-sensitive and should not
   be touched.
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D120774: [clang-format] Handle builtins in constraint expression

2022-03-12 Thread Björn Schäpers via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8b4d68bf65ef: [clang-format] Handle builtins in constraint 
expression (authored by HazardyKnusperkeks).

Changed prior to commit:
  https://reviews.llvm.org/D120774?vs=413430=414881#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120774

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -23810,6 +23810,18 @@
   verifyFormat("template \n"
"concept Node = std::is_object_v;");
 
+  verifyFormat("template \n"
+   "concept integral = __is_integral(T);");
+
+  verifyFormat("template \n"
+   "concept is2D = __array_extent(T, 1) == 2;");
+
+  verifyFormat("template \n"
+   "concept isRhs = __is_rvalue_expr(std::declval() + 2)");
+
+  verifyFormat("template \n"
+   "concept Same = __is_same_as;");
+
   auto Style = getLLVMStyle();
   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
 
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -3132,30 +3132,6 @@
 return;
   break;
 
-case tok::identifier:
-  // We need to differentiate identifiers for a template deduction guide,
-  // variables, or function return types (the constraint expression has
-  // ended before that), and basically all other cases. But it's easier to
-  // check the other way around.
-  assert(FormatTok->Previous);
-  switch (FormatTok->Previous->Tok.getKind()) {
-  case tok::coloncolon:  // Nested identifier.
-  case tok::ampamp:  // Start of a function or variable for the
-  case tok::pipepipe:// constraint expression.
-  case tok::kw_requires: // Initial identifier of a requires clause.
-  case tok::equal:   // Initial identifier of a concept declaration.
-break;
-  default:
-return;
-  }
-
-  // Read identifier with optional template declaration.
-  nextToken();
-  if (FormatTok->is(tok::less))
-parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
-/*ClosingBraceKind=*/tok::greater);
-  break;
-
 case tok::kw_const:
 case tok::semi:
 case tok::kw_class:
@@ -3232,7 +3208,34 @@
   break;
 
 default:
-  return;
+  if (!FormatTok->Tok.getIdentifierInfo()) {
+// Identifiers are part of the default case, we check for more then
+// tok::identifier to handle builtin type traits.
+return;
+  }
+
+  // We need to differentiate identifiers for a template deduction guide,
+  // variables, or function return types (the constraint expression has
+  // ended before that), and basically all other cases. But it's easier to
+  // check the other way around.
+  assert(FormatTok->Previous);
+  switch (FormatTok->Previous->Tok.getKind()) {
+  case tok::coloncolon:  // Nested identifier.
+  case tok::ampamp:  // Start of a function or variable for the
+  case tok::pipepipe:// constraint expression.
+  case tok::kw_requires: // Initial identifier of a requires clause.
+  case tok::equal:   // Initial identifier of a concept declaration.
+break;
+  default:
+return;
+  }
+
+  // Read identifier with optional template declaration.
+  nextToken();
+  if (FormatTok->is(tok::less))
+parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
+/*ClosingBraceKind=*/tok::greater);
+  break;
 }
   } while (!eof());
 }


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -23810,6 +23810,18 @@
   verifyFormat("template \n"
"concept Node = std::is_object_v;");
 
+  verifyFormat("template \n"
+   "concept integral = __is_integral(T);");
+
+  verifyFormat("template \n"
+   "concept is2D = __array_extent(T, 1) == 2;");
+
+  verifyFormat("template \n"
+   "concept isRhs = __is_rvalue_expr(std::declval() + 2)");
+
+  verifyFormat("template \n"
+   "concept Same = __is_same_as;");
+
   auto Style = getLLVMStyle();
   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
 
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ 

[clang] 9106a07 - [clang-format][docs] Fix incorrect 'clang-format 12' option markers

2022-03-12 Thread Björn Schäpers via cfe-commits

Author: Krystian Kuzniarek
Date: 2022-03-12T22:49:57+01:00
New Revision: 9106a07f1fcb4bd425a3ef2f9f3e2b68bc1ad916

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

LOG: [clang-format][docs] Fix incorrect 'clang-format 12' option markers

Introduced by 23a5090c6, some style option markers indicated
'clang-format 12', though their respective options were available in
earlier releases.

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 1f2e94940b53c..9b5d9ee7ef298 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -606,7 +606,7 @@ the configuration (without a prefix: ``Auto``).
 
 
 
-**AlignOperands** (``OperandAlignmentStyle``) :versionbadge:`clang-format 12`
+**AlignOperands** (``OperandAlignmentStyle``) :versionbadge:`clang-format 3.5`
   If ``true``, horizontally align operands of binary and ternary
   expressions.
 
@@ -749,7 +749,7 @@ the configuration (without a prefix: ``Auto``).
   return;
 }
 
-**AllowShortEnumsOnASingleLine** (``Boolean``) :versionbadge:`clang-format 12`
+**AllowShortEnumsOnASingleLine** (``Boolean``) :versionbadge:`clang-format 11`
   Allow short enums on a single line.
 
   .. code-block:: c++
@@ -2606,7 +2606,7 @@ the configuration (without a prefix: ``Auto``).
plop();  plop();
  }  }
 
-**IndentExternBlock** (``IndentExternBlockStyle``) :versionbadge:`clang-format 
12`
+**IndentExternBlock** (``IndentExternBlockStyle``) :versionbadge:`clang-format 
11`
   IndentExternBlockStyle is the type of indenting of extern blocks.
 
   Possible values:
@@ -2792,7 +2792,7 @@ the configuration (without a prefix: ``Auto``).
   --i;  --i;
 while (i);} while (i);
 
-**InsertTrailingCommas** (``TrailingCommaStyle``) :versionbadge:`clang-format 
12`
+**InsertTrailingCommas** (``TrailingCommaStyle``) :versionbadge:`clang-format 
11`
   If set to ``TCS_Wrapped`` will insert trailing commas in container
   literals (arrays and objects) that wrap across multiple lines.
   It is currently only available for JavaScript
@@ -3150,7 +3150,7 @@ the configuration (without a prefix: ``Auto``).
  [self onOperationDone];
  }];
 
-**ObjCBreakBeforeNestedBlockParam** (``Boolean``) :versionbadge:`clang-format 
12`
+**ObjCBreakBeforeNestedBlockParam** (``Boolean``) :versionbadge:`clang-format 
11`
   Break parameters list into lines when there is nested block
   parameters in a function call.
 
@@ -4358,7 +4358,7 @@ the configuration (without a prefix: ``Auto``).
 
 
 
-**WhitespaceSensitiveMacros** (``List of Strings``) 
:versionbadge:`clang-format 12`
+**WhitespaceSensitiveMacros** (``List of Strings``) 
:versionbadge:`clang-format 11`
   A vector of macros which are whitespace-sensitive and should not
   be touched.
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 49b932c8d16e1..70af9b19085ee 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -503,7 +503,7 @@ struct FormatStyle {
 
   /// If ``true``, horizontally align operands of binary and ternary
   /// expressions.
-  /// \version 12
+  /// \version 3.5
   OperandAlignmentStyle AlignOperands;
 
   /// If ``true``, aligns trailing comments.
@@ -566,7 +566,7 @@ struct FormatStyle {
   /// B
   ///   } myEnum;
   /// \endcode
-  /// \version 12
+  /// \version 11
   bool AllowShortEnumsOnASingleLine;
 
   /// Different styles for merging short blocks containing at most one
@@ -991,7 +991,7 @@ struct FormatStyle {
   ///   //^ inserted
   ///   ]
   /// \endcode
-  /// \version 12
+  /// \version 11
   TrailingCommaStyle InsertTrailingCommas;
 
   /// If ``false``, a function declaration's or function definition's
@@ -2359,7 +2359,7 @@ struct FormatStyle {
   /// \endcode
   ///
   /// For example: BOOST_PP_STRINGIZE
-  /// \version 12
+  /// \version 11
   std::vector WhitespaceSensitiveMacros;
 
   tooling::IncludeStyle IncludeStyle;
@@ -2522,7 +2522,7 @@ struct FormatStyle {
   };
 
   /// IndentExternBlockStyle is the type of indenting of extern blocks.
-  /// \version 12
+  /// \version 11
   IndentExternBlockStyle IndentExternBlock;
 
   /// Indent the requires clause in a template. This only applies when
@@ -2922,7 +2922,7 @@ struct FormatStyle {
   ///}]
   ///}
   /// 

[clang] 8b4d68b - [clang-format] Handle builtins in constraint expression

2022-03-12 Thread Björn Schäpers via cfe-commits

Author: Björn Schäpers
Date: 2022-03-12T22:44:24+01:00
New Revision: 8b4d68bf65ef145333aae82683b5fcee29b38dc2

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

LOG: [clang-format] Handle builtins in constraint expression

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

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 994b197347bc1..3a245b8b5fa0d 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3132,30 +3132,6 @@ void UnwrappedLineParser::parseConstraintExpression() {
 return;
   break;
 
-case tok::identifier:
-  // We need to 
diff erentiate identifiers for a template deduction guide,
-  // variables, or function return types (the constraint expression has
-  // ended before that), and basically all other cases. But it's easier to
-  // check the other way around.
-  assert(FormatTok->Previous);
-  switch (FormatTok->Previous->Tok.getKind()) {
-  case tok::coloncolon:  // Nested identifier.
-  case tok::ampamp:  // Start of a function or variable for the
-  case tok::pipepipe:// constraint expression.
-  case tok::kw_requires: // Initial identifier of a requires clause.
-  case tok::equal:   // Initial identifier of a concept declaration.
-break;
-  default:
-return;
-  }
-
-  // Read identifier with optional template declaration.
-  nextToken();
-  if (FormatTok->is(tok::less))
-parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
-/*ClosingBraceKind=*/tok::greater);
-  break;
-
 case tok::kw_const:
 case tok::semi:
 case tok::kw_class:
@@ -3232,7 +3208,34 @@ void UnwrappedLineParser::parseConstraintExpression() {
   break;
 
 default:
-  return;
+  if (!FormatTok->Tok.getIdentifierInfo()) {
+// Identifiers are part of the default case, we check for more then
+// tok::identifier to handle builtin type traits.
+return;
+  }
+
+  // We need to 
diff erentiate identifiers for a template deduction guide,
+  // variables, or function return types (the constraint expression has
+  // ended before that), and basically all other cases. But it's easier to
+  // check the other way around.
+  assert(FormatTok->Previous);
+  switch (FormatTok->Previous->Tok.getKind()) {
+  case tok::coloncolon:  // Nested identifier.
+  case tok::ampamp:  // Start of a function or variable for the
+  case tok::pipepipe:// constraint expression.
+  case tok::kw_requires: // Initial identifier of a requires clause.
+  case tok::equal:   // Initial identifier of a concept declaration.
+break;
+  default:
+return;
+  }
+
+  // Read identifier with optional template declaration.
+  nextToken();
+  if (FormatTok->is(tok::less))
+parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
+/*ClosingBraceKind=*/tok::greater);
+  break;
 }
   } while (!eof());
 }

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index b344ac33cd580..37a42382e8f85 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -23810,6 +23810,18 @@ TEST_F(FormatTest, Concepts) {
   verifyFormat("template \n"
"concept Node = std::is_object_v;");
 
+  verifyFormat("template \n"
+   "concept integral = __is_integral(T);");
+
+  verifyFormat("template \n"
+   "concept is2D = __array_extent(T, 1) == 2;");
+
+  verifyFormat("template \n"
+   "concept isRhs = __is_rvalue_expr(std::declval() + 2)");
+
+  verifyFormat("template \n"
+   "concept Same = __is_same_as;");
+
   auto Style = getLLVMStyle();
   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
 



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


[PATCH] D120631: [clang-format][docs] Fix incorrect 'clang-format 12' option markers

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

Your patches are not directly applicable.
You have

  --- clang/include/clang/Format/Format.h
  +++ clang/include/clang/Format/Format.h

instead of

  --- a/clang/include/clang/Format/Format.h
  +++ b/clang/include/clang/Format/Format.h

which results in

  $ git apply diff.patch
  error: docs/ClangFormatStyleOptions.rst: No such file or directory
  error: include/clang/Format/Format.h: No such file or directory


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120631

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


[PATCH] D111400: [Clang] Implement P2242R3

2022-03-12 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 414880.
cor3ntin added a comment.

- Rebase
- Update cxx_status as we are now targeting clang 15
- Test the pre-C++2b warnings


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111400

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/dtor.cpp
  clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3-2b.cpp
  clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
  clang/test/Lexer/cxx-features.cpp
  clang/test/SemaCXX/constant-expression-cxx14.cpp
  clang/test/SemaCXX/constant-expression-cxx2b.cpp
  clang/test/SemaCXX/cxx1z-constexpr-lambdas.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1361,7 +1361,7 @@
 
   Non-literal variables (and labels and gotos) in constexpr functions
   https://wg21.link/P2242R3;>P2242R3
-  No
+  Clang 15
 
 
   Character encoding of diagnostic text
Index: clang/test/SemaCXX/cxx1z-constexpr-lambdas.cpp
===
--- clang/test/SemaCXX/cxx1z-constexpr-lambdas.cpp
+++ clang/test/SemaCXX/cxx1z-constexpr-lambdas.cpp
@@ -115,11 +115,6 @@
 constexpr const char *Str = "abc";
 static_assert(fp4(Str) == Str);
 
-auto NCL = [](int i) { static int j; return j; }; //expected-note{{declared here}}
-constexpr int (*fp5)(int) = NCL;
-constexpr int I =  //expected-error{{must be initialized by a constant expression}}
-  fp5(5); //expected-note{{non-constexpr function}} 
-
 namespace test_dont_always_instantiate_constexpr_templates {
 
 auto explicit_return_type = [](auto x) -> int { return x.get(); };
Index: clang/test/SemaCXX/constant-expression-cxx2b.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/constant-expression-cxx2b.cpp
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -std=c++2b -fsyntax-only -verify %s -fcxx-exceptions -triple=x86_64-linux-gnu -Wpre-c++2b-compat
+
+constexpr int f(int n) {  // expected-error {{constexpr function never produces a constant expression}}
+  static const int m = n; //  expected-note {{declared here}}  \
+  //  expected-warning {{definition of a static variable in a constexpr function is incompatible with C++ standards before C++2b}}
+  return m;   //  expected-note {{initializer of 'm' is not a constant expression}}
+}
+constexpr int g(int n) {//  expected-error {{constexpr function never produces a constant expression}}
+  thread_local const int m = n; //  expected-note {{declared here}} \
+//  expected-warning {{definition of a thread_local variable in a constexpr function is incompatible with C++ standards before C++2b}}
+  return m; //  expected-note {{initializer of 'm' is not a constant expression}}
+}
+
+constexpr int h(int n) {
+  if (!n)
+return 0;
+  static const int m = n; // expected-warning{{definition of a static variable in a constexpr function is incompatible with C++ standards before C++2b}}
+  return m;
+}
+constexpr int i(int n) {
+  if (!n)
+return 0;
+  thread_local const int m = n; // expected-warning{{definition of a thread_local variable in a constexpr function is incompatible with C++ standards before C++2b}}
+  return m;
+}
Index: clang/test/SemaCXX/constant-expression-cxx14.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx14.cpp
+++ clang/test/SemaCXX/constant-expression-cxx14.cpp
@@ -44,14 +44,6 @@
   return 3 * k3 + 5 * k2 + n * k - 20;
 }
 static_assert(g(2) == 42, "");
-constexpr int h(int n) {
-  static const int m = n; // expected-error {{static variable not permitted in a constexpr function}}
-  return m;
-}
-constexpr int i(int n) {
-  thread_local const int m = n; // expected-error {{thread_local variable not permitted in a constexpr function}}
-  return m;
-}
 
 // if-statements can be used in constexpr functions.
 constexpr int j(int k) {
@@ -65,7 +57,9 @@
   return 2;
 }
   }
-} // expected-note 2{{control reached end of constexpr function}}
+} // expected-warning {{non-void}} \
+  //expected-note 2{{control reached end of constexpr function}}
+
 static_assert(j(0) == -3, "");
 static_assert(j(1) == 5, "");
 static_assert(j(2), ""); // expected-error {{constant expression}} expected-note {{in call to 'j(2)'}}
Index: clang/test/Lexer/cxx-features.cpp
===
--- clang/test/Lexer/cxx-features.cpp
+++ clang/test/Lexer/cxx-features.cpp
@@ -277,7 +277,7 @@
 #error "wrong value for __cpp_lambdas"
 #endif
 
-#if 

[PATCH] D120610: [DebugInfo] Include DW_TAG_skeleton_unit when looking for parent UnitDie

2022-03-12 Thread Wenlei He via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4f320ca4ba15: [DebugInfo] Include DW_TAG_skeleton_unit when 
looking for parent UnitDie (authored by wenlei).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120610

Files:
  llvm/lib/CodeGen/AsmPrinter/DIE.cpp
  llvm/test/DebugInfo/X86/fission-template.ll


Index: llvm/test/DebugInfo/X86/fission-template.ll
===
--- /dev/null
+++ llvm/test/DebugInfo/X86/fission-template.ll
@@ -0,0 +1,75 @@
+; Check that we handle template types for split-dwarf-inlining correctly.
+; RUN: llc -split-dwarf-file=%t.dwo -O2 < %s -dwarf-version=5 
-mtriple=x86_64-unknown-linux-gnu -filetype=obj -o -  | llvm-dwarfdump - | 
FileCheck %s
+;
+; The test case is generated from the following code
+; clang -cc1 -emit-llvm -fdebug-info-for-profiling -fsplit-dwarf-inlining 
-debug-info-kind=constructor -dwarf-version=5 -split-dwarf-file temp.dwo -O2
+;
+; void f1();
+;
+; template 
+; void f2() {
+;   f1();
+; }
+;
+; void f3() {
+;   f2();
+; }
+
+; CHECK:  .debug_info contents:
+; CHECK:DW_TAG_skeleton_unit
+; CHECK:  DW_TAG_subprogram
+; CHECK-NEXT: DW_AT_linkage_name   ("_Z2f2IiEvv")
+; CHECK-NEXT: DW_AT_name   ("f2")
+; CHECK:  DW_TAG_template_type_parameter
+; CHECK-NEXT:   DW_AT_type (0x{{.*}} "int")
+; CHECK-NEXT:   DW_AT_name ("T")
+; CHECK:  .debug_info.dwo contents:
+; CHECK:DW_TAG_compile_unit
+; CHECK:  DW_TAG_subprogram
+; CHECK-NEXT: DW_AT_linkage_name   ("_Z2f2IiEvv")
+; CHECK-NEXT: DW_AT_name   ("f2")
+; CHECK:  DW_TAG_template_type_parameter
+; CHECK-NEXT:   DW_AT_type (0x{{.*}} "int")
+; CHECK-NEXT:   DW_AT_name ("T")
+
+; ModuleID = 'split-debug-inlining-template.cpp'
+source_filename = 
"llvm-project/clang/test/CodeGen/split-debug-inlining-template.cpp"
+target datalayout = 
"e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-redhat-linux-gnu"
+
+; Function Attrs: mustprogress nounwind
+define dso_local void @_Z2f3v() local_unnamed_addr #0 !dbg !6 {
+entry:
+  tail call void @_Z2f1v() #2, !dbg !11
+  ret void, !dbg !17
+}
+
+declare !dbg !18 void @_Z2f1v() local_unnamed_addr #1
+
+attributes #0 = { mustprogress nounwind "frame-pointer"="none" 
"min-legal-vector-width"="0" "no-trapping-math"="true" 
"stack-protector-buffer-size"="8" "target-features"="+cx8,+mmx,+sse,+sse2,+x87" 
}
+attributes #1 = { "frame-pointer"="none" "no-trapping-math"="true" 
"stack-protector-buffer-size"="8" "target-features"="+cx8,+mmx,+sse,+sse2,+x87" 
}
+attributes #2 = { nounwind }
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!2, !3, !4}
+!llvm.ident = !{!5}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus_14, file: !1, 
producer: "clang version 15.0.0 (https://github.com/llvm/llvm-project.git 
8b2b9c3fa91ebe583f8c634482885a669b82a1f0)", isOptimized: true, runtimeVersion: 
0, splitDebugFilename: "split-debug-inlining-template.c.tmp.dwo", emissionKind: 
FullDebug, debugInfoForProfiling: true, nameTableKind: None)
+!1 = !DIFile(filename: "llvm-project/clang/test/CodeGen/", directory: 
"build-debug", checksumkind: CSK_MD5, checksum: 
"0fb39b3bb5a60928b5d9c251b2d91b2c")
+!2 = !{i32 7, !"Dwarf Version", i32 5}
+!3 = !{i32 2, !"Debug Info Version", i32 3}
+!4 = !{i32 1, !"wchar_size", i32 4}
+!5 = !{!"clang version 15.0.0 (https://github.com/llvm/llvm-project.git 
8b2b9c3fa91ebe583f8c634482885a669b82a1f0)"}
+!6 = distinct !DISubprogram(name: "f3", linkageName: "_Z2f3v", scope: !7, 
file: !7, line: 11, type: !8, scopeLine: 11, flags: DIFlagPrototyped | 
DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: 
!0, retainedNodes: !10)
+!7 = !DIFile(filename: 
"llvm-project/clang/test/CodeGen/split-debug-inlining-template.cpp", directory: 
"", checksumkind: CSK_MD5, checksum: "0fb39b3bb5a60928b5d9c251b2d91b2c")
+!8 = !DISubroutineType(types: !9)
+!9 = !{null}
+!10 = !{}
+!11 = !DILocation(line: 8, column: 3, scope: !12, inlinedAt: !16)
+!12 = distinct !DISubprogram(name: "f2", linkageName: "_Z2f2IiEvv", 
scope: !7, file: !7, line: 7, type: !8, scopeLine: 7, flags: DIFlagPrototyped | 
DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: 
!0, templateParams: !13, retainedNodes: !10)
+!13 = !{!14}
+!14 = !DITemplateTypeParameter(name: "T", type: !15)
+!15 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+!16 = distinct !DILocation(line: 12, column: 3, scope: !6)
+!17 = !DILocation(line: 13, column: 1, scope: !6)
+!18 = !DISubprogram(name: "f1", linkageName: "_Z2f1v", scope: !7, file: !7, 
line: 4, type: !8, flags: DIFlagPrototyped, spFlags: DISPFlagOptimized, 
retainedNodes: !10)
Index: llvm/lib/CodeGen/AsmPrinter/DIE.cpp
===
--- 

[PATCH] D119788: [AArch64] Add support for -march=native for Apple M1 CPU

2022-03-12 Thread Keith Smiley via Phabricator via cfe-commits
keith updated this revision to Diff 414878.
keith added a comment.

Fix typo


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119788

Files:
  clang/lib/Driver/ToolChains/Arch/AArch64.cpp
  llvm/lib/Support/Host.cpp

Index: llvm/lib/Support/Host.cpp
===
--- llvm/lib/Support/Host.cpp
+++ llvm/lib/Support/Host.cpp
@@ -38,6 +38,8 @@
 #include 
 #include 
 #include 
+#include 
+#include 
 #endif
 #ifdef _AIX
 #include 
@@ -1294,32 +1296,45 @@
   bool HaveVectorSupport = CVT[244] & 0x80;
   return getCPUNameFromS390Model(Id, HaveVectorSupport);
 }
-#elif defined(__APPLE__) && defined(__aarch64__)
-StringRef sys::getHostCPUName() {
-  return "cyclone";
-}
-#elif defined(__APPLE__) && defined(__arm__)
-StringRef sys::getHostCPUName() {
-  host_basic_info_data_t hostInfo;
-  mach_msg_type_number_t infoCount;
+#elif defined(__APPLE__) && (defined(__arm__) || defined(__aarch64__))
+#define CPUFAMILY_ARM_SWIFT 0x1e2d6381
+#define CPUFAMILY_ARM_CYCLONE 0x37a09642
+#define CPUFAMILY_ARM_TYPHOON 0x2c91a47e
+#define CPUFAMILY_ARM_TWISTER 0x92fb37c8
+#define CPUFAMILY_ARM_HURRICANE 0x67ceee93
+#define CPUFAMILY_ARM_MONSOON_MISTRAL 0xe81e7ef6
+#define CPUFAMILY_ARM_VORTEX_TEMPEST 0x07d34b9f
+#define CPUFAMILY_ARM_LIGHTNING_THUNDER 0x462504d2
+#define CPUFAMILY_ARM_FIRESTORM_ICESTORM 0x1b588bb3
 
-  infoCount = HOST_BASIC_INFO_COUNT;
-  mach_port_t hostPort = mach_host_self();
-  host_info(hostPort, HOST_BASIC_INFO, (host_info_t),
-);
-  mach_port_deallocate(mach_task_self(), hostPort);
+StringRef sys::getHostCPUName() {
+  uint32_t Family;
+  size_t Length = sizeof(Family);
+  sysctlbyname("hw.cpufamily", , , NULL, 0);
 
-  if (hostInfo.cpu_type != CPU_TYPE_ARM) {
-assert(false && "CPUType not equal to ARM should not be possible on ARM");
-return "generic";
+  switch (Family) {
+  case CPUFAMILY_ARM_SWIFT:
+return "swift";
+  case CPUFAMILY_ARM_CYCLONE:
+return "apple-a7";
+  case CPUFAMILY_ARM_TYPHOON:
+return "apple-a8";
+  case CPUFAMILY_ARM_TWISTER:
+return "apple-a9";
+  case CPUFAMILY_ARM_HURRICANE:
+return "apple-a10";
+  case CPUFAMILY_ARM_MONSOON_MISTRAL:
+return "apple-a11";
+  case CPUFAMILY_ARM_VORTEX_TEMPEST:
+return "apple-a12";
+  case CPUFAMILY_ARM_LIGHTNING_THUNDER:
+return "apple-a13";
+  case CPUFAMILY_ARM_FIRESTORM_ICESTORM:
+return "apple-m1";
+  default:
+// Default to the newest CPU we know about.
+return "apple-m1";
   }
-  switch (hostInfo.cpu_subtype) {
-case CPU_SUBTYPE_ARM_V7S:
-  return "swift";
-default:;
-}
-
-  return "generic";
 }
 #elif defined(_AIX)
 StringRef sys::getHostCPUName() {
@@ -1450,9 +1465,6 @@
 #elif defined(__linux__) && defined(__s390x__)
 int computeHostNumPhysicalCores() { return sysconf(_SC_NPROCESSORS_ONLN); }
 #elif defined(__APPLE__)
-#include 
-#include 
-
 // Gets the number of *physical cores* on the machine.
 int computeHostNumPhysicalCores() {
   uint32_t count;
Index: clang/lib/Driver/ToolChains/Arch/AArch64.cpp
===
--- clang/lib/Driver/ToolChains/Arch/AArch64.cpp
+++ clang/lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -151,6 +151,8 @@
   std::pair Split = StringRef(MarchLowerCase).split("+");
 
   llvm::AArch64::ArchKind ArchKind = llvm::AArch64::parseArch(Split.first);
+  if (Split.first == "native")
+ArchKind = llvm::AArch64::getCPUArchKind(llvm::sys::getHostCPUName().str());
   if (ArchKind == llvm::AArch64::ArchKind::INVALID ||
   !llvm::AArch64::getArchFeatures(ArchKind, Features))
 return false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D120296: [Attr] Fix a btf_type_tag AST generation bug

2022-03-12 Thread Yonghong Song via Phabricator via cfe-commits
yonghong-song updated this revision to Diff 414872.
yonghong-song added a comment.

- fix one 'auto' declaration issue
- rework on the test with overloadable attribute.


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

https://reviews.llvm.org/D120296

Files:
  clang/include/clang-c/Index.h
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/ASTNodeTraverser.h
  clang/include/clang/AST/PropertiesBase.td
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/AST/Type.h
  clang/include/clang/AST/TypeLoc.h
  clang/include/clang/AST/TypeProperties.td
  clang/include/clang/Basic/TypeNodes.td
  clang/include/clang/Serialization/ASTRecordReader.h
  clang/include/clang/Serialization/ASTRecordWriter.h
  clang/include/clang/Serialization/TypeBitCodes.def
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ASTStructuralEquivalence.cpp
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/TypeLoc.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDebugInfo.h
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaType.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/CodeGen/attr-btf_type_tag-similar-type.c
  clang/test/PCH/btf_type_tag_attr.c
  clang/test/Sema/attr-btf_type_tag.c
  clang/tools/libclang/CIndex.cpp
  clang/tools/libclang/CXType.cpp

Index: clang/tools/libclang/CXType.cpp
===
--- clang/tools/libclang/CXType.cpp
+++ clang/tools/libclang/CXType.cpp
@@ -116,6 +116,7 @@
 TKCASE(Elaborated);
 TKCASE(Pipe);
 TKCASE(Attributed);
+TKCASE(BTFTagAttributed);
 TKCASE(Atomic);
 default:
   return CXType_Unexposed;
@@ -136,6 +137,10 @@
 return MakeCXType(ATT->getEquivalentType(), TU);
   }
 }
+if (auto *ATT = T->getAs()) {
+  if (!(TU->ParsingOptions & CXTranslationUnit_IncludeAttributedTypes))
+return MakeCXType(ATT->getWrappedType(), TU);
+}
 // Handle paren types as the original type
 if (auto *PTT = T->getAs()) {
   return MakeCXType(PTT->getInnerType(), TU);
@@ -610,6 +615,7 @@
 TKIND(Elaborated);
 TKIND(Pipe);
 TKIND(Attributed);
+TKIND(BTFTagAttributed);
 TKIND(BFloat16);
 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) TKIND(Id);
 #include "clang/Basic/OpenCLImageTypes.def"
@@ -1051,6 +1057,9 @@
   if (auto *ATT = T->getAs())
 return MakeCXType(ATT->getModifiedType(), GetTU(CT));
 
+  if (auto *ATT = T->getAs())
+return MakeCXType(ATT->getWrappedType(), GetTU(CT));
+
   return MakeCXType(QualType(), GetTU(CT));
 }
 
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -1672,6 +1672,10 @@
   return Visit(TL.getModifiedLoc());
 }
 
+bool CursorVisitor::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
+  return Visit(TL.getWrappedLoc());
+}
+
 bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
  bool SkipResultType) {
   if (!SkipResultType && Visit(TL.getReturnLoc()))
Index: clang/test/Sema/attr-btf_type_tag.c
===
--- clang/test/Sema/attr-btf_type_tag.c
+++ clang/test/Sema/attr-btf_type_tag.c
@@ -23,3 +23,15 @@
 int __tag4 * __tag5 * __tag6 *foo1(struct t __tag1 * __tag2 * __tag3 *a1) {
   return (int __tag4 * __tag5 * __tag6 *)a1[0][0]->d;
 }
+
+// The btf_type_tag attribute will be ignored during _Generic type matching
+int g1 = _Generic((int *)0, int __tag1 *: 0);
+int g2 = _Generic((int __tag1 *)0, int *: 0);
+
+// The btf_type_tag attribute will be ignored during overloadable type matching
+void bar2(int __tag1 *a) __attribute__((overloadable)) { asm volatile (""); } // expected-note {{previous definition is here}}
+void bar2(int *a) __attribute__((overloadable)) { asm volatile (""); } // expected-error {{redefinition of 'bar2'}}
+void foo2(int __tag1 *a, int *b) {
+  bar2(a);
+  bar2(b);
+}
Index: clang/test/PCH/btf_type_tag_attr.c
===
--- /dev/null
+++ clang/test/PCH/btf_type_tag_attr.c
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -emit-pch -o %t %s
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -include-pch %t \
+// RUN:   -fsyntax-only -verify %s
+
+// expected-no-diagnostics
+
+int __attribute__((btf_type_tag("tag1"))) __attribute__((btf_type_tag("tag2"))) *p;
Index: clang/test/CodeGen/attr-btf_type_tag-similar-type.c
===
--- /dev/null
+++ clang/test/CodeGen/attr-btf_type_tag-similar-type.c
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -triple %itanium_abi_triple -debug-info-kind=limited -S -emit-llvm -o - %s | FileCheck %s
+
+struct map_value {
+   

[PATCH] D120610: [DebugInfo] Include DW_TAG_skeleton_unit when looking for parent UnitDie

2022-03-12 Thread David Blaikie via Phabricator via cfe-commits
dblaikie accepted this revision.
dblaikie added a comment.
This revision is now accepted and ready to land.

Thanks, sounds good!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120610

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


[PATCH] D121533: [clang][deps] Fix traversal of precompiled dependencies

2022-03-12 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: Bigcheese, dexonsmith.
Herald added a project: All.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The code for traversing precompiled dependencies is somewhat complicated and 
contains a dangling iterator bug.

This patch uses simpler, recursive implementation.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121533

Files:
  clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp


Index: clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -84,33 +84,18 @@
 PrebuiltModuleFilesT ,
 llvm::StringSet<> ,
 bool VisitInputFiles) {
-  // Maps the names of modules that weren't yet visited to their PCM path.
-  llvm::StringMap ModuleFilesWorklist;
-  // Contains PCM paths of all visited modules.
-  llvm::StringSet<> VisitedModuleFiles;
-
-  PrebuiltModuleListener Listener(ModuleFilesWorklist, InputFiles,
-  VisitInputFiles);
-
-  auto GatherModuleFileInfo = [&](StringRef ASTFile) {
-ASTReader::readASTFileControlBlock(
-ASTFile, CI.getFileManager(), CI.getPCHContainerReader(),
-/*FindModuleFileExtensions=*/false, Listener,
-/*ValidateDiagnosticOptions=*/false);
-  };
-
-  GatherModuleFileInfo(PrebuiltModuleFilename);
-  while (!ModuleFilesWorklist.empty()) {
-auto WorklistItemIt = ModuleFilesWorklist.begin();
-
-if (!VisitedModuleFiles.contains(WorklistItemIt->getValue())) {
-  VisitedModuleFiles.insert(WorklistItemIt->getValue());
-  GatherModuleFileInfo(WorklistItemIt->getValue());
-  ModuleFiles[WorklistItemIt->getKey().str()] = WorklistItemIt->getValue();
-}
-
-ModuleFilesWorklist.erase(WorklistItemIt);
-  }
+  // Maps the names of imported modules to their PCM paths.
+  llvm::StringMap Imports;
+  PrebuiltModuleListener Listener(Imports, InputFiles, VisitInputFiles);
+  ASTReader::readASTFileControlBlock(
+  PrebuiltModuleFilename, CI.getFileManager(), CI.getPCHContainerReader(),
+  /*FindModuleFileExtensions=*/false, Listener,
+  /*ValidateDiagnosticOptions=*/false);
+
+  for (const auto  : Imports)
+if (ModuleFiles.insert({Import.getKey().str(), Import.getValue()}).second)
+  visitPrebuiltModule(Import.getValue(), CI, ModuleFiles, InputFiles,
+  VisitInputFiles);
 }
 
 /// Transform arbitrary file name into an object-like file name.


Index: clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -84,33 +84,18 @@
 PrebuiltModuleFilesT ,
 llvm::StringSet<> ,
 bool VisitInputFiles) {
-  // Maps the names of modules that weren't yet visited to their PCM path.
-  llvm::StringMap ModuleFilesWorklist;
-  // Contains PCM paths of all visited modules.
-  llvm::StringSet<> VisitedModuleFiles;
-
-  PrebuiltModuleListener Listener(ModuleFilesWorklist, InputFiles,
-  VisitInputFiles);
-
-  auto GatherModuleFileInfo = [&](StringRef ASTFile) {
-ASTReader::readASTFileControlBlock(
-ASTFile, CI.getFileManager(), CI.getPCHContainerReader(),
-/*FindModuleFileExtensions=*/false, Listener,
-/*ValidateDiagnosticOptions=*/false);
-  };
-
-  GatherModuleFileInfo(PrebuiltModuleFilename);
-  while (!ModuleFilesWorklist.empty()) {
-auto WorklistItemIt = ModuleFilesWorklist.begin();
-
-if (!VisitedModuleFiles.contains(WorklistItemIt->getValue())) {
-  VisitedModuleFiles.insert(WorklistItemIt->getValue());
-  GatherModuleFileInfo(WorklistItemIt->getValue());
-  ModuleFiles[WorklistItemIt->getKey().str()] = WorklistItemIt->getValue();
-}
-
-ModuleFilesWorklist.erase(WorklistItemIt);
-  }
+  // Maps the names of imported modules to their PCM paths.
+  llvm::StringMap Imports;
+  PrebuiltModuleListener Listener(Imports, InputFiles, VisitInputFiles);
+  ASTReader::readASTFileControlBlock(
+  PrebuiltModuleFilename, CI.getFileManager(), CI.getPCHContainerReader(),
+  /*FindModuleFileExtensions=*/false, Listener,
+  /*ValidateDiagnosticOptions=*/false);
+
+  for (const auto  : Imports)
+if (ModuleFiles.insert({Import.getKey().str(), Import.getValue()}).second)
+  visitPrebuiltModule(Import.getValue(), CI, ModuleFiles, InputFiles,
+  VisitInputFiles);
 }
 
 /// Transform arbitrary file name 

[PATCH] D121245: [clang][parser] Allow GNU attributes before namespace identifier

2022-03-12 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX marked an inline comment as done.
ArcsinX added inline comments.



Comment at: clang/lib/Parse/ParseDeclCXX.cpp:79
+
+  auto ReadLabelAttrubutes = [&] {
+// Read label attributes, if present.

aaron.ballman wrote:
> However, I don't think there's a reason we need this lambda -- it seems we 
> can call `MaybeParseGNUAttributes()` instead, and get the attribute location 
> from the `ParsedAttributesWithRange` object passed in.
`MaybeParseAttributes(PAKM_GNU | PAKM_CXX11, Attrs)` parses different kind of 
attributes in a loop (e.g. `struct __attribute__(()) [[]] [[]] 
__attribute__(()) S {};` is valid for clang), but we can't use it because we 
need to warn about c++11 attributes usage for namespace if c++ < 17. So, I 
added a lambda which works similar to `MaybeParseAttributes()`.

Thus, now clang handles attributes for namespace like it handle attributes for 
structure.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121245

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


[PATCH] D121532: [Clang][WIP] Fix Unevaluated Lambdas

2022-03-12 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin created this revision.
Herald added a subscriber: martong.
Herald added a reviewer: shafik.
Herald added a project: All.
cor3ntin requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Unlike other types, when lambdas are instanciated,
they are recreated from scratch.
When an unevaluated lambdas appear in the type of a function,
parameter it is instanciated in the wrong declaration context,
as parameters are transformed before the function.

To support lambda in function parameters, we try to
compute whether they are dependant without looking at the
declaration context.

This is a short term stopgap solution to avoid clang
iceing. A better fix might be to inject some kind of
transparent declaration with correctly computed dependency
for function parameters, variable templates, etc.

Fixes https://github.com/llvm/llvm-project/issues/50376
Fixes https://github.com/llvm/llvm-project/issues/51414
Fixes https://github.com/llvm/llvm-project/issues/51416
Fixes https://github.com/llvm/llvm-project/issues/51641
Fixes https://github.com/llvm/llvm-project/issues/54296


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121532

Files:
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/DeclBase.cpp
  clang/lib/AST/DeclCXX.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/SemaCXX/lambda-unevaluated.cpp

Index: clang/test/SemaCXX/lambda-unevaluated.cpp
===
--- clang/test/SemaCXX/lambda-unevaluated.cpp
+++ clang/test/SemaCXX/lambda-unevaluated.cpp
@@ -30,6 +30,27 @@
 auto e = g(0); // expected-error{{no matching function for call}}
 // expected-note@-2 {{substitution failure}}
 
+template 
+auto foo(decltype([] {
+  return [] { return T(); }();
+})) {}
+
+void test() {
+  foo({});
+}
+
+template 
+struct C {
+  template 
+  auto foo(decltype([] {
+return [] { return T(); }();
+  })) {}
+};
+
+void test2() {
+  C{}.foo({});
+}
+
 namespace PR52073 {
 // OK, these are distinct functions not redefinitions.
 template void f(decltype([]{})) {} // expected-note {{candidate}}
@@ -40,6 +61,62 @@
 template void g(const char (*)[([]{ return N; })()]) {} // expected-note {{candidate}}
 template void g(const char (*)[([]{ return N; })()]) {} // expected-note {{candidate}}
 // FIXME: We instantiate the lambdas into the context of the function template,
-// so we think they're dependent and can't evaluate a call to them.
+//  so we think they're dependent and can't evaluate a call to them.
 void use_g() { g<6>(&"hello"); } // expected-error {{no matching function}}
 }
+
+namespace GH51416 {
+
+template 
+struct A {
+  void spam(decltype([] {}));
+};
+
+template 
+void A::spam(decltype([] {})) // expected-error{{out-of-line definition of 'spam' does not match}}
+{}
+
+struct B {
+  template 
+  void spam(decltype([] {}));
+};
+
+template 
+void B::spam(decltype([] {})) {} // expected-error{{out-of-line definition of 'spam' does not match}}
+
+} // namespace GH51416
+
+namespace GH50376 {
+
+template 
+struct foo_t {// expected-note 2{{candidate constructor}}
+  foo_t(T ptr) {} // expected-note{{candidate constructor}}
+};
+
+template 
+using alias = foo_t;
+
+template 
+auto fun(T const ) -> alias {
+  return alias{t}; // expected-error{{no viable conversion from returned value of type 'alias<...>'}}
+}
+
+void f() {
+  int i;
+  auto const error = fun(i); // expected-note{{in instantiation}}
+}
+
+} // namespace GH50376
+
+namespace GH51414 {
+template  void spam(decltype([] {}) (*s)[sizeof(T)] = nullptr) {}
+void foo() {
+  spam();
+}
+} // namespace GH51414
+
+namespace GH51641 {
+template 
+void foo(decltype(+[](T) {}) lambda, T param);
+static_assert(!__is_same(decltype(foo), void));
+} // namespace GH51641
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -5727,7 +5727,7 @@
   // Add lambda-specific data.
   if (Data.IsLambda) {
 auto  = D->getLambdaData();
-Record->push_back(Lambda.Dependent);
+Record->push_back(Lambda.DependencyKind);
 Record->push_back(Lambda.IsGenericLambda);
 Record->push_back(Lambda.CaptureDefault);
 Record->push_back(Lambda.NumCaptures);
Index: clang/lib/Serialization/ASTReaderDecl.cpp
===
--- clang/lib/Serialization/ASTReaderDecl.cpp
+++ clang/lib/Serialization/ASTReaderDecl.cpp
@@ -1801,7 +1801,7 @@
 using Capture = LambdaCapture;
 
 auto  = static_cast(Data);
-Lambda.Dependent = Record.readInt();
+Lambda.DependencyKind = Record.readInt();
 Lambda.IsGenericLambda = 

[PATCH] D121245: [clang][parser] Allow GNU attributes before namespace identifier

2022-03-12 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX updated this revision to Diff 414868.
ArcsinX added a comment.

- get attributes location from ParsedAttributesWithRange object
- parse subsequent attributes of different kinds in a loop


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121245

Files:
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/test/Parser/namespace-attributes.cpp

Index: clang/test/Parser/namespace-attributes.cpp
===
--- /dev/null
+++ clang/test/Parser/namespace-attributes.cpp
@@ -0,0 +1,41 @@
+// RUN: %clang_cc1 -std=c++17 -verify %s
+
+namespace __attribute__(()) A
+{
+}
+
+namespace A __attribute__(())
+{
+}
+
+namespace __attribute__(()) [[]] A
+{
+}
+
+namespace [[]] __attribute__(()) A
+{
+}
+
+namespace A __attribute__(()) [[]]
+{
+}
+
+namespace A [[]] __attribute__(())
+{
+}
+
+namespace [[]] A __attribute__(())
+{
+}
+
+namespace __attribute__(()) A [[]]
+{
+}
+
+namespace A::B __attribute__(()) // expected-error{{attributes cannot be specified on a nested namespace definition}}
+{
+}
+
+namespace __attribute__(()) A::B // expected-error{{attributes cannot be specified on a nested namespace definition}}
+{
+}
Index: clang/lib/Parse/ParseDeclCXX.cpp
===
--- clang/lib/Parse/ParseDeclCXX.cpp
+++ clang/lib/Parse/ParseDeclCXX.cpp
@@ -74,15 +74,27 @@
   SourceLocation FirstNestedInlineLoc;
 
   ParsedAttributesWithRange attrs(AttrFactory);
-  SourceLocation attrLoc;
-  if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
-Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
-? diag::warn_cxx14_compat_ns_enum_attribute
-: diag::ext_ns_enum_attribute)
-  << 0 /*namespace*/;
-attrLoc = Tok.getLocation();
-ParseCXX11Attributes(attrs);
-  }
+
+  auto ReadAttributes = [&] {
+bool MoreToParse;
+do {
+  MoreToParse = false;
+  if (Tok.is(tok::kw___attribute)) {
+ParseGNUAttributes(attrs);
+MoreToParse = true;
+  }
+  if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
+Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
+? diag::warn_cxx14_compat_ns_enum_attribute
+: diag::ext_ns_enum_attribute)
+<< 0 /*namespace*/;
+ParseCXX11Attributes(attrs);
+MoreToParse = true;
+  }
+} while (MoreToParse);
+  };
+
+  ReadAttributes();
 
   if (Tok.is(tok::identifier)) {
 Ident = Tok.getIdentifierInfo();
@@ -108,16 +120,14 @@
 }
   }
 
+  ReadAttributes();
+
+  SourceLocation attrLoc = attrs.Range.getBegin();
+
   // A nested namespace definition cannot have attributes.
   if (!ExtraNSs.empty() && attrLoc.isValid())
 Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
 
-  // Read label attributes, if present.
-  if (Tok.is(tok::kw___attribute)) {
-attrLoc = Tok.getLocation();
-ParseGNUAttributes(attrs);
-  }
-
   if (Tok.is(tok::equal)) {
 if (!Ident) {
   Diag(Tok, diag::err_expected) << tok::identifier;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D119788: [AArch64] Add support for -march=native for Apple M1 CPU

2022-03-12 Thread Keith Smiley via Phabricator via cfe-commits
keith updated this revision to Diff 414866.
keith added a comment.
Herald added a project: All.

Update default to latest known CPU


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119788

Files:
  clang/lib/Driver/ToolChains/Arch/AArch64.cpp
  llvm/lib/Support/Host.cpp

Index: llvm/lib/Support/Host.cpp
===
--- llvm/lib/Support/Host.cpp
+++ llvm/lib/Support/Host.cpp
@@ -38,6 +38,8 @@
 #include 
 #include 
 #include 
+#include 
+#include 
 #endif
 #ifdef _AIX
 #include 
@@ -1294,32 +1296,45 @@
   bool HaveVectorSupport = CVT[244] & 0x80;
   return getCPUNameFromS390Model(Id, HaveVectorSupport);
 }
-#elif defined(__APPLE__) && defined(__aarch64__)
-StringRef sys::getHostCPUName() {
-  return "cyclone";
-}
-#elif defined(__APPLE__) && defined(__arm__)
-StringRef sys::getHostCPUName() {
-  host_basic_info_data_t hostInfo;
-  mach_msg_type_number_t infoCount;
+#elif defined(__APPLE__) && (defined(__arm__) || defined(__aarch64__))
+#define CPUFAMILY_ARM_SWIFT 0x1e2d6381
+#define CPUFAMILY_ARM_CYCLONE 0x37a09642
+#define CPUFAMILY_ARM_TYPHOON 0x2c91a47e
+#define CPUFAMILY_ARM_TWISTER 0x92fb37c8
+#define CPUFAMILY_ARM_HURRICANE 0x67ceee93
+#define CPUFAMILY_ARM_MONSOON_MISTRAL 0xe81e7ef6
+#define CPUFAMILY_ARM_VORTEX_TEMPEST 0x07d34b9f
+#define CPUFAMILY_ARM_LIGHTNING_THUNDER 0x462504d2
+#define CPUFAMILY_ARM_FIRESTORM_ICESTORM 0x1b588bb3
 
-  infoCount = HOST_BASIC_INFO_COUNT;
-  mach_port_t hostPort = mach_host_self();
-  host_info(hostPort, HOST_BASIC_INFO, (host_info_t),
-);
-  mach_port_deallocate(mach_task_self(), hostPort);
+StringRef sys::getHostCPUName() {
+  uint32_t Family;
+  size_t Length = sizeof(Family);
+  sysctlbyname("hw.cpufamily", , , NULL, 0);
 
-  if (hostInfo.cpu_type != CPU_TYPE_ARM) {
-assert(false && "CPUType not equal to ARM should not be possible on ARM");
-return "generic";
+  switch (Family) {
+  case CPUFAMILY_ARM_SWIFT:
+return "swift";
+  case CPUFAMILY_ARM_CYCLONE:
+return "apple-a7";
+  case CPUFAMILY_ARM_TYPHOON:
+return "apple-a8";
+  case CPUFAMILY_ARM_TWISTER:
+return "apple-a9";
+  case CPUFAMILY_ARM_HURRICANE:
+return "apple-a10";
+  case CPUFAMILY_ARM_MONSOON_MISTRAL:
+return "apple-a11";
+  case CPUFAMILY_ARM_VORTEX_TEMPEST:
+return "apple-a12";
+  case CPUFAMILY_ARM_LIGHTNING_THUNDER:
+return "apple-a13";
+  case CPUFAMILY_ARM_FIRESTORM_ICESTORM:
+return "apple-m1";
+  default:
+// Default to the knewest CPU we know about.
+return "apple-m1";
   }
-  switch (hostInfo.cpu_subtype) {
-case CPU_SUBTYPE_ARM_V7S:
-  return "swift";
-default:;
-}
-
-  return "generic";
 }
 #elif defined(_AIX)
 StringRef sys::getHostCPUName() {
@@ -1450,9 +1465,6 @@
 #elif defined(__linux__) && defined(__s390x__)
 int computeHostNumPhysicalCores() { return sysconf(_SC_NPROCESSORS_ONLN); }
 #elif defined(__APPLE__)
-#include 
-#include 
-
 // Gets the number of *physical cores* on the machine.
 int computeHostNumPhysicalCores() {
   uint32_t count;
Index: clang/lib/Driver/ToolChains/Arch/AArch64.cpp
===
--- clang/lib/Driver/ToolChains/Arch/AArch64.cpp
+++ clang/lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -151,6 +151,8 @@
   std::pair Split = StringRef(MarchLowerCase).split("+");
 
   llvm::AArch64::ArchKind ArchKind = llvm::AArch64::parseArch(Split.first);
+  if (Split.first == "native")
+ArchKind = llvm::AArch64::getCPUArchKind(llvm::sys::getHostCPUName().str());
   if (ArchKind == llvm::AArch64::ArchKind::INVALID ||
   !llvm::AArch64::getArchFeatures(ArchKind, Features))
 return false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D100692: clang-tidy: discover binaries in build dir

2022-03-12 Thread Keith Smiley via Phabricator via cfe-commits
keith added a comment.
Herald added subscribers: cfe-commits, carlosgalvezp.
Herald added a project: All.

Ping, it seems like https://reviews.llvm.org/D101037 is stalled but the docs at 
this point state py >=3.6 is required for working on llvm so I think we're good 
here https://llvm.org/docs/GettingStarted.html#software


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D100692

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


[PATCH] D109977: LLVM Driver Multicall tool

2022-03-12 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.
Herald added a project: All.

In D109977#3282545 , @MaskRay wrote:

> I have tried the latest diff but 
> `-DLLVM_ENABLE_PROJECTS='clang;clang-tools-extra;flang;lldb;lld;compiler-rt;openmp;mlir;cross-project-tests'
>  -DLLVM_TOOL_LLVM_DRIVER_BUILD=on` gives me:
>
>   CMake Error at cmake/modules/LLVM-Config.cmake:110 (target_link_libraries): 
> 
> The keyword signature for target_link_libraries has already been used 
> with
> the target "obj.dsymutil".  All uses of target_link_libraries with a 
> target   
> must be either all-keyword or all-plain.  
> 
>   
> 
> The uses of the keyword signature are here:   
>   
>   
> 
>  * cmake/modules/AddLLVM.cmake:897 (target_link_libraries)
> 
>   
> 
>   Call Stack (most recent call first):
> 
> cmake/modules/LLVM-Config.cmake:95 (explicit_llvm_config) 
> 
> cmake/modules/AddLLVM.cmake:898 (llvm_config) 
>   
> cmake/modules/AddLLVM.cmake:1264 (add_llvm_executable)
>   
> tools/dsymutil/CMakeLists.txt:21 (add_llvm_tool)

⬆️


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109977

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


[PATCH] D121076: [MLIR][Python] Add SCFIfOp Python binding

2022-03-12 Thread Mehdi AMINI via Phabricator via cfe-commits
mehdi_amini added a comment.

Seems like there is a local base commit in your repository: you're not 
uploading a diff that applies on HEAD.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121076

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


[PATCH] D121069: [clang-format] Minimize the damage caused by AlignArrayOfStructures when working on non square arrays

2022-03-12 Thread MyDeveloperDay 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 rGadfe58b09df9: [clang-format] Minimize the damage caused by 
AlignArrayOfStructures when… (authored by MyDeveloperDay).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121069

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

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -25335,6 +25335,138 @@
   verifyFormat("#define A x%:%:y");
 }
 
+TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) {
+  auto Style = getLLVMStyle();
+  Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
+  Style.AlignConsecutiveAssignments =
+  FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
+  Style.AlignConsecutiveDeclarations =
+  FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
+
+  // The AlignArray code is incorrect for non square Arrays and can cause
+  // crashes, these tests assert that the array is not changed but will
+  // also act as regression tests for when it is properly fixed
+  verifyFormat("struct test demo[] = {\n"
+   "{1, 2},\n"
+   "{3, 4, 5},\n"
+   "{6, 7, 8}\n"
+   "};",
+   Style);
+  verifyFormat("struct test demo[] = {\n"
+   "{1, 2, 3, 4, 5},\n"
+   "{3, 4, 5},\n"
+   "{6, 7, 8}\n"
+   "};",
+   Style);
+  verifyFormat("struct test demo[] = {\n"
+   "{1, 2, 3, 4, 5},\n"
+   "{3, 4, 5},\n"
+   "{6, 7, 8, 9, 10, 11, 12}\n"
+   "};",
+   Style);
+  verifyFormat("struct test demo[] = {\n"
+   "{1, 2, 3},\n"
+   "{3, 4, 5},\n"
+   "{6, 7, 8, 9, 10, 11, 12}\n"
+   "};",
+   Style);
+
+  verifyFormat("S{\n"
+   "{},\n"
+   "{},\n"
+   "{a, b}\n"
+   "};",
+   Style);
+  verifyFormat("S{\n"
+   "{},\n"
+   "{},\n"
+   "{a, b},\n"
+   "};",
+   Style);
+  verifyFormat("void foo() {\n"
+   "  auto thing = test{\n"
+   "  {\n"
+   "   {13}, {something}, // A\n"
+   "  }\n"
+   "  };\n"
+   "}",
+   "void foo() {\n"
+   "  auto thing = test{\n"
+   "  {\n"
+   "   {13},\n"
+   "   {something}, // A\n"
+   "  }\n"
+   "  };\n"
+   "}",
+   Style);
+}
+
+TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) {
+  auto Style = getLLVMStyle();
+  Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
+  Style.AlignConsecutiveAssignments =
+  FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
+  Style.AlignConsecutiveDeclarations =
+  FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
+
+  // The AlignArray code is incorrect for non square Arrays and can cause
+  // crashes, these tests assert that the array is not changed but will
+  // also act as regression tests for when it is properly fixed
+  verifyFormat("struct test demo[] = {\n"
+   "{1, 2},\n"
+   "{3, 4, 5},\n"
+   "{6, 7, 8}\n"
+   "};",
+   Style);
+  verifyFormat("struct test demo[] = {\n"
+   "{1, 2, 3, 4, 5},\n"
+   "{3, 4, 5},\n"
+   "{6, 7, 8}\n"
+   "};",
+   Style);
+  verifyFormat("struct test demo[] = {\n"
+   "{1, 2, 3, 4, 5},\n"
+   "{3, 4, 5},\n"
+   "{6, 7, 8, 9, 10, 11, 12}\n"
+   "};",
+   Style);
+  verifyFormat("struct test demo[] = {\n"
+   "{1, 2, 3},\n"
+   "{3, 4, 5},\n"
+   "{6, 7, 8, 9, 10, 11, 12}\n"
+   "};",
+   Style);
+
+  verifyFormat("S{\n"
+   "{},\n"
+   "{},\n"
+   "{a, b}\n"
+   "};",
+   Style);
+  verifyFormat("S{\n"
+   "{},\n"
+   "{},\n"
+   "{a, b},\n"
+   "};",
+   Style);
+  verifyFormat("void foo() {\n"
+   "  auto thing = test{\n"
+   "  {\n"
+   "   {13}, {something}, // A\n"
+   "  }\n"
+   "  };\n"
+   

[clang] adfe58b - [clang-format] Minimize the damage caused by AlignArrayOfStructures when working on non square arrays

2022-03-12 Thread via cfe-commits

Author: mydeveloperday
Date: 2022-03-12T17:22:31Z
New Revision: adfe58b09df957f8911c5e152daa9564e5931631

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

LOG: [clang-format] Minimize the damage caused by AlignArrayOfStructures when 
working on non square arrays

I have lost count of the number of times this has been reported, but it 
fundamentally comes down to the fact that the "AlignArrayLeft/Right" function 
is fundamentally broken for non-square arrays.

As a result, a pointer can end up running off the end of the array structure, 
I've spent the last 2 weekends trying to rewrite this algorithm but I've 
struggled to get it aligned correctly.

This is an interim fix, that ignores all array that are non-square and leaves 
them alone. I think this can allow us to close out most of the crashes (if not 
all).

I think this can help reduce the number of bugs coming in that are duplicates.

https://github.com/llvm/llvm-project/issues/53748
https://github.com/llvm/llvm-project/issues/51767
https://github.com/llvm/llvm-project/issues/51277

Reviewed By: curdeius, HazardyKnusperkeks, feg208

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

Added: 


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

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 473cf9cb192e8..1f2e94940b53c 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -236,6 +236,9 @@ the configuration (without a prefix: ``Auto``).
   if not ``None``, when using initialization for an array of structs
   aligns the fields into columns.
 
+  NOTE: As of clang-format 15 this option only applied to arrays with equal
+  number of columns per row.
+
   Possible values:
 
   * ``AIAS_Left`` (in configuration: ``Left``)

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 81f8190211ec5..49b932c8d16e1 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -131,6 +131,10 @@ struct FormatStyle {
   };
   /// if not ``None``, when using initialization for an array of structs
   /// aligns the fields into columns.
+  ///
+  /// NOTE: As of clang-format 15 this option only applied to arrays with equal
+  /// number of columns per row.
+  ///
   /// \version 13
   ArrayInitializerAlignmentStyle AlignArrayOfStructures;
 

diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index 55e0b7f8e8d9e..b62fdb33722a3 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1032,11 +1032,13 @@ void WhitespaceManager::alignArrayInitializers(unsigned 
Start, unsigned End) {
 
 void WhitespaceManager::alignArrayInitializersRightJustified(
 CellDescriptions &) {
-  auto  = CellDescs.Cells;
+  if (!CellDescs.isRectangular())
+return;
 
+  auto  = CellDescs.Cells;
   // Now go through and fixup the spaces.
   auto *CellIter = Cells.begin();
-  for (auto i = 0U; i < CellDescs.CellCount; ++i, ++CellIter) {
+  for (auto i = 0U; i < CellDescs.CellCounts[0]; ++i, ++CellIter) {
 unsigned NetWidth = 0U;
 if (isSplitCell(*CellIter))
   NetWidth = getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
@@ -1058,16 +1060,16 @@ void 
WhitespaceManager::alignArrayInitializersRightJustified(
   if (CellIter != Cells.begin()) {
 auto ThisNetWidth =
 getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
-auto MaxNetWidth =
-getMaximumNetWidth(Cells.begin(), CellIter, 
CellDescs.InitialSpaces,
-   CellDescs.CellCount);
+auto MaxNetWidth = getMaximumNetWidth(
+Cells.begin(), CellIter, CellDescs.InitialSpaces,
+CellDescs.CellCounts[0], CellDescs.CellCounts.size());
 if (ThisNetWidth < MaxNetWidth)
   Changes[CellIter->Index].Spaces = (MaxNetWidth - ThisNetWidth);
 auto RowCount = 1U;
 auto Offset = std::distance(Cells.begin(), CellIter);
 for (const auto *Next = CellIter->NextColumnElement; Next != nullptr;
  Next = Next->NextColumnElement) {
-  auto *Start = (Cells.begin() + RowCount * CellDescs.CellCount);
+  auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
   auto *End = Start + Offset;
   ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
   if (ThisNetWidth < MaxNetWidth)
@@ -1100,8 +1102,11 @@ void 
WhitespaceManager::alignArrayInitializersRightJustified(
 
 

[PATCH] D121069: [clang-format] Minimize the damage caused by AlignArrayOfStructures when working on non square arrays

2022-03-12 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 414857.
MyDeveloperDay marked 10 inline comments as done.
MyDeveloperDay added a comment.

Fixing final review comments prior to commit


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

https://reviews.llvm.org/D121069

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

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -25315,6 +25315,138 @@
   verifyFormat("#define A x%:%:y");
 }
 
+TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) {
+  auto Style = getLLVMStyle();
+  Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
+  Style.AlignConsecutiveAssignments =
+  FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
+  Style.AlignConsecutiveDeclarations =
+  FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
+
+  // The AlignArray code is incorrect for non square Arrays and can cause
+  // crashes, these tests assert that the array is not changed but will
+  // also act as regression tests for when it is properly fixed
+  verifyFormat("struct test demo[] = {\n"
+   "{1, 2},\n"
+   "{3, 4, 5},\n"
+   "{6, 7, 8}\n"
+   "};",
+   Style);
+  verifyFormat("struct test demo[] = {\n"
+   "{1, 2, 3, 4, 5},\n"
+   "{3, 4, 5},\n"
+   "{6, 7, 8}\n"
+   "};",
+   Style);
+  verifyFormat("struct test demo[] = {\n"
+   "{1, 2, 3, 4, 5},\n"
+   "{3, 4, 5},\n"
+   "{6, 7, 8, 9, 10, 11, 12}\n"
+   "};",
+   Style);
+  verifyFormat("struct test demo[] = {\n"
+   "{1, 2, 3},\n"
+   "{3, 4, 5},\n"
+   "{6, 7, 8, 9, 10, 11, 12}\n"
+   "};",
+   Style);
+
+  verifyFormat("S{\n"
+   "{},\n"
+   "{},\n"
+   "{a, b}\n"
+   "};",
+   Style);
+  verifyFormat("S{\n"
+   "{},\n"
+   "{},\n"
+   "{a, b},\n"
+   "};",
+   Style);
+  verifyFormat("void foo() {\n"
+   "  auto thing = test{\n"
+   "  {\n"
+   "   {13}, {something}, // A\n"
+   "  }\n"
+   "  };\n"
+   "}",
+   "void foo() {\n"
+   "  auto thing = test{\n"
+   "  {\n"
+   "   {13},\n"
+   "   {something}, // A\n"
+   "  }\n"
+   "  };\n"
+   "}",
+   Style);
+}
+
+TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) {
+  auto Style = getLLVMStyle();
+  Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
+  Style.AlignConsecutiveAssignments =
+  FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
+  Style.AlignConsecutiveDeclarations =
+  FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
+
+  // The AlignArray code is incorrect for non square Arrays and can cause
+  // crashes, these tests assert that the array is not changed but will
+  // also act as regression tests for when it is properly fixed
+  verifyFormat("struct test demo[] = {\n"
+   "{1, 2},\n"
+   "{3, 4, 5},\n"
+   "{6, 7, 8}\n"
+   "};",
+   Style);
+  verifyFormat("struct test demo[] = {\n"
+   "{1, 2, 3, 4, 5},\n"
+   "{3, 4, 5},\n"
+   "{6, 7, 8}\n"
+   "};",
+   Style);
+  verifyFormat("struct test demo[] = {\n"
+   "{1, 2, 3, 4, 5},\n"
+   "{3, 4, 5},\n"
+   "{6, 7, 8, 9, 10, 11, 12}\n"
+   "};",
+   Style);
+  verifyFormat("struct test demo[] = {\n"
+   "{1, 2, 3},\n"
+   "{3, 4, 5},\n"
+   "{6, 7, 8, 9, 10, 11, 12}\n"
+   "};",
+   Style);
+
+  verifyFormat("S{\n"
+   "{},\n"
+   "{},\n"
+   "{a, b}\n"
+   "};",
+   Style);
+  verifyFormat("S{\n"
+   "{},\n"
+   "{},\n"
+   "{a, b},\n"
+   "};",
+   Style);
+  verifyFormat("void foo() {\n"
+   "  auto thing = test{\n"
+   "  {\n"
+   "   {13}, {something}, // A\n"
+   "  }\n"
+   "  };\n"
+   "}",
+   "void foo() {\n"
+   "  auto thing = test{\n"
+   "  {\n"
+ 

[PATCH] D121076: [MLIR][Python] Add SCFIfOp Python binding

2022-03-12 Thread Hongzheng Chen via Phabricator via cfe-commits
chhzh123 added a comment.

I've rebased to the latest commit in the main branch, but the pre-merge checks 
still failed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121076

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


[PATCH] D121076: [MLIR][Python] Add SCFIfOp Python binding

2022-03-12 Thread Hongzheng Chen via Phabricator via cfe-commits
chhzh123 updated this revision to Diff 414852.
chhzh123 added a comment.

Try rebasing again


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121076

Files:
  mlir/python/mlir/dialects/_scf_ops_ext.py
  mlir/test/python/dialects/scf.py

Index: mlir/test/python/dialects/scf.py
===
--- mlir/test/python/dialects/scf.py
+++ mlir/test/python/dialects/scf.py
@@ -82,3 +82,58 @@
 # CHECK:   iter_args(%{{.*}} = %[[ARGS]]#0, %{{.*}} = %[[ARGS]]#1)
 # CHECK: scf.yield %{{.*}}, %{{.*}}
 # CHECK:   return
+
+
+@constructAndPrintInModule
+def testIfWithoutElse():
+  bool = IntegerType.get_signless(1)
+  i32 = IntegerType.get_signless(32)
+
+  @builtin.FuncOp.from_py_func(bool)
+  def simple_if(cond):
+if_op = scf.IfOp(cond)
+with InsertionPoint(if_op.then_block):
+  one = arith.ConstantOp(i32, 1)
+  add = arith.AddIOp(one, one)
+  scf.YieldOp([])
+return
+
+
+# CHECK: func @simple_if(%[[ARG0:.*]]: i1)
+# CHECK: scf.if %[[ARG0:.*]]
+# CHECK:   %[[ONE:.*]] = arith.constant 1
+# CHECK:   %[[ADD:.*]] = arith.addi %[[ONE]], %[[ONE]]
+# CHECK: return
+
+
+@constructAndPrintInModule
+def testIfWithElse():
+  bool = IntegerType.get_signless(1)
+  i32 = IntegerType.get_signless(32)
+
+  @builtin.FuncOp.from_py_func(bool)
+  def simple_if_else(cond):
+if_op = scf.IfOp(cond, [i32, i32], hasElse=True)
+with InsertionPoint(if_op.then_block):
+  x_true = arith.ConstantOp(i32, 0)
+  y_true = arith.ConstantOp(i32, 1)
+  scf.YieldOp([x_true, y_true])
+with InsertionPoint(if_op.else_block):
+  x_false = arith.ConstantOp(i32, 2)
+  y_false = arith.ConstantOp(i32, 3)
+  scf.YieldOp([x_false, y_false])
+add = arith.AddIOp(if_op.results[0], if_op.results[1])
+return
+
+
+# CHECK: func @simple_if_else(%[[ARG0:.*]]: i1)
+# CHECK: %[[RET:.*]]:2 = scf.if %[[ARG0:.*]]
+# CHECK:   %[[ZERO:.*]] = arith.constant 0
+# CHECK:   %[[ONE:.*]] = arith.constant 1
+# CHECK:   scf.yield %[[ZERO]], %[[ONE]]
+# CHECK: } else {
+# CHECK:   %[[TWO:.*]] = arith.constant 2
+# CHECK:   %[[THREE:.*]] = arith.constant 3
+# CHECK:   scf.yield %[[TWO]], %[[THREE]]
+# CHECK: arith.addi %[[RET]]#0, %[[RET]]#1
+# CHECK: return
Index: mlir/python/mlir/dialects/_scf_ops_ext.py
===
--- mlir/python/mlir/dialects/_scf_ops_ext.py
+++ mlir/python/mlir/dialects/_scf_ops_ext.py
@@ -70,16 +70,16 @@
   """Specialization for the SCF if op class."""
 
   def __init__(self,
-   results_,
cond,
-   withElseRegion=False,
+   results_=[],
*,
+   hasElse=False,
loc=None,
ip=None):
 """Creates an SCF `if` operation.
 
-- `cond` is a boolean value to determine which regions of code will be executed.
-- `withElseRegion` determines whether the if operation has the else branch.
+- `cond` is a MLIR value of 'i1' type to determine which regions of code will be executed.
+- `hasElse` determines whether the if operation has the else branch.
 """
 operands = []
 operands.append(cond)
@@ -92,9 +92,9 @@
 operands=operands,
 loc=loc,
 ip=ip))
-self.regions[0].blocks.append(*results)
-if withElseRegion:
-self.regions[1].blocks.append(*results)
+self.regions[0].blocks.append(*[])
+if hasElse:
+self.regions[1].blocks.append(*[])
 
   @property
   def then_block(self):
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121517: Incorrectly accepts overload of (T&, int) vs. (T const&, U) #54347

2022-03-12 Thread Ed Catmur via Phabricator via cfe-commits
ecatmur updated this revision to Diff 414848.

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

https://reviews.llvm.org/D121517

Files:
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/test/SemaCXX/overload-call.cpp


Index: clang/test/SemaCXX/overload-call.cpp
===
--- clang/test/SemaCXX/overload-call.cpp
+++ clang/test/SemaCXX/overload-call.cpp
@@ -688,3 +688,13 @@
 f(pmf);
   }
 }
+
+namespace PR54347 {
+  template void f1(T&, int); // expected-note {{candidate function}}
+  template void f1(T const&, U); // expected-note 
{{candidate function}}
+  void g1(int const& i) { f1(i, 0); } // expected-error {{ambiguous}}
+
+  template void f2(T(&)[5], int); // expected-note {{candidate 
function}}
+  template void f2(T const(&)[5], U); // expected-note 
{{candidate function}}
+  void g2(int const(& a)[5]) { f2(a, 0); } // expected-error {{ambiguous}}
+}
Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -1358,7 +1358,7 @@
 if (ARef)
   A = A->getPointeeType();
 
-if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
+if (PRef && ARef) {
   // C++11 [temp.deduct.partial]p9:
   //   If, for a given type, deduction succeeds in both directions (i.e.,
   //   the types are identical after the transformations above) and both


Index: clang/test/SemaCXX/overload-call.cpp
===
--- clang/test/SemaCXX/overload-call.cpp
+++ clang/test/SemaCXX/overload-call.cpp
@@ -688,3 +688,13 @@
 f(pmf);
   }
 }
+
+namespace PR54347 {
+  template void f1(T&, int); // expected-note {{candidate function}}
+  template void f1(T const&, U); // expected-note {{candidate function}}
+  void g1(int const& i) { f1(i, 0); } // expected-error {{ambiguous}}
+
+  template void f2(T(&)[5], int); // expected-note {{candidate function}}
+  template void f2(T const(&)[5], U); // expected-note {{candidate function}}
+  void g2(int const(& a)[5]) { f2(a, 0); } // expected-error {{ambiguous}}
+}
Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -1358,7 +1358,7 @@
 if (ARef)
   A = A->getPointeeType();
 
-if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
+if (PRef && ARef) {
   // C++11 [temp.deduct.partial]p9:
   //   If, for a given type, deduction succeeds in both directions (i.e.,
   //   the types are identical after the transformations above) and both
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121076: [MLIR][Python] Add SCFIfOp Python binding

2022-03-12 Thread Hongzheng Chen via Phabricator via cfe-commits
chhzh123 updated this revision to Diff 414847.
chhzh123 added a comment.

Rebase 3 commits


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121076

Files:
  mlir/python/mlir/dialects/_scf_ops_ext.py
  mlir/test/python/dialects/scf.py

Index: mlir/test/python/dialects/scf.py
===
--- mlir/test/python/dialects/scf.py
+++ mlir/test/python/dialects/scf.py
@@ -82,3 +82,58 @@
 # CHECK:   iter_args(%{{.*}} = %[[ARGS]]#0, %{{.*}} = %[[ARGS]]#1)
 # CHECK: scf.yield %{{.*}}, %{{.*}}
 # CHECK:   return
+
+
+@constructAndPrintInModule
+def testIfWithoutElse():
+  bool = IntegerType.get_signless(1)
+  i32 = IntegerType.get_signless(32)
+
+  @builtin.FuncOp.from_py_func(bool)
+  def simple_if(cond):
+if_op = scf.IfOp(cond)
+with InsertionPoint(if_op.then_block):
+  one = arith.ConstantOp(i32, 1)
+  add = arith.AddIOp(one, one)
+  scf.YieldOp([])
+return
+
+
+# CHECK: func @simple_if(%[[ARG0:.*]]: i1)
+# CHECK: scf.if %[[ARG0:.*]]
+# CHECK:   %[[ONE:.*]] = arith.constant 1
+# CHECK:   %[[ADD:.*]] = arith.addi %[[ONE]], %[[ONE]]
+# CHECK: return
+
+
+@constructAndPrintInModule
+def testIfWithElse():
+  bool = IntegerType.get_signless(1)
+  i32 = IntegerType.get_signless(32)
+
+  @builtin.FuncOp.from_py_func(bool)
+  def simple_if_else(cond):
+if_op = scf.IfOp(cond, [i32, i32], hasElse=True)
+with InsertionPoint(if_op.then_block):
+  x_true = arith.ConstantOp(i32, 0)
+  y_true = arith.ConstantOp(i32, 1)
+  scf.YieldOp([x_true, y_true])
+with InsertionPoint(if_op.else_block):
+  x_false = arith.ConstantOp(i32, 2)
+  y_false = arith.ConstantOp(i32, 3)
+  scf.YieldOp([x_false, y_false])
+add = arith.AddIOp(if_op.results[0], if_op.results[1])
+return
+
+
+# CHECK: func @simple_if_else(%[[ARG0:.*]]: i1)
+# CHECK: %[[RET:.*]]:2 = scf.if %[[ARG0:.*]]
+# CHECK:   %[[ZERO:.*]] = arith.constant 0
+# CHECK:   %[[ONE:.*]] = arith.constant 1
+# CHECK:   scf.yield %[[ZERO]], %[[ONE]]
+# CHECK: } else {
+# CHECK:   %[[TWO:.*]] = arith.constant 2
+# CHECK:   %[[THREE:.*]] = arith.constant 3
+# CHECK:   scf.yield %[[TWO]], %[[THREE]]
+# CHECK: arith.addi %[[RET]]#0, %[[RET]]#1
+# CHECK: return
Index: mlir/python/mlir/dialects/_scf_ops_ext.py
===
--- mlir/python/mlir/dialects/_scf_ops_ext.py
+++ mlir/python/mlir/dialects/_scf_ops_ext.py
@@ -70,16 +70,16 @@
   """Specialization for the SCF if op class."""
 
   def __init__(self,
-   results_,
cond,
-   withElseRegion=False,
+   results_=[],
*,
+   hasElse=False,
loc=None,
ip=None):
 """Creates an SCF `if` operation.
 
-- `cond` is a boolean value to determine which regions of code will be executed.
-- `withElseRegion` determines whether the if operation has the else branch.
+- `cond` is a MLIR value of 'i1' type to determine which regions of code will be executed.
+- `hasElse` determines whether the if operation has the else branch.
 """
 operands = []
 operands.append(cond)
@@ -92,9 +92,9 @@
 operands=operands,
 loc=loc,
 ip=ip))
-self.regions[0].blocks.append(*results)
-if withElseRegion:
-self.regions[1].blocks.append(*results)
+self.regions[0].blocks.append(*[])
+if hasElse:
+self.regions[1].blocks.append(*[])
 
   @property
   def then_block(self):
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121076: [MLIR][Python] Add SCFIfOp Python binding

2022-03-12 Thread Hongzheng Chen via Phabricator via cfe-commits
chhzh123 updated this revision to Diff 414845.
chhzh123 added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121076

Files:
  mlir/test/python/dialects/scf.py


Index: mlir/test/python/dialects/scf.py
===
--- mlir/test/python/dialects/scf.py
+++ mlir/test/python/dialects/scf.py
@@ -82,3 +82,58 @@
 # CHECK:   iter_args(%{{.*}} = %[[ARGS]]#0, %{{.*}} = %[[ARGS]]#1)
 # CHECK: scf.yield %{{.*}}, %{{.*}}
 # CHECK:   return
+
+
+@constructAndPrintInModule
+def testIfWithoutElse():
+  bool = IntegerType.get_signless(1)
+  i32 = IntegerType.get_signless(32)
+
+  @builtin.FuncOp.from_py_func(bool)
+  def simple_if(cond):
+if_op = scf.IfOp(cond)
+with InsertionPoint(if_op.then_block):
+  one = arith.ConstantOp(i32, 1)
+  add = arith.AddIOp(one, one)
+  scf.YieldOp([])
+return
+
+
+# CHECK: func @simple_if(%[[ARG0:.*]]: i1)
+# CHECK: scf.if %[[ARG0:.*]]
+# CHECK:   %[[ONE:.*]] = arith.constant 1
+# CHECK:   %[[ADD:.*]] = arith.addi %[[ONE]], %[[ONE]]
+# CHECK: return
+
+
+@constructAndPrintInModule
+def testIfWithElse():
+  bool = IntegerType.get_signless(1)
+  i32 = IntegerType.get_signless(32)
+
+  @builtin.FuncOp.from_py_func(bool)
+  def simple_if_else(cond):
+if_op = scf.IfOp(cond, [i32, i32], hasElse=True)
+with InsertionPoint(if_op.then_block):
+  x_true = arith.ConstantOp(i32, 0)
+  y_true = arith.ConstantOp(i32, 1)
+  scf.YieldOp([x_true, y_true])
+with InsertionPoint(if_op.else_block):
+  x_false = arith.ConstantOp(i32, 2)
+  y_false = arith.ConstantOp(i32, 3)
+  scf.YieldOp([x_false, y_false])
+add = arith.AddIOp(if_op.results[0], if_op.results[1])
+return
+
+
+# CHECK: func @simple_if_else(%[[ARG0:.*]]: i1)
+# CHECK: %[[RET:.*]]:2 = scf.if %[[ARG0:.*]]
+# CHECK:   %[[ZERO:.*]] = arith.constant 0
+# CHECK:   %[[ONE:.*]] = arith.constant 1
+# CHECK:   scf.yield %[[ZERO]], %[[ONE]]
+# CHECK: } else {
+# CHECK:   %[[TWO:.*]] = arith.constant 2
+# CHECK:   %[[THREE:.*]] = arith.constant 3
+# CHECK:   scf.yield %[[TWO]], %[[THREE]]
+# CHECK: arith.addi %[[RET]]#0, %[[RET]]#1
+# CHECK: return


Index: mlir/test/python/dialects/scf.py
===
--- mlir/test/python/dialects/scf.py
+++ mlir/test/python/dialects/scf.py
@@ -82,3 +82,58 @@
 # CHECK:   iter_args(%{{.*}} = %[[ARGS]]#0, %{{.*}} = %[[ARGS]]#1)
 # CHECK: scf.yield %{{.*}}, %{{.*}}
 # CHECK:   return
+
+
+@constructAndPrintInModule
+def testIfWithoutElse():
+  bool = IntegerType.get_signless(1)
+  i32 = IntegerType.get_signless(32)
+
+  @builtin.FuncOp.from_py_func(bool)
+  def simple_if(cond):
+if_op = scf.IfOp(cond)
+with InsertionPoint(if_op.then_block):
+  one = arith.ConstantOp(i32, 1)
+  add = arith.AddIOp(one, one)
+  scf.YieldOp([])
+return
+
+
+# CHECK: func @simple_if(%[[ARG0:.*]]: i1)
+# CHECK: scf.if %[[ARG0:.*]]
+# CHECK:   %[[ONE:.*]] = arith.constant 1
+# CHECK:   %[[ADD:.*]] = arith.addi %[[ONE]], %[[ONE]]
+# CHECK: return
+
+
+@constructAndPrintInModule
+def testIfWithElse():
+  bool = IntegerType.get_signless(1)
+  i32 = IntegerType.get_signless(32)
+
+  @builtin.FuncOp.from_py_func(bool)
+  def simple_if_else(cond):
+if_op = scf.IfOp(cond, [i32, i32], hasElse=True)
+with InsertionPoint(if_op.then_block):
+  x_true = arith.ConstantOp(i32, 0)
+  y_true = arith.ConstantOp(i32, 1)
+  scf.YieldOp([x_true, y_true])
+with InsertionPoint(if_op.else_block):
+  x_false = arith.ConstantOp(i32, 2)
+  y_false = arith.ConstantOp(i32, 3)
+  scf.YieldOp([x_false, y_false])
+add = arith.AddIOp(if_op.results[0], if_op.results[1])
+return
+
+
+# CHECK: func @simple_if_else(%[[ARG0:.*]]: i1)
+# CHECK: %[[RET:.*]]:2 = scf.if %[[ARG0:.*]]
+# CHECK:   %[[ZERO:.*]] = arith.constant 0
+# CHECK:   %[[ONE:.*]] = arith.constant 1
+# CHECK:   scf.yield %[[ZERO]], %[[ONE]]
+# CHECK: } else {
+# CHECK:   %[[TWO:.*]] = arith.constant 2
+# CHECK:   %[[THREE:.*]] = arith.constant 3
+# CHECK:   scf.yield %[[TWO]], %[[THREE]]
+# CHECK: arith.addi %[[RET]]#0, %[[RET]]#1
+# CHECK: return
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121525: [clang][deps] Create lit substitution for deps-to-rsp

2022-03-12 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added a reviewer: Bigcheese.
Herald added a project: All.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch gets rid of the ridiculous relative path we use to invoke the 
`module-deps-to-rsp.py` script and creates proper lit substituion, cleaning up 
the tests.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121525

Files:
  clang/test/ClangScanDeps/modulemap-via-vfs.m
  clang/test/ClangScanDeps/modules-inferred-explicit-build.m
  clang/test/ClangScanDeps/modules-no-undeclared-includes.c
  clang/test/ClangScanDeps/modules-pch-common-submodule.c
  clang/test/ClangScanDeps/modules-pch-common-via-submodule.c
  clang/test/ClangScanDeps/modules-pch.c
  clang/test/ClangScanDeps/modules-symlink.c
  clang/test/lit.cfg.py

Index: clang/test/lit.cfg.py
===
--- clang/test/lit.cfg.py
+++ clang/test/lit.cfg.py
@@ -115,6 +115,11 @@
 ('%hmaptool', "'%s' %s" % (config.python_executable,
  os.path.join(config.clang_tools_dir, 'hmaptool'
 
+config.substitutions.append(
+('%deps-to-rsp',
+ '"%s" %s' % (config.python_executable, os.path.join(config.clang_src_dir, 'utils',
+ 'module-deps-to-rsp.py'
+
 config.substitutions.append(('%host_cc', config.host_cc))
 config.substitutions.append(('%host_cxx', config.host_cxx))
 
Index: clang/test/ClangScanDeps/modules-symlink.c
===
--- clang/test/ClangScanDeps/modules-symlink.c
+++ clang/test/ClangScanDeps/modules-symlink.c
@@ -43,10 +43,8 @@
 // RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full \
 // RUN:   -generate-modules-path-args -module-files-dir %t/build > %t/result_pch.json
 //
-// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch.json \
-// RUN:   --module-name=mod > %t/mod.cc1.rsp
-// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch.json \
-// RUN:   --tu-index=0 > %t/pch.rsp
+// RUN: %deps-to-rsp %t/result_pch.json --module-name=mod > %t/mod.cc1.rsp
+// RUN: %deps-to-rsp %t/result_pch.json --tu-index=0 > %t/pch.rsp
 //
 // RUN: %clang @%t/mod.cc1.rsp
 // RUN: %clang @%t/pch.rsp
Index: clang/test/ClangScanDeps/modules-pch.c
===
--- clang/test/ClangScanDeps/modules-pch.c
+++ clang/test/ClangScanDeps/modules-pch.c
@@ -107,14 +107,10 @@
 
 // Explicitly build the PCH:
 //
-// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch.json \
-// RUN:   --module-name=ModCommon1 > %t/mod_common_1.cc1.rsp
-// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch.json \
-// RUN:   --module-name=ModCommon2 > %t/mod_common_2.cc1.rsp
-// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch.json \
-// RUN:   --module-name=ModPCH > %t/mod_pch.cc1.rsp
-// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch.json \
-// RUN:   --tu-index=0 > %t/pch.rsp
+// RUN: %deps-to-rsp %t/result_pch.json --module-name=ModCommon1 > %t/mod_common_1.cc1.rsp
+// RUN: %deps-to-rsp %t/result_pch.json --module-name=ModCommon2 > %t/mod_common_2.cc1.rsp
+// RUN: %deps-to-rsp %t/result_pch.json --module-name=ModPCH > %t/mod_pch.cc1.rsp
+// RUN: %deps-to-rsp %t/result_pch.json --tu-index=0 > %t/pch.rsp
 //
 // RUN: %clang @%t/mod_common_1.cc1.rsp
 // RUN: %clang @%t/mod_common_2.cc1.rsp
@@ -173,10 +169,8 @@
 
 // Explicitly build the TU:
 //
-// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_tu.json \
-// RUN:   --module-name=ModTU > %t/mod_tu.cc1.rsp
-// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_tu.json \
-// RUN:   --tu-index=0 > %t/tu.rsp
+// RUN: %deps-to-rsp %t/result_tu.json --module-name=ModTU > %t/mod_tu.cc1.rsp
+// RUN: %deps-to-rsp %t/result_tu.json --tu-index=0 > %t/tu.rsp
 //
 // RUN: %clang @%t/mod_tu.cc1.rsp
 // RUN: %clang @%t/tu.rsp
@@ -235,10 +229,8 @@
 
 // Explicitly build the TU that has common modules with the PCH:
 //
-// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_tu_with_common.json \
-// RUN:   --module-name=ModTUWithCommon > %t/mod_tu_with_common.cc1.rsp
-// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_tu_with_common.json \
-// RUN:   --tu-index=0 > %t/tu_with_common.rsp
+// RUN: %deps-to-rsp %t/result_tu_with_common.json --module-name=ModTUWithCommon > %t/mod_tu_with_common.cc1.rsp
+// RUN: %deps-to-rsp %t/result_tu_with_common.json --tu-index=0 > %t/tu_with_common.rsp
 //
 // RUN: %clang @%t/mod_tu_with_common.cc1.rsp
 // RUN: %clang @%t/tu_with_common.rsp
Index: clang/test/ClangScanDeps/modules-pch-common-via-submodule.c
===
--- clang/test/ClangScanDeps/modules-pch-common-via-submodule.c
+++ 

[clang] 913107f - [clang][deps] Update helper script documentation

2022-03-12 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-03-12T16:55:38+01:00
New Revision: 913107fa1fb1ea680f1f079a1cdfc5f05a7bfb0b

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

LOG: [clang][deps] Update helper script documentation

Since D118986, clang-scan-deps returns the whole command line even for the 
original translation units.

Added: 


Modified: 
clang/utils/module-deps-to-rsp.py

Removed: 




diff  --git a/clang/utils/module-deps-to-rsp.py 
b/clang/utils/module-deps-to-rsp.py
index 416b4e6a88749..0688c40a58956 100755
--- a/clang/utils/module-deps-to-rsp.py
+++ b/clang/utils/module-deps-to-rsp.py
@@ -1,9 +1,6 @@
 #!/usr/bin/env python3
 
 # Converts clang-scan-deps output into response files.
-#   * For modules, arguments in the resulting response file are enough to 
build a PCM.
-#   * For translation units, the response file needs to be added to the 
original Clang invocation from compilation
-# database.
 #
 # Usage:
 #
@@ -11,7 +8,7 @@
 #   module-deps-to-rsp.py deps.json --module-name=ModuleName > 
module_name.cc1.rsp
 #   module-deps-to-rsp.py deps.json --tu-index=0 > tu.rsp
 #   clang @module_name.cc1.rsp
-#   clang ... @tu.rsp
+#   clang @tu.rsp
 
 import argparse
 import json



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


[PATCH] D121516: [clang][deps] Simplify PREFIX definitions in tests

2022-03-12 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a reviewer: Bigcheese.
jansvoboda11 added a comment.

In case you want to do a post-commit review.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121516

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


[PATCH] D121516: [clang][deps] Simplify PREFIX definitions in tests

2022-03-12 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc4b13f7a2f7f: [clang][deps] Simplify PREFIX definitions in 
tests (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121516

Files:
  clang/test/ClangScanDeps/diagnostics.c
  clang/test/ClangScanDeps/modules-context-hash.c
  clang/test/ClangScanDeps/modules-fmodule-name-no-module-built.m
  clang/test/ClangScanDeps/modules-full-by-mod-name.cpp
  clang/test/ClangScanDeps/modules-full.cpp
  clang/test/ClangScanDeps/modules-inferred.m
  clang/test/ClangScanDeps/modules-pch-common-submodule.c
  clang/test/ClangScanDeps/modules-pch-common-via-submodule.c
  clang/test/ClangScanDeps/modules-pch.c
  clang/test/ClangScanDeps/preserved-args.c
  clang/test/ClangScanDeps/removed-args.c

Index: clang/test/ClangScanDeps/removed-args.c
===
--- clang/test/ClangScanDeps/removed-args.c
+++ clang/test/ClangScanDeps/removed-args.c
@@ -8,12 +8,10 @@
 // RUN: cp %S/Inputs/removed-args/* %t
 
 // RUN: sed "s|DIR|%/t|g" %S/Inputs/removed-args/cdb.json.template > %t/cdb.json
-// RUN: echo -%t > %t/result.json
-// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full >> %t/result.json
-// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full > %t/result.json
+// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
 //
-// CHECK:  -[[PREFIX:.*]]
-// CHECK-NEXT: {
+// CHECK:  {
 // CHECK-NEXT:   "modules": [
 // CHECK-NEXT: {
 // CHECK-NEXT:   "clang-module-deps": [],
Index: clang/test/ClangScanDeps/preserved-args.c
===
--- clang/test/ClangScanDeps/preserved-args.c
+++ clang/test/ClangScanDeps/preserved-args.c
@@ -2,12 +2,10 @@
 // RUN: cp -r %S/Inputs/preserved-args/* %t
 // RUN: sed -e "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
 
-// RUN: echo -%t > %t/result.json
-// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full >> %t/result.json
-// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full > %t/result.json
+// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
 
-// CHECK:  -[[PREFIX:.*]]
-// CHECK-NEXT: {
+// CHECK:  {
 // CHECK-NEXT:   "modules": [
 // CHECK-NEXT: {
 // CHECK:"command-line": [
Index: clang/test/ClangScanDeps/modules-pch.c
===
--- clang/test/ClangScanDeps/modules-pch.c
+++ clang/test/ClangScanDeps/modules-pch.c
@@ -8,16 +8,14 @@
 // Scan dependencies of the PCH:
 //
 // RUN: sed "s|DIR|%/t|g" %S/Inputs/modules-pch/cdb_pch.json > %t/cdb.json
-// RUN: echo -%t > %t/result_pch.json
 // RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full \
-// RUN:   -generate-modules-path-args -module-files-dir %t/build >> %t/result_pch.json
-// RUN: cat %t/result_pch.json | sed 's:\?:/:g' | FileCheck %s -check-prefix=CHECK-PCH
+// RUN:   -generate-modules-path-args -module-files-dir %t/build > %t/result_pch.json
+// RUN: cat %t/result_pch.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t -check-prefix=CHECK-PCH
 //
 // Check we didn't build the PCH during dependency scanning.
 // RUN: not cat %/t/pch.h.gch
 //
-// CHECK-PCH:  -[[PREFIX:.*]]
-// CHECK-PCH-NEXT: {
+// CHECK-PCH:  {
 // CHECK-PCH-NEXT:   "modules": [
 // CHECK-PCH-NEXT: {
 // CHECK-PCH-NEXT:   "clang-module-deps": [],
@@ -109,14 +107,13 @@
 
 // Explicitly build the PCH:
 //
-// RUN: tail -n +2 %t/result_pch.json > %t/result_pch_stripped.json
-// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch_stripped.json \
+// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch.json \
 // RUN:   --module-name=ModCommon1 > %t/mod_common_1.cc1.rsp
-// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch_stripped.json \
+// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch.json \
 // RUN:   --module-name=ModCommon2 > %t/mod_common_2.cc1.rsp
-// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch_stripped.json \
+// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch.json \
 // RUN:   --module-name=ModPCH > %t/mod_pch.cc1.rsp
-// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch_stripped.json \
+// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch.json \
 // RUN:   --tu-index=0 > %t/pch.rsp
 //
 // RUN: %clang @%t/mod_common_1.cc1.rsp
@@ -127,13 +124,11 @@
 // Scan dependencies of the TU:
 //
 // RUN: sed "s|DIR|%/t|g" 

[clang] c4b13f7 - [clang][deps] Simplify PREFIX definitions in tests

2022-03-12 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-03-12T16:45:09+01:00
New Revision: c4b13f7a2f7f74006f2436ef431093d13d94f1f3

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

LOG: [clang][deps] Simplify PREFIX definitions in tests

Instead of outputting the test directory into the JSON result file, parsing it 
with `FileCheck` and then potentially stripping it, simply use `FileCheck`'s 
`-D` option.

Note that we use `%/t` instead of `%t` in order to normalize to forward slashes 
on Windows, which matches what we do with `sed 's:\?:/:g'`.

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

Added: 


Modified: 
clang/test/ClangScanDeps/diagnostics.c
clang/test/ClangScanDeps/modules-context-hash.c
clang/test/ClangScanDeps/modules-fmodule-name-no-module-built.m
clang/test/ClangScanDeps/modules-full-by-mod-name.cpp
clang/test/ClangScanDeps/modules-full.cpp
clang/test/ClangScanDeps/modules-inferred.m
clang/test/ClangScanDeps/modules-pch-common-submodule.c
clang/test/ClangScanDeps/modules-pch-common-via-submodule.c
clang/test/ClangScanDeps/modules-pch.c
clang/test/ClangScanDeps/preserved-args.c
clang/test/ClangScanDeps/removed-args.c

Removed: 




diff  --git a/clang/test/ClangScanDeps/diagnostics.c 
b/clang/test/ClangScanDeps/diagnostics.c
index 0dcac47afc8d7..0b36abc744062 100644
--- a/clang/test/ClangScanDeps/diagnostics.c
+++ b/clang/test/ClangScanDeps/diagnostics.c
@@ -2,17 +2,15 @@
 // RUN: cp %S/Inputs/diagnostics/* %t
 
 // RUN: sed "s|DIR|%/t|g" %S/Inputs/diagnostics/cdb.json.template > %t/cdb.json
-// RUN: echo -%t > %t/result.json
-// RUN: clang-scan-deps -compilation-database %t/cdb.json -format 
experimental-full 2>&1 >> %t/result.json
-// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format 
experimental-full 2>&1 > %t/result.json
+// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
 
 // Check that the '-Wno-error=invalid-ios-deployment-target' option is being
 // respected and invalid arguments like '-target i386-apple-ios14.0-simulator'
 // do not result in an error.
 
 // CHECK-NOT:  error:
-// CHECK:  -[[PREFIX:.*]]
-// CHECK-NEXT: {
+// CHECK:  {
 // CHECK-NEXT:   "modules": [
 // CHECK-NEXT: {
 // CHECK-NEXT:   "clang-module-deps": [],

diff  --git a/clang/test/ClangScanDeps/modules-context-hash.c 
b/clang/test/ClangScanDeps/modules-context-hash.c
index 10c7d18ba36e6..7968e0284783b 100644
--- a/clang/test/ClangScanDeps/modules-context-hash.c
+++ b/clang/test/ClangScanDeps/modules-context-hash.c
@@ -13,13 +13,11 @@
 // entities would be non-deterministic. To prevent this, run the scans 
separately
 // and verify that the context hashes 
diff er with a single FileCheck invocation.
 //
-// RUN: echo -%t > %t/result.json
-// RUN: clang-scan-deps -compilation-database %t/cdb_a.json -format 
experimental-full -j 1 >> %t/result.json
+// RUN: clang-scan-deps -compilation-database %t/cdb_a.json -format 
experimental-full -j 1 >  %t/result.json
 // RUN: clang-scan-deps -compilation-database %t/cdb_b.json -format 
experimental-full -j 1 >> %t/result.json
-// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s 
-check-prefix=CHECK
+// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t 
-check-prefix=CHECK
 
-// CHECK:  -[[PREFIX:.*]]
-// CHECK-NEXT: {
+// CHECK:  {
 // CHECK-NEXT:   "modules": [
 // CHECK-NEXT: {
 // CHECK-NEXT:   "clang-module-deps": [],

diff  --git a/clang/test/ClangScanDeps/modules-fmodule-name-no-module-built.m 
b/clang/test/ClangScanDeps/modules-fmodule-name-no-module-built.m
index 8469b49d0af67..518d7040facd8 100644
--- a/clang/test/ClangScanDeps/modules-fmodule-name-no-module-built.m
+++ b/clang/test/ClangScanDeps/modules-fmodule-name-no-module-built.m
@@ -9,16 +9,14 @@
 // RUN: cp %S/Inputs/module.modulemap %t.dir/Inputs/module.modulemap
 // RUN: sed -e "s|DIR|%/t.dir|g" %S/Inputs/module_fmodule_name_cdb.json > 
%t.cdb
 
-// RUN: echo %t.dir > %t.result
 // RUN: clang-scan-deps -compilation-database %t.cdb -j 1 -format 
experimental-full \
-// RUN:   -generate-modules-path-args -mode preprocess-minimized-sources >> 
%t.result
-// RUN: cat %t.result | sed 's:\?:/:g' | FileCheck --check-prefixes=CHECK 
%s
+// RUN:   -generate-modules-path-args -mode preprocess-minimized-sources > 
%t.result
+// RUN: cat %t.result | sed 's:\?:/:g' | FileCheck -DPREFIX=%/t.dir 
--check-prefixes=CHECK %s
 
 #import "header3.h"
 #import "header.h"
 
-// CHECK: [[PREFIX:.*]]
-// CHECK-NEXT: {
+// CHECK:  {
 // CHECK-NEXT:   "modules": [
 // CHECK-NEXT: {
 // CHECK-NEXT:   "clang-module-deps": []

diff  --git a/clang/test/ClangScanDeps/modules-full-by-mod-name.cpp 

[PATCH] D121517: Incorrectly accepts overload of (T&, int) vs. (T const&, U) #54347

2022-03-12 Thread Ed Catmur via Phabricator via cfe-commits
ecatmur updated this revision to Diff 414826.

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

https://reviews.llvm.org/D121517

Files:
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/test/SemaCXX/overload-call.cpp


Index: clang/test/SemaCXX/overload-call.cpp
===
--- clang/test/SemaCXX/overload-call.cpp
+++ clang/test/SemaCXX/overload-call.cpp
@@ -688,3 +688,13 @@
 f(pmf);
   }
 }
+
+namespace PR54347 {
+  template void f(T&, int); // expected-note {{candidate function}}
+  template void f(T const&, U); // expected-note {{candidate 
function}}
+  void g(int const& i) { f(i, 0); } // expected-error {{ambiguous}}
+
+  template void f(T(&)[5], int); // expected-note {{candidate 
function}}
+  template void f(T const(&)[5], U); // expected-note 
{{candidate function}}
+  void g(int const(& a)[5]) { f(a, 0); } // expected-error {{ambiguous}}
+}
Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -1358,7 +1358,7 @@
 if (ARef)
   A = A->getPointeeType();
 
-if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
+if (PRef && ARef) {
   // C++11 [temp.deduct.partial]p9:
   //   If, for a given type, deduction succeeds in both directions (i.e.,
   //   the types are identical after the transformations above) and both


Index: clang/test/SemaCXX/overload-call.cpp
===
--- clang/test/SemaCXX/overload-call.cpp
+++ clang/test/SemaCXX/overload-call.cpp
@@ -688,3 +688,13 @@
 f(pmf);
   }
 }
+
+namespace PR54347 {
+  template void f(T&, int); // expected-note {{candidate function}}
+  template void f(T const&, U); // expected-note {{candidate function}}
+  void g(int const& i) { f(i, 0); } // expected-error {{ambiguous}}
+
+  template void f(T(&)[5], int); // expected-note {{candidate function}}
+  template void f(T const(&)[5], U); // expected-note {{candidate function}}
+  void g(int const(& a)[5]) { f(a, 0); } // expected-error {{ambiguous}}
+}
Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -1358,7 +1358,7 @@
 if (ARef)
   A = A->getPointeeType();
 
-if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
+if (PRef && ARef) {
   // C++11 [temp.deduct.partial]p9:
   //   If, for a given type, deduction succeeds in both directions (i.e.,
   //   the types are identical after the transformations above) and both
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121517: Incorrectly accepts overload of (T&, int) vs. (T const&, U) #54347

2022-03-12 Thread Ed Catmur via Phabricator via cfe-commits
ecatmur updated this revision to Diff 414825.

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

https://reviews.llvm.org/D121517

Files:
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/test/SemaCXX/overload-call.cpp


Index: clang/test/SemaCXX/overload-call.cpp
===
--- clang/test/SemaCXX/overload-call.cpp
+++ clang/test/SemaCXX/overload-call.cpp
@@ -688,3 +688,13 @@
 f(pmf);
   }
 }
+
+namespace PR54347 {
+  template void f(T&, int); // expected-note {{candidate function}}
+  template void f(T const&, U) // expected-note {{candidate 
function}};
+  void g(int const& i) { f(i, 0); } // expected-error {{ambiguous}}
+
+  template void f(T(&)[5], int); // expected-note {{candidate 
function}}
+  template void f(T const(&)[5], U); // expected-note 
{{candidate function}}
+  void g(int const(& a)[5]) { f(a, 0); } // expected-error {{ambiguous}}
+}
Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -1358,7 +1358,7 @@
 if (ARef)
   A = A->getPointeeType();
 
-if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
+if (PRef && ARef) {
   // C++11 [temp.deduct.partial]p9:
   //   If, for a given type, deduction succeeds in both directions (i.e.,
   //   the types are identical after the transformations above) and both


Index: clang/test/SemaCXX/overload-call.cpp
===
--- clang/test/SemaCXX/overload-call.cpp
+++ clang/test/SemaCXX/overload-call.cpp
@@ -688,3 +688,13 @@
 f(pmf);
   }
 }
+
+namespace PR54347 {
+  template void f(T&, int); // expected-note {{candidate function}}
+  template void f(T const&, U) // expected-note {{candidate function}};
+  void g(int const& i) { f(i, 0); } // expected-error {{ambiguous}}
+
+  template void f(T(&)[5], int); // expected-note {{candidate function}}
+  template void f(T const(&)[5], U); // expected-note {{candidate function}}
+  void g(int const(& a)[5]) { f(a, 0); } // expected-error {{ambiguous}}
+}
Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -1358,7 +1358,7 @@
 if (ARef)
   A = A->getPointeeType();
 
-if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
+if (PRef && ARef) {
   // C++11 [temp.deduct.partial]p9:
   //   If, for a given type, deduction succeeds in both directions (i.e.,
   //   the types are identical after the transformations above) and both
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121517: Incorrectly accepts overload of (T&, int) vs. (T const&, U) #54347

2022-03-12 Thread Ed Catmur via Phabricator via cfe-commits
ecatmur updated this revision to Diff 414824.

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

https://reviews.llvm.org/D121517

Files:
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/test/SemaCXX/overload-call.cpp


Index: clang/test/SemaCXX/overload-call.cpp
===
--- clang/test/SemaCXX/overload-call.cpp
+++ clang/test/SemaCXX/overload-call.cpp
@@ -688,3 +688,13 @@
 f(pmf);
   }
 }
+
+namespace PR54347 {
+  template void f(T&, int);
+  template void f(T const&, U);
+  void g(int const& i) { f(i, 0); } // expected-error {{ambiguous}}
+
+  template void f(T(&)[5], int);
+  template void f(T const(&)[5], U);
+  void g(int const(& a)[5]) { f(a, 0); } // expected-error {{ambiguous}}
+}
Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -1358,7 +1358,7 @@
 if (ARef)
   A = A->getPointeeType();
 
-if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
+if (PRef && ARef) {
   // C++11 [temp.deduct.partial]p9:
   //   If, for a given type, deduction succeeds in both directions (i.e.,
   //   the types are identical after the transformations above) and both


Index: clang/test/SemaCXX/overload-call.cpp
===
--- clang/test/SemaCXX/overload-call.cpp
+++ clang/test/SemaCXX/overload-call.cpp
@@ -688,3 +688,13 @@
 f(pmf);
   }
 }
+
+namespace PR54347 {
+  template void f(T&, int);
+  template void f(T const&, U);
+  void g(int const& i) { f(i, 0); } // expected-error {{ambiguous}}
+
+  template void f(T(&)[5], int);
+  template void f(T const(&)[5], U);
+  void g(int const(& a)[5]) { f(a, 0); } // expected-error {{ambiguous}}
+}
Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -1358,7 +1358,7 @@
 if (ARef)
   A = A->getPointeeType();
 
-if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
+if (PRef && ARef) {
   // C++11 [temp.deduct.partial]p9:
   //   If, for a given type, deduction succeeds in both directions (i.e.,
   //   the types are identical after the transformations above) and both
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121517: Incorrectly accepts overload of (T&, int) vs. (T const&, U) #54347

2022-03-12 Thread Ed Catmur via Phabricator via cfe-commits
ecatmur added a comment.

https://github.com/llvm/llvm-project/issues/54347


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121517

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


[PATCH] D121517: Incorrectly accepts overload of (T&, int) vs. (T const&, U) #54347

2022-03-12 Thread Ed Catmur via Phabricator via cfe-commits
ecatmur created this revision.
Herald added a project: All.
ecatmur requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

clang correctly rejects as ambiguous:

template int f(T&, int); // 1
template int f(T const&, U); // 2
int g(int const& i) { return f(i, 0); }
However if the order of template parameters in (2) is swapped:

template int f(T&, int); // 1
template int f(T const&, U); // 2'
int g(int const& i) { return f(i, 0); }
clang incorrectly accepts, calling (1).

All versions tested up to current trunk incorrectly accept; 3.6 and older also 
incorrectly accept the first case.
gcc correctly rejects both cases since 4.5, incorrectly accepting in earlier 
versions.
icc 13 onwards correctly rejects.
MSVC correctly rejects (although it has other bugs in this area).

The problem appears to be that DeduceTemplateArgumentsByTypeMatch incorrectly 
believes that P and A are distinct; P is type-parameter-0-1 whereas A is 
type-parameter-0-0.

I believe this can be fixed simply by removing the hasSameUnqualifiedType 
check, since if the types are dissimilar the call would fail later anyway,


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121517

Files:
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/test/SemaCXX/overload-call.cpp


Index: clang/test/SemaCXX/overload-call.cpp
===
--- clang/test/SemaCXX/overload-call.cpp
+++ clang/test/SemaCXX/overload-call.cpp
@@ -688,3 +688,13 @@
 f(pmf);
   }
 }
+
+namespace PR54347 {
+  template void f(T&, int);
+  template void f(T const&, U);
+  void g(int const& i) { f(i, 0); } // expected-error {{ambiguous}}
+
+  template void f(T(&)[5], int);
+  template void f(T const(&)[5], U);
+  void g(int const(& a)[5]) { f(a, 0); } // expected-error {{ambiguous}}
+}
Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -1358,7 +1358,7 @@
 if (ARef)
   A = A->getPointeeType();
 
-if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
+if (PRef && ARef) {
   // C++11 [temp.deduct.partial]p9:
   //   If, for a given type, deduction succeeds in both directions (i.e.,
   //   the types are identical after the transformations above) and both


Index: clang/test/SemaCXX/overload-call.cpp
===
--- clang/test/SemaCXX/overload-call.cpp
+++ clang/test/SemaCXX/overload-call.cpp
@@ -688,3 +688,13 @@
 f(pmf);
   }
 }
+
+namespace PR54347 {
+  template void f(T&, int);
+  template void f(T const&, U);
+  void g(int const& i) { f(i, 0); } // expected-error {{ambiguous}}
+
+  template void f(T(&)[5], int);
+  template void f(T const(&)[5], U);
+  void g(int const(& a)[5]) { f(a, 0); } // expected-error {{ambiguous}}
+}
Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -1358,7 +1358,7 @@
 if (ARef)
   A = A->getPointeeType();
 
-if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
+if (PRef && ARef) {
   // C++11 [temp.deduct.partial]p9:
   //   If, for a given type, deduction succeeds in both directions (i.e.,
   //   the types are identical after the transformations above) and both
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121516: [clang][deps] Simplify PREFIX definitions in tests

2022-03-12 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
Herald added a project: All.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Instead of outputting the test directory into the JSON result file, parsing it 
with `FileCheck` and then potentially stripping it, simply use `FileCheck`'s 
`-D` option.

Note that we use `%/t` instead of `%t` in order to normalize to forward slashes 
on Windows, which matches what we print in the scanner.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121516

Files:
  clang/test/ClangScanDeps/diagnostics.c
  clang/test/ClangScanDeps/modules-context-hash.c
  clang/test/ClangScanDeps/modules-fmodule-name-no-module-built.m
  clang/test/ClangScanDeps/modules-full-by-mod-name.cpp
  clang/test/ClangScanDeps/modules-full.cpp
  clang/test/ClangScanDeps/modules-inferred.m
  clang/test/ClangScanDeps/modules-pch-common-submodule.c
  clang/test/ClangScanDeps/modules-pch-common-via-submodule.c
  clang/test/ClangScanDeps/modules-pch.c
  clang/test/ClangScanDeps/preserved-args.c
  clang/test/ClangScanDeps/removed-args.c

Index: clang/test/ClangScanDeps/removed-args.c
===
--- clang/test/ClangScanDeps/removed-args.c
+++ clang/test/ClangScanDeps/removed-args.c
@@ -8,12 +8,10 @@
 // RUN: cp %S/Inputs/removed-args/* %t
 
 // RUN: sed "s|DIR|%/t|g" %S/Inputs/removed-args/cdb.json.template > %t/cdb.json
-// RUN: echo -%t > %t/result.json
-// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full >> %t/result.json
-// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full > %t/result.json
+// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
 //
-// CHECK:  -[[PREFIX:.*]]
-// CHECK-NEXT: {
+// CHECK:  {
 // CHECK-NEXT:   "modules": [
 // CHECK-NEXT: {
 // CHECK-NEXT:   "clang-module-deps": [],
Index: clang/test/ClangScanDeps/preserved-args.c
===
--- clang/test/ClangScanDeps/preserved-args.c
+++ clang/test/ClangScanDeps/preserved-args.c
@@ -2,12 +2,10 @@
 // RUN: cp -r %S/Inputs/preserved-args/* %t
 // RUN: sed -e "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
 
-// RUN: echo -%t > %t/result.json
-// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full >> %t/result.json
-// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full > %t/result.json
+// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
 
-// CHECK:  -[[PREFIX:.*]]
-// CHECK-NEXT: {
+// CHECK:  {
 // CHECK-NEXT:   "modules": [
 // CHECK-NEXT: {
 // CHECK:"command-line": [
Index: clang/test/ClangScanDeps/modules-pch.c
===
--- clang/test/ClangScanDeps/modules-pch.c
+++ clang/test/ClangScanDeps/modules-pch.c
@@ -8,16 +8,14 @@
 // Scan dependencies of the PCH:
 //
 // RUN: sed "s|DIR|%/t|g" %S/Inputs/modules-pch/cdb_pch.json > %t/cdb.json
-// RUN: echo -%t > %t/result_pch.json
 // RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full \
-// RUN:   -generate-modules-path-args -module-files-dir %t/build >> %t/result_pch.json
-// RUN: cat %t/result_pch.json | sed 's:\?:/:g' | FileCheck %s -check-prefix=CHECK-PCH
+// RUN:   -generate-modules-path-args -module-files-dir %t/build > %t/result_pch.json
+// RUN: cat %t/result_pch.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t -check-prefix=CHECK-PCH
 //
 // Check we didn't build the PCH during dependency scanning.
 // RUN: not cat %/t/pch.h.gch
 //
-// CHECK-PCH:  -[[PREFIX:.*]]
-// CHECK-PCH-NEXT: {
+// CHECK-PCH:  {
 // CHECK-PCH-NEXT:   "modules": [
 // CHECK-PCH-NEXT: {
 // CHECK-PCH-NEXT:   "clang-module-deps": [],
@@ -109,14 +107,13 @@
 
 // Explicitly build the PCH:
 //
-// RUN: tail -n +2 %t/result_pch.json > %t/result_pch_stripped.json
-// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch_stripped.json \
+// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch.json \
 // RUN:   --module-name=ModCommon1 > %t/mod_common_1.cc1.rsp
-// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch_stripped.json \
+// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch.json \
 // RUN:   --module-name=ModCommon2 > %t/mod_common_2.cc1.rsp
-// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch_stripped.json \
+// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch.json \
 // RUN:   --module-name=ModPCH > %t/mod_pch.cc1.rsp
-// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch_stripped.json \
+// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch.json \
 // RUN:   --tu-index=0 > 

[clang] 4d6835f - [clang][deps] Attempt to fix Windows test failure

2022-03-12 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-03-12T12:09:22+01:00
New Revision: 4d6835f96d610c59c6558f571214e6c42097fec9

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

LOG: [clang][deps] Attempt to fix Windows test failure

Added: 


Modified: 
clang/test/ClangScanDeps/modules-no-undeclared-includes.c

Removed: 




diff  --git a/clang/test/ClangScanDeps/modules-no-undeclared-includes.c 
b/clang/test/ClangScanDeps/modules-no-undeclared-includes.c
index 005c279c9acfe..72f39223cffc1 100644
--- a/clang/test/ClangScanDeps/modules-no-undeclared-includes.c
+++ b/clang/test/ClangScanDeps/modules-no-undeclared-includes.c
@@ -27,7 +27,7 @@ module User [no_undeclared_includes] { header "user.h" }
 // RUN: sed "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
 // RUN: clang-scan-deps -compilation-database %t/cdb.json -format 
experimental-full \
 // RUN:   -generate-modules-path-args -module-files-dir %t/build > 
%t/result.json
-// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%t
+// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
 
 // CHECK:{
 // CHECK-NEXT:   "modules": [



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


[PATCH] D120474: [clang][deps] Remove '-fmodules-cache-path=' arguments

2022-03-12 Thread Jan Svoboda 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 rGcf4a31fc0f97: [clang][deps] Remove 
-fmodules-cache-path= arguments (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120474

Files:
  clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
  clang/test/ClangScanDeps/modules-inferred-explicit-build.m
  clang/tools/clang-scan-deps/ClangScanDeps.cpp


Index: clang/tools/clang-scan-deps/ClangScanDeps.cpp
===
--- clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -374,11 +374,11 @@
 const ModuleDeps  = MDIt->second;
 
 StringRef Filename = llvm::sys::path::filename(MD.ImplicitModulePCMPath);
+StringRef ModuleCachePath = llvm::sys::path::parent_path(
+llvm::sys::path::parent_path(MD.ImplicitModulePCMPath));
 
-SmallString<256> ExplicitPCMPath(
-!ModuleFilesDir.empty()
-? ModuleFilesDir
-: MD.BuildInvocation.getHeaderSearchOpts().ModuleCachePath);
+SmallString<256> ExplicitPCMPath(!ModuleFilesDir.empty() ? ModuleFilesDir
+ : 
ModuleCachePath);
 llvm::sys::path::append(ExplicitPCMPath, MD.ID.ContextHash, Filename);
 return std::string(ExplicitPCMPath);
   }
Index: clang/test/ClangScanDeps/modules-inferred-explicit-build.m
===
--- clang/test/ClangScanDeps/modules-inferred-explicit-build.m
+++ clang/test/ClangScanDeps/modules-inferred-explicit-build.m
@@ -12,7 +12,7 @@
 // RUN: %python %S/../../utils/module-deps-to-rsp.py %t.db --tu-index=0 > 
%t.tu.rsp
 // RUN: %clang @%t.inferred.cc1.rsp -pedantic -Werror
 // RUN: %clang @%t.system.cc1.rsp -pedantic -Werror
-// RUN: %clang @%t.tu.rsp -pedantic -Werror -Wno-unused-command-line-argument
+// RUN: %clang @%t.tu.rsp -pedantic -Werror
 
 #include 
 #include 
Index: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
===
--- clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -51,6 +51,7 @@
 
   CI.getLangOpts()->ImplicitModules = false;
   CI.getHeaderSearchOpts().ImplicitModuleMaps = false;
+  CI.getHeaderSearchOpts().ModuleCachePath.clear();
 
   // Report the prebuilt modules this module uses.
   for (const auto  : Deps.PrebuiltModuleDeps)
Index: clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
@@ -31,7 +31,13 @@
   getAdditionalArgsWithoutModulePaths();
   Args.insert(Args.end(), AdditionalArgs.begin(), AdditionalArgs.end());
 
-  // TODO: Filter out implicit modules leftovers (e.g. 
"-fmodules-cache-path=").
+  // This argument is unused in explicit compiles.
+  llvm::erase_if(Args, [](const std::string ) {
+return Arg.find("-fmodules-cache-path=") == 0;
+  });
+
+  // TODO: Filter out the remaining implicit modules leftovers
+  // (e.g. "-fmodules-prune-interval=" or "-fmodules-prune-after=").
 
   return Args;
 }


Index: clang/tools/clang-scan-deps/ClangScanDeps.cpp
===
--- clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -374,11 +374,11 @@
 const ModuleDeps  = MDIt->second;
 
 StringRef Filename = llvm::sys::path::filename(MD.ImplicitModulePCMPath);
+StringRef ModuleCachePath = llvm::sys::path::parent_path(
+llvm::sys::path::parent_path(MD.ImplicitModulePCMPath));
 
-SmallString<256> ExplicitPCMPath(
-!ModuleFilesDir.empty()
-? ModuleFilesDir
-: MD.BuildInvocation.getHeaderSearchOpts().ModuleCachePath);
+SmallString<256> ExplicitPCMPath(!ModuleFilesDir.empty() ? ModuleFilesDir
+ : ModuleCachePath);
 llvm::sys::path::append(ExplicitPCMPath, MD.ID.ContextHash, Filename);
 return std::string(ExplicitPCMPath);
   }
Index: clang/test/ClangScanDeps/modules-inferred-explicit-build.m
===
--- clang/test/ClangScanDeps/modules-inferred-explicit-build.m
+++ clang/test/ClangScanDeps/modules-inferred-explicit-build.m
@@ -12,7 +12,7 @@
 // RUN: %python %S/../../utils/module-deps-to-rsp.py %t.db --tu-index=0 > %t.tu.rsp
 // RUN: %clang @%t.inferred.cc1.rsp -pedantic -Werror
 // RUN: %clang @%t.system.cc1.rsp -pedantic -Werror
-// RUN: 

[clang] cf4a31f - [clang][deps] Remove '-fmodules-cache-path=' arguments

2022-03-12 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-03-12T11:42:07+01:00
New Revision: cf4a31fc0f9745dabbd7d9cba56a6a9045a026d0

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

LOG: [clang][deps] Remove '-fmodules-cache-path=' arguments

With explicit modules build, the '-fmodules-cache-path=' argument is unused.

This patch removes the argument to avoid warnings or errors (with '-Werror') 
stemming from that.

Depends on D118915.

Reviewed By: dexonsmith

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

Added: 


Modified: 
clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
clang/test/ClangScanDeps/modules-inferred-explicit-build.m
clang/tools/clang-scan-deps/ClangScanDeps.cpp

Removed: 




diff  --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
index 06d39c266e80c..55d2c48af41a2 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
@@ -31,7 +31,13 @@ FullDependencies::getCommandLineWithoutModulePaths() const {
   getAdditionalArgsWithoutModulePaths();
   Args.insert(Args.end(), AdditionalArgs.begin(), AdditionalArgs.end());
 
-  // TODO: Filter out implicit modules leftovers (e.g. 
"-fmodules-cache-path=").
+  // This argument is unused in explicit compiles.
+  llvm::erase_if(Args, [](const std::string ) {
+return Arg.find("-fmodules-cache-path=") == 0;
+  });
+
+  // TODO: Filter out the remaining implicit modules leftovers
+  // (e.g. "-fmodules-prune-interval=" or "-fmodules-prune-after=").
 
   return Args;
 }

diff  --git a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp 
b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
index ed18a111e51f3..4d70b0c80aad2 100644
--- a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -51,6 +51,7 @@ CompilerInvocation 
ModuleDepCollector::makeInvocationForModuleBuildWithoutPaths(
 
   CI.getLangOpts()->ImplicitModules = false;
   CI.getHeaderSearchOpts().ImplicitModuleMaps = false;
+  CI.getHeaderSearchOpts().ModuleCachePath.clear();
 
   // Report the prebuilt modules this module uses.
   for (const auto  : Deps.PrebuiltModuleDeps)

diff  --git a/clang/test/ClangScanDeps/modules-inferred-explicit-build.m 
b/clang/test/ClangScanDeps/modules-inferred-explicit-build.m
index 09101ff89a5e7..5321a13f21910 100644
--- a/clang/test/ClangScanDeps/modules-inferred-explicit-build.m
+++ b/clang/test/ClangScanDeps/modules-inferred-explicit-build.m
@@ -12,7 +12,7 @@
 // RUN: %python %S/../../utils/module-deps-to-rsp.py %t.db --tu-index=0 > 
%t.tu.rsp
 // RUN: %clang @%t.inferred.cc1.rsp -pedantic -Werror
 // RUN: %clang @%t.system.cc1.rsp -pedantic -Werror
-// RUN: %clang @%t.tu.rsp -pedantic -Werror -Wno-unused-command-line-argument
+// RUN: %clang @%t.tu.rsp -pedantic -Werror
 
 #include 
 #include 

diff  --git a/clang/tools/clang-scan-deps/ClangScanDeps.cpp 
b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
index 8d70808575699..8b6697f020ab3 100644
--- a/clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -374,11 +374,11 @@ class FullDeps {
 const ModuleDeps  = MDIt->second;
 
 StringRef Filename = llvm::sys::path::filename(MD.ImplicitModulePCMPath);
+StringRef ModuleCachePath = llvm::sys::path::parent_path(
+llvm::sys::path::parent_path(MD.ImplicitModulePCMPath));
 
-SmallString<256> ExplicitPCMPath(
-!ModuleFilesDir.empty()
-? ModuleFilesDir
-: MD.BuildInvocation.getHeaderSearchOpts().ModuleCachePath);
+SmallString<256> ExplicitPCMPath(!ModuleFilesDir.empty() ? ModuleFilesDir
+ : 
ModuleCachePath);
 llvm::sys::path::append(ExplicitPCMPath, MD.ID.ContextHash, Filename);
 return std::string(ExplicitPCMPath);
   }



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


[PATCH] D118915: [clang][deps] Generate '-fmodule-file=' only for direct dependencies

2022-03-12 Thread Jan Svoboda 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 rG7f6af607464e: [clang][deps] Generate 
-fmodule-file= only for direct dependencies (authored by 
jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118915

Files:
  clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
  clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
  clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
  clang/test/ClangScanDeps/modules-full.cpp
  clang/test/ClangScanDeps/modules-pch.c
  clang/tools/clang-scan-deps/ClangScanDeps.cpp

Index: clang/tools/clang-scan-deps/ClangScanDeps.cpp
===
--- clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -298,10 +298,7 @@
 
 ID.CommandLine = GenerateModulesPathArgs
  ? FD.getCommandLine(
-   [&](ModuleID MID) { return lookupPCMPath(MID); },
-   [&](ModuleID MID) -> const ModuleDeps & {
- return lookupModuleDeps(MID);
-   })
+   [&](ModuleID MID) { return lookupPCMPath(MID); })
  : FD.getCommandLineWithoutModulePaths();
 
 Inputs.push_back(std::move(ID));
@@ -336,10 +333,7 @@
   {"command-line",
GenerateModulesPathArgs
? MD.getCanonicalCommandLine(
- [&](ModuleID MID) { return lookupPCMPath(MID); },
- [&](ModuleID MID) -> const ModuleDeps & {
-   return lookupModuleDeps(MID);
- })
+ [&](ModuleID MID) { return lookupPCMPath(MID); })
: MD.getCanonicalCommandLineWithoutModulePaths()},
   };
   OutModules.push_back(std::move(O));
@@ -369,12 +363,16 @@
   StringRef lookupPCMPath(ModuleID MID) {
 auto PCMPath = PCMPaths.insert({MID, ""});
 if (PCMPath.second)
-  PCMPath.first->second = constructPCMPath(lookupModuleDeps(MID));
+  PCMPath.first->second = constructPCMPath(MID);
 return PCMPath.first->second;
   }
 
   /// Construct a path for the explicitly built PCM.
-  std::string constructPCMPath(const ModuleDeps ) const {
+  std::string constructPCMPath(ModuleID MID) const {
+auto MDIt = Modules.find(IndexedModuleID{MID, 0});
+assert(MDIt != Modules.end());
+const ModuleDeps  = MDIt->second;
+
 StringRef Filename = llvm::sys::path::filename(MD.ImplicitModulePCMPath);
 
 SmallString<256> ExplicitPCMPath(
@@ -385,12 +383,6 @@
 return std::string(ExplicitPCMPath);
   }
 
-  const ModuleDeps (ModuleID MID) {
-auto I = Modules.find(IndexedModuleID{MID, 0});
-assert(I != Modules.end());
-return I->second;
-  };
-
   struct IndexedModuleID {
 ModuleID ID;
 mutable size_t InputIndex;
Index: clang/test/ClangScanDeps/modules-pch.c
===
--- clang/test/ClangScanDeps/modules-pch.c
+++ clang/test/ClangScanDeps/modules-pch.c
@@ -97,7 +97,6 @@
 // CHECK-PCH:  "-fno-implicit-modules",
 // CHECK-PCH-NEXT: "-fno-implicit-module-maps",
 // CHECK-PCH-NEXT: "-fmodule-file=[[PREFIX]]/build/[[HASH_MOD_COMMON_1]]/ModCommon1-{{.*}}.pcm",
-// CHECK-PCH-NEXT: "-fmodule-file=[[PREFIX]]/build/[[HASH_MOD_COMMON_2]]/ModCommon2-{{.*}}.pcm",
 // CHECK-PCH-NEXT: "-fmodule-file=[[PREFIX]]/build/[[HASH_MOD_PCH]]/ModPCH-{{.*}}.pcm"
 // CHECK-PCH-NEXT:   ],
 // CHECK-PCH-NEXT:   "file-deps": [
Index: clang/test/ClangScanDeps/modules-full.cpp
===
--- clang/test/ClangScanDeps/modules-full.cpp
+++ clang/test/ClangScanDeps/modules-full.cpp
@@ -169,9 +169,7 @@
 // CHECK:  "-fno-implicit-modules"
 // CHECK-NEXT: "-fno-implicit-module-maps"
 // CHECK-NO-ABS-NOT:   "-fmodule-file={{.*}}"
-// CHECK-ABS-NEXT: "-fmodule-file=[[PREFIX]]/module-cache{{(_clangcl)?}}/[[HASH_H2_DINCLUDE]]/header2-{{[A-Z0-9]+}}.pcm"
 // CHECK-ABS-NEXT: "-fmodule-file=[[PREFIX]]/module-cache{{(_clangcl)?}}/[[HASH_H1_DINCLUDE]]/header1-{{[A-Z0-9]+}}.pcm"
-// CHECK-CUSTOM-NEXT:  "-fmodule-file=[[PREFIX]]/custom/[[HASH_H2_DINCLUDE]]/header2-{{[A-Z0-9]+}}.pcm"
 // CHECK-CUSTOM-NEXT:  "-fmodule-file=[[PREFIX]]/custom/[[HASH_H1_DINCLUDE]]/header1-{{[A-Z0-9]+}}.pcm"
 // CHECK-NEXT:   ],
 // CHECK-NEXT:   "file-deps": [
Index: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
===
--- clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ 

[clang] 7f6af60 - [clang][deps] Generate '-fmodule-file=' only for direct dependencies

2022-03-12 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-03-12T11:32:51+01:00
New Revision: 7f6af607464e5bcf2bd8b7bc7724a5985d7a0c34

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

LOG: [clang][deps] Generate '-fmodule-file=' only for direct dependencies

The `clang-scan-deps` tool currently generates `-fmodule-file=` command-line 
arguments for the whole transitive closure of modular dependencies. This is not 
necessary, we only need to provide the direct dependencies on the command line. 
Information about transitive dependencies is stored within the `.pcm` files of 
direct dependencies. This makes the command lines shorter, but should be a NFC 
otherwise (unless there are bugs in the loading mechanism for explicit modules).

Depends on D120465.

Reviewed By: Bigcheese

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

Added: 


Modified: 
clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
clang/test/ClangScanDeps/modules-full.cpp
clang/test/ClangScanDeps/modules-pch.c
clang/tools/clang-scan-deps/ClangScanDeps.cpp

Removed: 




diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
index 36447dd2e38e6..aee4ddee9707b 100644
--- a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
+++ b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
@@ -51,12 +51,8 @@ struct FullDependencies {
   ///  arguments and the "-o" argument. It needs to return
   ///  a path for where the PCM for the given module is to
   ///  be located.
-  /// \param LookupModuleDeps This function is called to collect the full
-  /// transitive set of dependencies for this
-  /// compilation.
-  std::vector getCommandLine(
-  std::function LookupPCMPath,
-  std::function LookupModuleDeps) const;
+  std::vector
+  getCommandLine(std::function LookupPCMPath) const;
 
   /// Get the full command line, excluding -fmodule-file=" arguments.
   std::vector getCommandLineWithoutModulePaths() const;

diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h 
b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
index d0fa474eda4eb..7936f9c60f6b0 100644
--- a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
+++ b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
@@ -113,27 +113,14 @@ struct ModuleDeps {
   ///  arguments and the "-o" argument. It needs to return
   ///  a path for where the PCM for the given module is to
   ///  be located.
-  /// \param LookupModuleDeps This function is called to collect the full
-  /// transitive set of dependencies for this
-  /// compilation.
   std::vector getCanonicalCommandLine(
-  std::function LookupPCMPath,
-  std::function LookupModuleDeps) const;
+  std::function LookupPCMPath) const;
 
   /// Gets the canonical command line suitable for passing to clang, excluding
   /// "-fmodule-file=" and "-o" arguments.
   std::vector getCanonicalCommandLineWithoutModulePaths() const;
 };
 
-namespace detail {
-/// Collect the paths of PCM for the modules in \c Modules transitively.
-void collectPCMPaths(
-llvm::ArrayRef Modules,
-std::function LookupPCMPath,
-std::function LookupModuleDeps,
-std::vector );
-} // namespace detail
-
 class ModuleDepCollector;
 
 /// Callback that records textual includes and direct modular includes/imports

diff  --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
index 12602fccc92e0..06d39c266e80c 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
@@ -14,15 +14,11 @@ namespace tooling {
 namespace dependencies {
 
 std::vector FullDependencies::getCommandLine(
-std::function LookupPCMPath,
-std::function LookupModuleDeps) const {
+std::function LookupPCMPath) const {
   std::vector Ret = getCommandLineWithoutModulePaths();
 
-  std::vector PCMPaths;
-  dependencies::detail::collectPCMPaths(ClangModuleDeps, LookupPCMPath,
-LookupModuleDeps, PCMPaths);
-  for (const std::string  : PCMPaths)
-Ret.push_back("-fmodule-file=" + PCMPath);
+  

[clang] a6ef363 - [clang][deps] Disable implicit module maps

2022-03-12 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-03-12T11:07:21+01:00
New Revision: a6ef3635461c7e689972337b281d0052331f6150

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

LOG: [clang][deps] Disable implicit module maps

Since D113473, we don't report any module map files via `-fmodule-map-file=` in 
explicit builds. The ultimate goal here is to make sure Clang doesn't 
open/read/parse/evaluate unnecessary module maps.

However, implicit module maps still end up reading all reachable module maps. 
This patch disables implicit module maps in explicit builds.

Unfortunately, we still need to report some module map files that aren't 
encoded in PCM files of dependencies: module maps that are necessary to 
correctly evaluate includes in modules marked as `[no_undeclared_includes]`.

Depends on D120464.

Reviewed By: dexonsmith

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

Added: 
clang/test/ClangScanDeps/modules-no-undeclared-includes.c

Modified: 
clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
clang/test/ClangScanDeps/modules-full.cpp
clang/test/ClangScanDeps/modules-inferred.m
clang/test/ClangScanDeps/modules-pch.c

Removed: 




diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h 
b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
index c2e9541db68e0..d0fa474eda4eb 100644
--- a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
+++ b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
@@ -85,6 +85,10 @@ struct ModuleDeps {
   /// on, not including transitive dependencies.
   llvm::StringSet<> FileDeps;
 
+  /// A collection of absolute paths to module map files that this module needs
+  /// to know about.
+  std::vector ModuleMapFileDeps;
+
   /// A collection of prebuilt modular dependencies this module directly 
depends
   /// on, not including transitive dependencies.
   std::vector PrebuiltModuleDeps;
@@ -122,13 +126,12 @@ struct ModuleDeps {
 };
 
 namespace detail {
-/// Collect the paths of PCM and module map files for the modules in \c Modules
-/// transitively.
-void collectPCMAndModuleMapPaths(
+/// Collect the paths of PCM for the modules in \c Modules transitively.
+void collectPCMPaths(
 llvm::ArrayRef Modules,
 std::function LookupPCMPath,
 std::function LookupModuleDeps,
-std::vector , std::vector );
+std::vector );
 } // namespace detail
 
 class ModuleDepCollector;

diff  --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
index 2723d4742819a..12602fccc92e0 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
@@ -19,9 +19,8 @@ std::vector FullDependencies::getCommandLine(
   std::vector Ret = getCommandLineWithoutModulePaths();
 
   std::vector PCMPaths;
-  std::vector ModMapPaths;
-  dependencies::detail::collectPCMAndModuleMapPaths(
-  ClangModuleDeps, LookupPCMPath, LookupModuleDeps, PCMPaths, ModMapPaths);
+  dependencies::detail::collectPCMPaths(ClangModuleDeps, LookupPCMPath,
+LookupModuleDeps, PCMPaths);
   for (const std::string  : PCMPaths)
 Ret.push_back("-fmodule-file=" + PCMPath);
 

diff  --git a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp 
b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
index 086215e7a573d..0b77ba8f9b0e8 100644
--- a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -50,11 +50,14 @@ CompilerInvocation 
ModuleDepCollector::makeInvocationForModuleBuildWithoutPaths(
   CI.getFrontendOpts().IsSystemModule = Deps.IsSystem;
 
   CI.getLangOpts()->ImplicitModules = false;
+  CI.getHeaderSearchOpts().ImplicitModuleMaps = false;
 
   // Report the prebuilt modules this module uses.
   for (const auto  : Deps.PrebuiltModuleDeps)
 CI.getFrontendOpts().ModuleFiles.push_back(PrebuiltModule.PCMFile);
 
+  CI.getFrontendOpts().ModuleMapFiles = Deps.ModuleMapFileDeps;
+
   Optimize(CI);
 
   // The original invocation probably didn't have strict context hash enabled.
@@ -94,9 +97,9 @@ std::vector ModuleDeps::getCanonicalCommandLine(
   FrontendOpts.Inputs.emplace_back(ClangModuleMapFile, ModuleMapInputKind);
   FrontendOpts.OutputFile = std::string(LookupPCMPath(ID));
 
-  dependencies::detail::collectPCMAndModuleMapPaths(
-  ClangModuleDeps, LookupPCMPath, LookupModuleDeps,
-  FrontendOpts.ModuleFiles, FrontendOpts.ModuleMapFiles);
+  

[PATCH] D120465: [clang][deps] Disable implicit module maps

2022-03-12 Thread Jan Svoboda 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 rGa6ef3635461c: [clang][deps] Disable implicit module maps 
(authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D120465?vs=413384=414814#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120465

Files:
  clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
  clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
  clang/test/ClangScanDeps/modules-full.cpp
  clang/test/ClangScanDeps/modules-inferred.m
  clang/test/ClangScanDeps/modules-no-undeclared-includes.c
  clang/test/ClangScanDeps/modules-pch.c

Index: clang/test/ClangScanDeps/modules-pch.c
===
--- clang/test/ClangScanDeps/modules-pch.c
+++ clang/test/ClangScanDeps/modules-pch.c
@@ -26,6 +26,7 @@
 // CHECK-PCH-NEXT: "-cc1"
 // CHECK-PCH:  "-emit-module"
 // CHECK-PCH:  "-fmodules"
+// CHECK-PCH-NOT:  "-fimplicit-module-maps"
 // CHECK-PCH:  "-fmodule-name=ModCommon1"
 // CHECK-PCH:  "-fno-implicit-modules"
 // CHECK-PCH:],
@@ -43,6 +44,7 @@
 // CHECK-PCH-NEXT: "-cc1"
 // CHECK-PCH:  "-emit-module"
 // CHECK-PCH:  "-fmodules"
+// CHECK-PCH-NOT:  "-fimplicit-module-maps"
 // CHECK-PCH:  "-fmodule-name=ModCommon2"
 // CHECK-PCH:  "-fno-implicit-modules"
 // CHECK-PCH:],
@@ -66,6 +68,7 @@
 // CHECK-PCH:  "-emit-module"
 // CHECK-PCH:  "-fmodule-file=[[PREFIX]]/build/[[HASH_MOD_COMMON_2]]/ModCommon2-{{.*}}.pcm"
 // CHECK-PCH:  "-fmodules"
+// CHECK-PCH-NOT:  "-fimplicit-module-maps"
 // CHECK-PCH:  "-fmodule-name=ModPCH"
 // CHECK-PCH:  "-fno-implicit-modules"
 // CHECK-PCH:],
@@ -139,6 +142,7 @@
 // CHECK-TU-NEXT:   "command-line": [
 // CHECK-TU-NEXT: "-cc1",
 // CHECK-TU:  "-emit-module",
+// CHECK-TU-NOT:  "-fimplicit-module-maps",
 // CHECK-TU:  "-fmodule-name=ModTU",
 // CHECK-TU:  "-fno-implicit-modules",
 // CHECK-TU:],
@@ -202,6 +206,7 @@
 // CHECK-TU-WITH-COMMON-NEXT: "-cc1",
 // CHECK-TU-WITH-COMMON:  "-emit-module",
 // CHECK-TU-WITH-COMMON:  "-fmodule-file=[[PREFIX]]/build/{{.*}}/ModCommon1-{{.*}}.pcm",
+// CHECK-TU-WITH-COMMON-NOT:  "-fimplicit-module-maps",
 // CHECK-TU-WITH-COMMON:  "-fmodule-name=ModTUWithCommon",
 // CHECK-TU-WITH-COMMON:  "-fno-implicit-modules",
 // CHECK-TU-WITH-COMMON:],
Index: clang/test/ClangScanDeps/modules-no-undeclared-includes.c
===
--- /dev/null
+++ clang/test/ClangScanDeps/modules-no-undeclared-includes.c
@@ -0,0 +1,72 @@
+// RUN: rm -rf %t && mkdir %t
+// RUN: split-file %s %t
+
+//--- undeclared/module.modulemap
+module Undeclared { header "undeclared.h" }
+
+//--- undeclared/undeclared.h
+
+//--- module.modulemap
+module User [no_undeclared_includes] { header "user.h" }
+
+//--- user.h
+#if __has_include("undeclared.h")
+#error Unreachable. Undeclared comes from a module that's not 'use'd, meaning the compiler should pretend it doesn't exist.
+#endif
+
+//--- test.c
+#include "user.h"
+
+//--- cdb.json.template
+[{
+  "directory": "DIR",
+  "command": "clang -fmodules -gmodules -fimplicit-module-maps -fmodules-cache-path=DIR/cache -IDIR/undeclared -c DIR/test.c -o DIR/test.o",
+  "file": "DIR/test.c"
+}]
+
+// RUN: sed "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full \
+// RUN:   -generate-modules-path-args -module-files-dir %t/build > %t/result.json
+// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%t
+
+// CHECK:{
+// CHECK-NEXT:   "modules": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file": "[[PREFIX]]/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK:  "-fmodule-map-file=[[PREFIX]]/undeclared/module.modulemap"
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "{{.*}}",
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: "[[PREFIX]]/module.modulemap",
+// CHECK-NEXT: "[[PREFIX]]/undeclared/module.modulemap",
+// CHECK-NEXT: "[[PREFIX]]/user.h"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "User"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "translation-units": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-context-hash": "{{.*}}"
+// CHECK-NEXT:   "clang-module-deps": [
+// CHECK-NEXT: 

[PATCH] D119599: [clang-format] Add option to align compound assignments like `+=`

2022-03-12 Thread sstwcw via Phabricator via cfe-commits
sstwcw added a comment.

@MyDeveloperDay Will you please accept this revision?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119599

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


[PATCH] D121450: [clang-format] Handle attributes before case label.

2022-03-12 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added inline comments.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:578
+break;
+
   LLVM_FALLTHROUGH;

owenpan wrote:
> Can we remove this empty line?
Will do.



Comment at: clang/lib/Format/UnwrappedLineParser.h:125-126
   FormatToken *parseIfThenElse(IfStmtKind *IfKind, bool KeepBraces = false);
+  void handleAttributes();
+  bool handleCppAttributes();
   void parseTryCatch();

owenpan wrote:
> Can we move them 1 line up so that the order of the declarations here will be 
> the same as that of the definitions in the .cpp file?
Will do.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121450

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