[clang-tools-extra] 97b6c92 - [include-cleaner] Add missing deps from unittests

2022-04-29 Thread via cfe-commits

Author: Sam McCall
Date: 2022-04-29T13:08:28+02:00
New Revision: 97b6c92dcd56937bc27de7c4c08381fc71c402e7

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

LOG: [include-cleaner] Add missing deps from unittests

Added: 


Modified: 
clang-tools-extra/include-cleaner/unittests/CMakeLists.txt

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/unittests/CMakeLists.txt 
b/clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
index fe33c3bcd137..0cbbefcdd611 100644
--- a/clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
+++ b/clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
@@ -14,7 +14,9 @@ target_include_directories(ClangIncludeCleanerTests
 
 clang_target_link_libraries(ClangIncludeCleanerTests
   PRIVATE
+  clangAST
   clangBasic
+  clangFrontend
   )
 
 target_link_libraries(ClangIncludeCleanerTests



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


[clang] 73417c5 - [HLSL][clang][Driver] Support validator version command line option.

2022-04-29 Thread via cfe-commits

Author: python3kgae
Date: 2022-04-29T16:48:08-07:00
New Revision: 73417c517644db5c419c85c0b3cb6750172fcab5

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

LOG: [HLSL][clang][Driver] Support validator version command line option.

The DXIL validator version option(/validator-version) decide the validator 
version when compile hlsl.
The format is major.minor like 1.0.

In normal case, the value of validator version should be got from DXIL 
validator. Before we got DXIL validator ready for llvm/main, DXIL validator 
version option is added first to set validator version.

It will affect code generation for DXIL, so it is treated as a code gen option.

A new member std::string DxilValidatorVersion is added to clang::CodeGenOptions.

Then CGHLSLRuntime is added to clang::CodeGenModule.
It is used to translate clang::CodeGenOptions::DxilValidatorVersion into a 
ModuleFlag under key "dx.valver" at end of clang code generation.

Reviewed By: beanz

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

Added: 
clang/lib/CodeGen/CGHLSLRuntime.cpp
clang/lib/CodeGen/CGHLSLRuntime.h
clang/test/CodeGenHLSL/validator_version.hlsl

Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/include/clang/Basic/TargetOptions.h
clang/include/clang/Driver/Options.td
clang/lib/CodeGen/CMakeLists.txt
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/CodeGen/CodeGenModule.h
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/HLSL.cpp
clang/lib/Driver/ToolChains/HLSL.h
clang/unittests/Driver/ToolChainTest.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 7ab7a8c0cd175..b35693462e33d 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -667,4 +667,13 @@ def err_drv_target_variant_invalid : Error<
 def err_drv_invalid_directx_shader_module : Error<
   "invalid profile : %0">;
 
+def err_drv_invalid_range_dxil_validator_version : Error<
+  "invalid validator version : %0\n"
+  "Validator version must be less than or equal to current internal version.">;
+def err_drv_invalid_format_dxil_validator_version : Error<
+  "invalid validator version : %0\n"
+  "Format of validator version is \".\" (ex:\"1.4\").">;
+def err_drv_invalid_empty_dxil_validator_version : Error<
+  "invalid validator version : %0\n"
+  "If validator major version is 0, minor version must also be 0.">;
 }

diff  --git a/clang/include/clang/Basic/TargetOptions.h 
b/clang/include/clang/Basic/TargetOptions.h
index 009f25981ca93..611add6f92682 100644
--- a/clang/include/clang/Basic/TargetOptions.h
+++ b/clang/include/clang/Basic/TargetOptions.h
@@ -110,8 +110,11 @@ class TargetOptions {
   /// The version of the darwin target variant SDK which was used during the
   /// compilation.
   llvm::VersionTuple DarwinTargetVariantSDKVersion;
+
+  /// The validator version for dxil.
+  std::string DxilValidatorVersion;
 };
 
-}  // end namespace clang
+} // end namespace clang
 
 #endif

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 15b94ee5425e9..ae95ab267c163 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -6736,20 +6736,21 @@ def _SLASH_ZW : CLJoined<"ZW">;
 
 def dxc_Group : OptionGroup<"">, Flags<[DXCOption]>,
   HelpText<"dxc compatibility options">;
-
 class DXCJoinedOrSeparate : Option<["/", "-"], name,
   KIND_JOINED_OR_SEPARATE>, Group, Flags<[DXCOption, 
NoXarchOption]>;
 
 def dxc_help : Option<["/", "-", "--"], "help", KIND_JOINED>,
   Group, Flags<[DXCOption, NoXarchOption]>, Alias,
   HelpText<"Display available options">;
-
-
 def Fo : DXCJoinedOrSeparate<"Fo">, Alias,
-  HelpText<"Output object file.">;
-
+  HelpText<"Output object file">;
+def dxil_validator_version : Option<["/", "-"], "validator-version", 
KIND_SEPARATE>,
+  Group, Flags<[DXCOption, NoXarchOption, CC1Option, HelpHidden]>,
+  HelpText<"Override validator version for module. Format: ;"
+   "Default: DXIL.dll version or current internal version">,
+  MarshallingInfoString>;
 def target_profile : DXCJoinedOrSeparate<"T">, MetaVarName<"">,
-  HelpText<"Set target profile.">,
+  HelpText<"Set target profile">,
   Values<"ps_6_0, ps_6_1, ps_6_2, ps_6_3, ps_6_4, ps_6_5, ps_6_6, ps_6_7,"
  "vs_6_0, vs_6_1, vs_6_2, vs_6_3, vs_6_4, vs_6_5, vs_6_6, vs_6_7,"
  "gs_6_0, gs_6_1, gs_6_2, gs_6_3, gs_6_4, gs_6_5, gs_6_6, gs_6_7,"

diff  --git a/clang/lib/CodeGen/CGHLSLRuntime.cpp 
b/clang/lib/CodeGen/CGHLSLRuntime.cpp
new file mode 100644
index 0..f5392213f9fe2
--- /dev/null
+++ b/clang/lib/CodeGen/CGHLSLRuntime.cp

[clang] 19978e0 - [RISCV]Add CTZ Intrinsic for ZBB in Clang

2022-04-29 Thread via cfe-commits

Author: joker881
Date: 2022-04-30T08:18:10+08:00
New Revision: 19978e08749f5f68fbd535121c4f2ed7297b3a4f

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

LOG: [RISCV]Add CTZ Intrinsic for ZBB in Clang

Add Intrinsics and test for B extension (updating coming soon (:

Reviewed By: craig.topper

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

Added: 


Modified: 
clang/include/clang/Basic/BuiltinsRISCV.def
clang/lib/CodeGen/CGBuiltin.cpp
clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbb.c
clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbb.c

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsRISCV.def 
b/clang/include/clang/Basic/BuiltinsRISCV.def
index 74b8c9ea6a94..b146118a99b5 100644
--- a/clang/include/clang/Basic/BuiltinsRISCV.def
+++ b/clang/include/clang/Basic/BuiltinsRISCV.def
@@ -20,6 +20,8 @@ TARGET_BUILTIN(__builtin_riscv_orc_b_32, "ZiZi", "nc", "zbb")
 TARGET_BUILTIN(__builtin_riscv_orc_b_64, "WiWi", "nc", "zbb,64bit")
 TARGET_BUILTIN(__builtin_riscv_clz_32, "ZiZi", "nc", "zbb")
 TARGET_BUILTIN(__builtin_riscv_clz_64, "WiWi", "nc", "zbb,64bit")
+TARGET_BUILTIN(__builtin_riscv_ctz_32, "ZiZi", "nc", "zbb")
+TARGET_BUILTIN(__builtin_riscv_ctz_64, "WiWi", "nc", "zbb,64bit")
 
 // Zbc or Zbkc extension
 TARGET_BUILTIN(__builtin_riscv_clmul, "LiLiLi", "nc", "zbc|zbkc")

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 83fd75fd9667..70fd869e5c67 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -19024,6 +19024,8 @@ Value *CodeGenFunction::EmitRISCVBuiltinExpr(unsigned 
BuiltinID,
   case RISCV::BI__builtin_riscv_orc_b_64:
   case RISCV::BI__builtin_riscv_clz_32:
   case RISCV::BI__builtin_riscv_clz_64:
+  case RISCV::BI__builtin_riscv_ctz_32:
+  case RISCV::BI__builtin_riscv_ctz_64:
   case RISCV::BI__builtin_riscv_clmul:
   case RISCV::BI__builtin_riscv_clmulh:
   case RISCV::BI__builtin_riscv_clmulr:
@@ -19074,6 +19076,11 @@ Value *CodeGenFunction::EmitRISCVBuiltinExpr(unsigned 
BuiltinID,
   Function *F = CGM.getIntrinsic(Intrinsic::ctlz, Ops[0]->getType());
   return Builder.CreateCall(F, {Ops[0], Builder.getInt1(false)});
 }
+case RISCV::BI__builtin_riscv_ctz_32:
+case RISCV::BI__builtin_riscv_ctz_64: {
+  Function *F = CGM.getIntrinsic(Intrinsic::cttz, Ops[0]->getType());
+  return Builder.CreateCall(F, {Ops[0], Builder.getInt1(false)});
+}
 
 // Zbc
 case RISCV::BI__builtin_riscv_clmul:

diff  --git a/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbb.c 
b/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbb.c
index c1827b1edbf5..45f57bd8cc74 100644
--- a/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbb.c
+++ b/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbb.c
@@ -24,4 +24,16 @@ int orc_b_32(int a) {
 //
 int clz_32(int a) {
   return __builtin_riscv_clz_32(a);
+}
+
+// RV32ZBB-LABEL: @ctz_32(
+// RV32ZBB-NEXT:  entry:
+// RV32ZBB-NEXT:[[A_ADDR:%.*]] = alloca i32, align 4
+// RV32ZBB-NEXT:store i32 [[A:%.*]], i32* [[A_ADDR]], align 4
+// RV32ZBB-NEXT:[[TMP0:%.*]] = load i32, i32* [[A_ADDR]], align 4
+// RV32ZBB-NEXT:[[TMP1:%.*]] = call i32 @llvm.cttz.i32(i32 [[TMP0]], i1 
false)
+// RV32ZBB-NEXT:ret i32 [[TMP1]]
+//
+int ctz_32(int a) {
+  return __builtin_riscv_ctz_32(a);
 }
\ No newline at end of file

diff  --git a/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbb.c 
b/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbb.c
index da2930c89120..00f2985c1557 100644
--- a/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbb.c
+++ b/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbb.c
@@ -48,4 +48,16 @@ int clz_32(int a) {
 //
 long clz_64(long a) {
   return __builtin_riscv_clz_64(a);
+}
+
+// RV64ZBB-LABEL: @ctz_64(
+// RV64ZBB-NEXT:  entry:
+// RV64ZBB-NEXT:[[A_ADDR:%.*]] = alloca i64, align 8
+// RV64ZBB-NEXT:store i64 [[A:%.*]], i64* [[A_ADDR]], align 8
+// RV64ZBB-NEXT:[[TMP0:%.*]] = load i64, i64* [[A_ADDR]], align 8
+// RV64ZBB-NEXT:[[TMP1:%.*]] = call i64 @llvm.cttz.i64(i64 [[TMP0]], i1 
false)
+// RV64ZBB-NEXT:ret i64 [[TMP1]]
+//
+long ctz_64(long a) {
+  return __builtin_riscv_ctz_64(a);
 }
\ No newline at end of file



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


[clang] 43c146c - [clang-format] Take out common code for parsing blocks NFC

2022-05-01 Thread via cfe-commits

Author: sstwcw
Date: 2022-05-01T08:58:40Z
New Revision: 43c146c96d8e4607266f2c2ef74c17d4170fc248

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

LOG: [clang-format] Take out common code for parsing blocks NFC

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 1e2f4d6761e1e..d20cead7d3212 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2713,55 +2713,49 @@ void UnwrappedLineParser::parseNew() {
   } while (!eof());
 }
 
-void UnwrappedLineParser::parseForOrWhileLoop() {
-  assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
- "'for', 'while' or foreach macro expected");
-  nextToken();
-  // JS' for await ( ...
-  if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
-nextToken();
-  if (Style.isCpp() && FormatTok->is(tok::kw_co_await))
-nextToken();
-  if (FormatTok->is(tok::l_paren))
-parseParens();
-
+void UnwrappedLineParser::parseLoopBody(bool TryRemoveBraces,
+bool WrapRightBrace) {
   keepAncestorBraces();
 
   if (FormatTok->is(tok::l_brace)) {
 FormatToken *LeftBrace = FormatTok;
 CompoundStatementIndenter Indenter(this, Style, Line->Level);
 parseBlock();
-if (Style.RemoveBracesLLVM) {
+if (TryRemoveBraces) {
   assert(!NestedTooDeep.empty());
   if (!NestedTooDeep.back())
 markOptionalBraces(LeftBrace);
 }
-addUnwrappedLine();
+if (WrapRightBrace)
+  addUnwrappedLine();
   } else {
 parseUnbracedBody();
   }
 
-  if (Style.RemoveBracesLLVM)
+  if (TryRemoveBraces)
 NestedTooDeep.pop_back();
 }
 
-void UnwrappedLineParser::parseDoWhile() {
-  assert(FormatTok->is(tok::kw_do) && "'do' expected");
+void UnwrappedLineParser::parseForOrWhileLoop() {
+  assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
+ "'for', 'while' or foreach macro expected");
   nextToken();
+  // JS' for await ( ...
+  if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
+nextToken();
+  if (Style.isCpp() && FormatTok->is(tok::kw_co_await))
+nextToken();
+  if (FormatTok->is(tok::l_paren))
+parseParens();
 
-  keepAncestorBraces();
+  parseLoopBody(Style.RemoveBracesLLVM, true);
+}
 
-  if (FormatTok->is(tok::l_brace)) {
-CompoundStatementIndenter Indenter(this, Style, Line->Level);
-parseBlock();
-if (Style.BraceWrapping.BeforeWhile)
-  addUnwrappedLine();
-  } else {
-parseUnbracedBody();
-  }
+void UnwrappedLineParser::parseDoWhile() {
+  assert(FormatTok->is(tok::kw_do) && "'do' expected");
+  nextToken();
 
-  if (Style.RemoveBracesLLVM)
-NestedTooDeep.pop_back();
+  parseLoopBody(false, Style.BraceWrapping.BeforeWhile);
 
   // FIXME: Add error handling.
   if (!FormatTok->is(tok::kw_while)) {

diff  --git a/clang/lib/Format/UnwrappedLineParser.h 
b/clang/lib/Format/UnwrappedLineParser.h
index 798bae24ad075..3334b5bad97b4 100644
--- a/clang/lib/Format/UnwrappedLineParser.h
+++ b/clang/lib/Format/UnwrappedLineParser.h
@@ -125,6 +125,7 @@ class UnwrappedLineParser {
   bool handleCppAttributes();
   FormatToken *parseIfThenElse(IfStmtKind *IfKind, bool KeepBraces = false);
   void parseTryCatch();
+  void parseLoopBody(bool TryRemoveBraces, bool WrapRightBrace);
   void parseForOrWhileLoop();
   void parseDoWhile();
   void parseLabel(bool LeftAlignLabel = false);



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


[clang] c8603db - [clang-format] Fix a bug that misformats Access Specifier after *[]

2022-05-02 Thread via cfe-commits

Author: owenca
Date: 2022-05-02T01:39:26-07:00
New Revision: c8603db0711e451cecb75c8e10a12e882d4e0b31

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

LOG: [clang-format] Fix a bug that misformats Access Specifier after *[]

Fixes #55132.

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

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 d20cead7d3212..520f73ac15eeb 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2048,6 +2048,11 @@ bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
   nextToken();
   if (FormatTok->is(tok::l_square))
 return false;
+  if (FormatTok->is(tok::r_square)) {
+const FormatToken *Next = Tokens->peekNextToken();
+if (Next && Next->is(tok::greater))
+  return false;
+  }
   parseSquare(/*LambdaIntroducer=*/true);
   return true;
 }

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index c685fa152281c..da25395b7df49 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -3336,6 +3336,14 @@ TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
   verifyFormat("if (public == private)\n");
   verifyFormat("void foo(public, private)");
   verifyFormat("public::foo();");
+
+  verifyFormat("class A {\n"
+   "public:\n"
+   "  std::unique_ptr b() { return nullptr; }\n"
+   "\n"
+   "private:\n"
+   "  int c;\n"
+   "};");
 }
 
 TEST_F(FormatTest, SeparatesLogicalBlocks) {
@@ -21487,6 +21495,7 @@ TEST_F(FormatTest, FormatsLambdas) {
"  bar([]() {} // Did not respect 
SpacesBeforeTrailingComments\n"
"  );\n"
"}");
+  verifyFormat("auto k = *[](int *j) { return j; }(&i);");
 
   // Lambdas created through weird macros.
   verifyFormat("void f() {\n"



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


[clang] 32eb7b8 - [Driver][test] Remove clang{{.*}} when testing -cc1 command lines

2022-05-02 Thread via cfe-commits

Author: Weverything
Date: 2022-05-02T17:08:20-07:00
New Revision: 32eb7b863e49222882afae39ca9f2888ee5cc7a0

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

LOG: [Driver][test] Remove clang{{.*}} when testing -cc1 command lines

The majority of tests omit testing "clang" for -cc1 command lines. In addition,
some distributions symlink %clang to an executable with a content hash based
filename so clang{{.*}} check won't work.

With this change, we can remove many -no-canonical-prefixes whose purpose was to
make the tests pass on such distributions.

Added: 


Modified: 
clang/test/Driver/wasm-toolchain.cpp

Removed: 




diff  --git a/clang/test/Driver/wasm-toolchain.cpp 
b/clang/test/Driver/wasm-toolchain.cpp
index a4b89b3ea2f7e..86a223a2ff092 100644
--- a/clang/test/Driver/wasm-toolchain.cpp
+++ b/clang/test/Driver/wasm-toolchain.cpp
@@ -16,48 +16,48 @@
 
 // RUN: %clangxx -### --target=wasm32-unknown-unknown --sysroot=/foo 
--stdlib=libc++ %s 2>&1 \
 // RUN:   | FileCheck -check-prefix=LINK %s
-// LINK: clang{{.*}}" "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
+// LINK: "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
 // LINK: wasm-ld{{.*}}" "-L/foo/lib" "crt1.o" "[[temp]]" "-lc++" "-lc++abi" 
"-lc" "{{.*[/\\]}}libclang_rt.builtins-wasm32.a" "-o" "a.out"
 
 // RUN: %clangxx -### --target=wasm32-unknown-unknown --sysroot=/foo 
--stdlib=libstdc++ %s 2>&1 \
 // RUN:   | FileCheck -check-prefix=LINK_STDCXX %s
-// LINK_STDCXX: clang{{.*}}" "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
+// LINK_STDCXX: "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
 // LINK_STDCXX: wasm-ld{{.*}}" "-L/foo/lib" "crt1.o" "[[temp]]" "-lstdc++" 
"-lc" "{{.*[/\\]}}libclang_rt.builtins-wasm32.a" "-o" "a.out"
 
 // A basic C++ link command-line with optimization with unknown OS.
 
 // RUN: %clangxx -### -O2 --target=wasm32-unknown-unknown --sysroot=/foo %s 
--stdlib=libc++ 2>&1 \
 // RUN:   | FileCheck -check-prefix=LINK_OPT %s
-// LINK_OPT: clang{{.*}}" "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
+// LINK_OPT: "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
 // LINK_OPT: wasm-ld{{.*}}" "-L/foo/lib" "crt1.o" "[[temp]]" "-lc++" 
"-lc++abi" "-lc" "{{.*[/\\]}}libclang_rt.builtins-wasm32.a" "-o" "a.out"
 
 // RUN: %clangxx -### -O2 --target=wasm32-unknown-unknown --sysroot=/foo %s 
--stdlib=libstdc++ 2>&1 \
 // RUN:   | FileCheck -check-prefix=LINK_OPT_STDCXX %s
-// LINK_OPT_STDCXX: clang{{.*}}" "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
+// LINK_OPT_STDCXX: "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
 // LINK_OPT_STDCXX: wasm-ld{{.*}}" "-L/foo/lib" "crt1.o" "[[temp]]" "-lstdc++" 
"-lc" "{{.*[/\\]}}libclang_rt.builtins-wasm32.a" "-o" "a.out"
 
 // A basic C++ link command-line with known OS.
 
 // RUN: %clangxx -### --target=wasm32-wasi --sysroot=/foo --stdlib=libc++ %s 
2>&1 \
 // RUN:   | FileCheck -check-prefix=LINK_KNOWN %s
-// LINK_KNOWN: clang{{.*}}" "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
+// LINK_KNOWN: "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
 // LINK_KNOWN: wasm-ld{{.*}}" "-L/foo/lib/wasm32-wasi" "crt1.o" "[[temp]]" 
"-lc++" "-lc++abi" "-lc" "{{.*[/\\]}}libclang_rt.builtins-wasm32.a" "-o" "a.out"
 
 // RUN: %clangxx -### --target=wasm32-wasi --sysroot=/foo --stdlib=libstdc++ 
%s 2>&1 \
 // RUN:   | FileCheck -check-prefix=LINK_KNOWN_STDCXX %s
-// LINK_KNOWN_STDCXX: clang{{.*}}" "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
+// LINK_KNOWN_STDCXX: "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
 // LINK_KNOWN_STDCXX: wasm-ld{{.*}}" "-L/foo/lib/wasm32-wasi" "crt1.o" 
"[[temp]]" "-lstdc++" "-lc" "{{.*[/\\]}}libclang_rt.builtins-wasm32.a" "-o" 
"a.out"
 
 // A basic C++ link command-line with optimization with known OS.
 
 // RUN: %clangxx -### -O2 --target=wasm32-wasi --sysroot=/foo %s 
--stdlib=libc++ 2>&1 \
 // RUN:   | FileCheck -check-prefix=LINK_OPT_KNOWN %s
-// LINK_OPT_KNOWN: clang{{.*}}" "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
+// LINK_OPT_KNOWN: "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
 // LINK_OPT_KNOWN: wasm-ld{{.*}}" "-L/foo/lib/wasm32-wasi" "crt1.o" "[[temp]]" 
"-lc++" "-lc++abi" "-lc" "{{.*[/\\]}}libclang_rt.builtins-wasm32.a" "-o" "a.out"
 
 // RUN: %clangxx -### -O2 --target=wasm32-wasi --sysroot=/foo %s 
--stdlib=libstdc++ 2>&1 \
 // RUN:   | FileCheck -check-prefix=LINK_OPT_KNOWN_STDCXX %s
-// LINK_OPT_KNOWN_STDCXX: clang{{.*}}" "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
+// LINK_OPT_KNOWN_STDCXX: "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
 // LINK_OPT_KNOWN_STDCXX: wasm-ld{{.*}}" "-L/foo/lib/wasm32-wasi" "crt1.o" 
"[[temp]]" "-lstdc++" "-lc" "{{.*[/\\]}}libclang_rt.builtins-wasm32.a" "-o" 
"a.out"
 
 // A basic C++ compile command-line with known OS.
@@ -65,7 +65,7 @@
 // RUN: %clangxx -### --target=wasm32-wasi --stdlib=libc++ %s 2>&1 \
 // RUN: --sysroot=%S/Inputs/basic_linux_libcxx_tree/usr \
 // RUN:   | FileCheck -check-prefix=COMPILE %s
-// COMPILE: clang{{.*}}" "-cc1"
+// COMPILE: "-cc1"
 // COMPILE: "-re

[clang] 3971880 - [clang-format][NFC] Clean up tryToParseLambdaIntroducer()

2022-05-03 Thread via cfe-commits

Author: owenca
Date: 2022-05-03T11:36:38-07:00
New Revision: 397188036d4cdec7c3bc9236b4a5197232283413

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

LOG: [clang-format][NFC] Clean up tryToParseLambdaIntroducer()

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 520f73ac15eeb..52ce0fff251c2 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1931,11 +1931,11 @@ bool UnwrappedLineParser::tryToParsePropertyAccessor() {
 }
 
 bool UnwrappedLineParser::tryToParseLambda() {
+  assert(FormatTok->is(tok::l_square));
   if (!Style.isCpp()) {
 nextToken();
 return false;
   }
-  assert(FormatTok->is(tok::l_square));
   FormatToken &LSquare = *FormatTok;
   if (!tryToParseLambdaIntroducer())
 return false;
@@ -2037,20 +2037,20 @@ bool UnwrappedLineParser::tryToParseLambda() {
 
 bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
   const FormatToken *Previous = FormatTok->Previous;
+  const FormatToken *LeftSquare = FormatTok;
+  nextToken();
   if (Previous &&
   (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new,
  tok::kw_delete, tok::l_square) ||
-   FormatTok->isCppStructuredBinding(Style) || Previous->closesScope() ||
+   LeftSquare->isCppStructuredBinding(Style) || Previous->closesScope() ||
Previous->isSimpleTypeSpecifier())) {
-nextToken();
 return false;
   }
-  nextToken();
   if (FormatTok->is(tok::l_square))
 return false;
   if (FormatTok->is(tok::r_square)) {
 const FormatToken *Next = Tokens->peekNextToken();
-if (Next && Next->is(tok::greater))
+if (Next->is(tok::greater))
   return false;
   }
   parseSquare(/*LambdaIntroducer=*/true);



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


[clang-tools-extra] 0e86cdd - [psuedo] Fix for unused warning by moving code into debug macro.

2022-05-03 Thread via cfe-commits

Author: Weverything
Date: 2022-05-03T16:07:59-07:00
New Revision: 0e86cddf988081018200bcdce22a96d9e91a

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

LOG: [psuedo] Fix for unused warning by moving code into debug macro.

Added: 


Modified: 
clang-tools-extra/pseudo/lib/GLR.cpp

Removed: 




diff  --git a/clang-tools-extra/pseudo/lib/GLR.cpp 
b/clang-tools-extra/pseudo/lib/GLR.cpp
index c1fdd8680ca85..771d69fb680dc 100644
--- a/clang-tools-extra/pseudo/lib/GLR.cpp
+++ b/clang-tools-extra/pseudo/lib/GLR.cpp
@@ -90,12 +90,13 @@ const ForestNode &glrParse(const TokenStream &Tokens,
 });
 
   if (!PendingAccept.empty()) {
-LLVM_DEBUG(llvm::dbgs() << llvm::formatv("Accept: {0} accepted result:\n",
- PendingAccept.size()));
-for (const auto &Accept : PendingAccept)
-  LLVM_DEBUG(llvm::dbgs()
- << "  - " << G.symbolName(Accept.Head->Payload->symbol())
- << "\n");
+LLVM_DEBUG({
+  llvm::dbgs() << llvm::formatv("Accept: {0} accepted result:\n",
+ PendingAccept.size());
+  for (const auto &Accept : PendingAccept)
+llvm::dbgs() << "  - " << G.symbolName(Accept.Head->Payload->symbol())
+ << "\n";
+});
 assert(PendingAccept.size() == 1);
 return *PendingAccept.front().Head->Payload;
   }



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


[clang] 342e1c7 - [clang-format] Fix a bug in AlignConsecutiveAssignments

2022-05-04 Thread via cfe-commits

Author: owenca
Date: 2022-05-04T12:04:43-07:00
New Revision: 342e1c77c360e745fc6457037e6c1e37b84f2791

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

LOG: [clang-format] Fix a bug in AlignConsecutiveAssignments

Fixes #55113.

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index 2dcc4fd62c5e8..cf4ef6338f1bd 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -369,6 +369,8 @@ AlignTokenSequence(const FormatStyle &Style, unsigned 
Start, unsigned End,
   if (Changes[i].Tok->MatchingParen &&
   Changes[i].Tok->MatchingParen->is(TT_LambdaLBrace))
 return false;
+  if (Changes[ScopeStart].NewlinesBefore > 0)
+return false;
   return Style.BinPackArguments;
 }
 

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 37f32691a1d36..78a3c21c33009 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -18010,11 +18010,21 @@ TEST_F(FormatTest, AlignWithLineBreaks) {
Style);
   // clang-format on
 
-  Style = getLLVMStyleWithColumns(120);
+  Style = getLLVMStyleWithColumns(20);
   Style.AlignConsecutiveAssignments.Enabled = true;
-  Style.ContinuationIndentWidth = 4;
   Style.IndentWidth = 4;
 
+  verifyFormat("void foo() {\n"
+   "int i1 = 1;\n"
+   "int j  = 0;\n"
+   "int k  = bar(\n"
+   "argument1,\n"
+   "argument2);\n"
+   "}",
+   Style);
+
+  Style.ColumnLimit = 120;
+
   // clang-format off
   verifyFormat("void SomeFunc() {\n"
"newWatcher.maxAgeUsec = 
ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp(monitorFrequencyUsec),\n"



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


[clang] df58018 - [analyzer] Get direct binding for specific punned case

2022-05-05 Thread via cfe-commits

Author: einvbri
Date: 2022-05-05T04:53:45-05:00
New Revision: df5801806d03c22099c85942134ca3004776016b

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

LOG: [analyzer] Get direct binding for specific punned case

Region store was not able to see through this case to the actual
initialized value of STRUCT ff. This change addresses this case by
getting the direct binding. This was found and debugged in a downstream
compiler, with debug guidance from @steakhal. A positive and negative
test case is added.

The specific case where this issue was exposed.

  typedef struct {
int a:1;
int b[2];
  } STRUCT;

  int main() {
STRUCT ff = {0};
STRUCT* pff = &ff;
int a = ((int)pff + 1);
return a;
  }

Reviewed By: steakhal, martong

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

Added: 
clang/test/Analysis/array-punned-region.c

Modified: 
clang/lib/StaticAnalyzer/Core/RegionStore.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp 
b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
index 20b167c9b3b22..43924cd4b5424 100644
--- a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -2147,8 +2147,13 @@ 
RegionStoreManager::getBindingForFieldOrElementCommon(RegionBindingsConstRef B,
   return UnknownVal();
 
 // Additionally allow introspection of a block's internal layout.
-if (!hasPartialLazyBinding && !isa(R->getBaseRegion()))
+// Try to get direct binding if all other attempts failed thus far.
+// Else, return UndefinedVal()
+if (!hasPartialLazyBinding && !isa(R->getBaseRegion())) {
+  if (const Optional &V = B.getDefaultBinding(R))
+return *V;
   return UndefinedVal();
+}
   }
 
   // All other values are symbolic.

diff  --git a/clang/test/Analysis/array-punned-region.c 
b/clang/test/Analysis/array-punned-region.c
new file mode 100644
index 0..d319fd7367ec5
--- /dev/null
+++ b/clang/test/Analysis/array-punned-region.c
@@ -0,0 +1,39 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.core,debug.ExprInspection -verify -analyzer-config 
eagerly-assume=false -triple x86_64-pc-linux-gnu %s
+
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.core,debug.ExprInspection -verify -analyzer-config 
eagerly-assume=false -triple i386-pc-linux-gnu  %s
+
+int clang_analyzer_eval(int);
+
+typedef struct {
+  int a : 1;
+  int b[2];
+} BITFIELD_CAST;
+
+void array_struct_bitfield_1() {
+  BITFIELD_CAST ff = {0};
+  BITFIELD_CAST *pff = &ff;
+  clang_analyzer_eval(*((int *)pff + 1) == 0); // expected-warning{{TRUE}}
+  ff.b[0] = 3;
+  clang_analyzer_eval(*((int *)pff + 1) == 3); // expected-warning{{TRUE}}
+}
+
+int array_struct_bitfield_2() {
+  BITFIELD_CAST ff = {0};
+  BITFIELD_CAST *pff = &ff;
+  int a = *((int *)pff + 2); // expected-warning{{Assigned value is garbage or 
undefined [core.uninitialized.Assign]}}
+  return a;
+}
+
+typedef struct {
+  unsigned int a : 1;
+  unsigned int x : 31;
+  unsigned int c : 1;
+  int b[2];
+} mystruct;
+
+void array_struct_bitfield_3() {
+  mystruct ff;
+  mystruct *pff = &ff;
+  ff.b[0] = 3;
+  clang_analyzer_eval(*((int *)pff + 2) == 3); // expected-warning{{TRUE}}
+}



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


[clang] dcb9067 - [clang][ASTImporter][NFC]: Move clang::ImportError into own header.

2022-05-05 Thread via cfe-commits

Author: phyBrackets
Date: 2022-05-06T00:14:32+05:30
New Revision: dcb906757ada24edf8da89439c72d015b53f204b

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

LOG: [clang][ASTImporter][NFC]: Move clang::ImportError into own header.

Reviewed By: martong

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

Added: 
clang/include/clang/AST/ASTImportError.h

Modified: 
clang/include/clang/AST/ASTImporter.h
clang/include/clang/AST/ASTImporterSharedState.h

Removed: 




diff  --git a/clang/include/clang/AST/ASTImportError.h 
b/clang/include/clang/AST/ASTImportError.h
new file mode 100644
index 0..034bd50cc7e15
--- /dev/null
+++ b/clang/include/clang/AST/ASTImportError.h
@@ -0,0 +1,50 @@
+//===- ASTImportError.h - Define errors while importing AST -*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines the ASTImportError class which basically defines the kind
+//  of error while importing AST .
+//
+//===--===//
+
+#ifndef LLVM_CLANG_AST_ASTIMPORTERROR_H
+#define LLVM_CLANG_AST_ASTIMPORTERROR_H
+
+#include "llvm/Support/Error.h"
+
+namespace clang {
+
+class ImportError : public llvm::ErrorInfo {
+public:
+  /// \brief Kind of error when importing an AST component.
+  enum ErrorKind {
+NameConflict, /// Naming ambiguity (likely ODR violation).
+UnsupportedConstruct, /// Not supported node or case.
+Unknown   /// Other error.
+  };
+
+  ErrorKind Error;
+
+  static char ID;
+
+  ImportError() : Error(Unknown) {}
+  ImportError(const ImportError &Other) : Error(Other.Error) {}
+  ImportError &operator=(const ImportError &Other) {
+Error = Other.Error;
+return *this;
+  }
+  ImportError(ErrorKind Error) : Error(Error) {}
+
+  std::string toString() const;
+
+  void log(llvm::raw_ostream &OS) const override;
+  std::error_code convertToErrorCode() const override;
+};
+
+} // namespace clang
+
+#endif // LLVM_CLANG_AST_ASTIMPORTERROR_H

diff  --git a/clang/include/clang/AST/ASTImporter.h 
b/clang/include/clang/AST/ASTImporter.h
index c8bdae10a6e6c..7d413115d769c 100644
--- a/clang/include/clang/AST/ASTImporter.h
+++ b/clang/include/clang/AST/ASTImporter.h
@@ -14,7 +14,7 @@
 #ifndef LLVM_CLANG_AST_ASTIMPORTER_H
 #define LLVM_CLANG_AST_ASTIMPORTER_H
 
-#include "clang/AST/APValue.h"
+#include "clang/AST/ASTImportError.h"
 #include "clang/AST/DeclBase.h"
 #include "clang/AST/DeclarationName.h"
 #include "clang/AST/ExprCXX.h"
@@ -29,7 +29,6 @@
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/Support/Error.h"
 #include 
 
 namespace clang {
@@ -49,33 +48,6 @@ class TagDecl;
 class TranslationUnitDecl;
 class TypeSourceInfo;
 
-  class ImportError : public llvm::ErrorInfo {
-  public:
-/// \brief Kind of error when importing an AST component.
-enum ErrorKind {
-NameConflict, /// Naming ambiguity (likely ODR violation).
-UnsupportedConstruct, /// Not supported node or case.
-Unknown /// Other error.
-};
-
-ErrorKind Error;
-
-static char ID;
-
-ImportError() : Error(Unknown) {}
-ImportError(const ImportError &Other) : Error(Other.Error) {}
-ImportError &operator=(const ImportError &Other) {
-  Error = Other.Error;
-  return *this;
-}
-ImportError(ErrorKind Error) : Error(Error) { }
-
-std::string toString() const;
-
-void log(raw_ostream &OS) const override;
-std::error_code convertToErrorCode() const override;
-  };
-
   // \brief Returns with a list of declarations started from the canonical decl
   // then followed by subsequent decls in the translation unit.
   // This gives a canonical list for each entry in the redecl chain.

diff  --git a/clang/include/clang/AST/ASTImporterSharedState.h 
b/clang/include/clang/AST/ASTImporterSharedState.h
index 686a8e22b2fa6..7be6f1460a856 100644
--- a/clang/include/clang/AST/ASTImporterSharedState.h
+++ b/clang/include/clang/AST/ASTImporterSharedState.h
@@ -14,11 +14,10 @@
 #ifndef LLVM_CLANG_AST_ASTIMPORTERSHAREDSTATE_H
 #define LLVM_CLANG_AST_ASTIMPORTERSHAREDSTATE_H
 
+#include "clang/AST/ASTImportError.h"
 #include "clang/AST/ASTImporterLookupTable.h"
 #include "clang/AST/Decl.h"
 #include "llvm/ADT/DenseMap.h"
-// FIXME We need this because of ImportError.
-#include "clang/AST/ASTImporter.h"
 
 namespace clang {
 



___
cfe-commits mailing list

[clang] 8b626a2 - [clang-format] Fix another bug in AlignConsecutiveAssignments

2022-05-05 Thread via cfe-commits

Author: owenca
Date: 2022-05-05T14:48:56-07:00
New Revision: 8b626a2caa672a174829105ff7749d8d9a080f2a

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

LOG: [clang-format] Fix another bug in AlignConsecutiveAssignments

The ShouldShiftBeAdded lambda checks if extra space should be
added before the wrapped part of a braced list. If the first
element of the list is wrapped, no extra space should be added.

Fixes #55161.

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index cf4ef6338f1b..8563312b45bb 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -398,6 +398,8 @@ AlignTokenSequence(const FormatStyle &Style, unsigned 
Start, unsigned End,
 Changes[OuterScopeStart - 1].Tok->is(TT_LambdaLBrace))
   return false;
   }
+  if (Changes[ScopeStart].NewlinesBefore > 0)
+return false;
   return true;
 }
 

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 78a3c21c3300..40e2cb054b24 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -18023,6 +18023,12 @@ TEST_F(FormatTest, AlignWithLineBreaks) {
"}",
Style);
 
+  verifyFormat("unsigned i = 0;\n"
+   "int a[]= {\n"
+   "1234567890,\n"
+   "-1234567890};",
+   Style);
+
   Style.ColumnLimit = 120;
 
   // clang-format off



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


[clang] e7aed73 - [clang-format][NFC] Add a few regression tests

2022-05-05 Thread via cfe-commits

Author: owenca
Date: 2022-05-05T15:12:24-07:00
New Revision: e7aed737eb2d8fb2150f38e48d1c3e0108931999

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

LOG: [clang-format][NFC] Add a few regression tests

Added: 


Modified: 
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 40e2cb054b242..d7d69f950a323 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -1573,6 +1573,17 @@ TEST_F(FormatTest, FormatShortBracedStatements) {
"  f();\n"
"}");
 
+  AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
+  FormatStyle::SBS_Empty;
+  AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
+  FormatStyle::SIS_WithoutElse;
+  verifyFormat("if (true) {}", AllowSimpleBracedStatements);
+  verifyFormat("if (i) break;", AllowSimpleBracedStatements);
+  verifyFormat("if (i > 0) {\n"
+   "  return i;\n"
+   "}",
+   AllowSimpleBracedStatements);
+
   AllowSimpleBracedStatements.IfMacros.push_back("MYIF");
   // Where line-lengths matter, a 2-letter synonym that maintains line length.
   // Not IF to avoid any confusion that IF is somehow special.
@@ -1580,11 +1591,7 @@ TEST_F(FormatTest, FormatShortBracedStatements) {
   AllowSimpleBracedStatements.ColumnLimit = 40;
   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
   FormatStyle::SBS_Always;
-
-  AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
-  FormatStyle::SIS_WithoutElse;
   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
-
   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;



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


[clang] 3fa5eb4 - [HLSL] add -fcgl option flag.

2022-05-06 Thread via cfe-commits

Author: python3kgae
Date: 2022-05-06T11:42:15-07:00
New Revision: 3fa5eb4cfc065b686c03f912e4414fd00a54d04e

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

LOG: [HLSL] add -fcgl option flag.

fcgl option will make compilation stop after clang codeGen and output the llvm 
ir.
It is added to check clang codeGen output for HLSL.

It will be translated into -S -emit-llvm and -disable-llvm-passes.

Reviewed By: aaron.ballman

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

Added: 
clang/test/Driver/dxc_fcgl.hlsl

Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/HLSL.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index d9a4cb23a0934..ae0048f2a24e6 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -6732,6 +6732,8 @@ def _SLASH_ZW : CLJoined<"ZW">;
 
 def dxc_Group : OptionGroup<"">, Flags<[DXCOption]>,
   HelpText<"dxc compatibility options">;
+class DXCFlag : Option<["/", "-"], name, KIND_FLAG>,
+  Group, Flags<[DXCOption, NoXarchOption]>;
 class DXCJoinedOrSeparate : Option<["/", "-"], name,
   KIND_JOINED_OR_SEPARATE>, Group, Flags<[DXCOption, 
NoXarchOption]>;
 
@@ -6756,3 +6758,7 @@ def target_profile : DXCJoinedOrSeparate<"T">, 
MetaVarName<"">,
  "lib_6_3, lib_6_4, lib_6_5, lib_6_6, lib_6_7, lib_6_x,"
  "ms_6_5, ms_6_6, ms_6_7,"
  "as_6_5, as_6_6, as_6_7">;
+def emit_pristine_llvm : DXCFlag<"emit-pristine-llvm">,
+  HelpText<"Emit pristine LLVM IR from the frontend by not running any LLVM 
passes at all."
+   "Same as -S + -emit-llvm + -disable-llvm-passes.">;
+def fcgl : DXCFlag<"fcgl">, Alias;

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index ebe51bcd3368a..33172d8042be9 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -3471,7 +3471,9 @@ static void RenderOpenCLOptions(const ArgList &Args, 
ArgStringList &CmdArgs,
 
 static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
   types::ID InputType) {
-  const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version};
+  const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
+ options::OPT_S, 
options::OPT_emit_llvm,
+ options::OPT_disable_llvm_passes};
 
   for (const auto &Arg : ForwardedArguments)
 if (const auto *A = Args.getLastArg(Arg))

diff  --git a/clang/lib/Driver/ToolChains/HLSL.cpp 
b/clang/lib/Driver/ToolChains/HLSL.cpp
index 2822e062fcd5c..b62395b168ea4 100644
--- a/clang/lib/Driver/ToolChains/HLSL.cpp
+++ b/clang/lib/Driver/ToolChains/HLSL.cpp
@@ -169,6 +169,15 @@ HLSLToolChain::TranslateArgs(const DerivedArgList &Args, 
StringRef BoundArch,
   if (!isLegalValidatorVersion(ValVerStr, getDriver()))
 continue;
 }
+if (A->getOption().getID() == options::OPT_emit_pristine_llvm) {
+  // Translate fcgl into -S -emit-llvm and -disable-llvm-passes.
+  DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_S));
+  DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_emit_llvm));
+  DAL->AddFlagArg(nullptr,
+  Opts.getOption(options::OPT_disable_llvm_passes));
+  A->claim();
+  continue;
+}
 DAL->append(A);
   }
   // Add default validator version if not set.

diff  --git a/clang/test/Driver/dxc_fcgl.hlsl b/clang/test/Driver/dxc_fcgl.hlsl
new file mode 100644
index 0..d3eb2523199ca
--- /dev/null
+++ b/clang/test/Driver/dxc_fcgl.hlsl
@@ -0,0 +1,5 @@
+// RUN: %clang_dxc -fcgl foo.hlsl -### %s 2>&1 | FileCheck %s
+
+// Make sure fcgl option flag which translated into "-S" "-emit-llvm" 
"-disable-llvm-passes".
+// CHECK:"-S" "-emit-llvm" "-disable-llvm-passes"
+



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


[clang] 24e9d90 - Added the brief discription about the new CSA checker.

2022-05-06 Thread via cfe-commits

Author: Shivam
Date: 2022-05-07T01:16:22+05:30
New Revision: 24e9d90e65243fd8674bfc264c1c7d27c3cce67c

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

LOG: Added the brief discription about the new CSA checker.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 0a5d3a85834d3..aa8376eed7f8b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -422,7 +422,10 @@ libclang
 Static Analyzer
 ---
 
-- ...
+- Added a new checker ``alpha.unix.cstring.UninitializedRead `` this will 
check for uninitialized reads
+  from common memory copy/manipulation functions such as:
+ ``memcpy, mempcpy, memmove, memcmp, strcmp, strncmp, strcpy, strlen, strsep`` 
and many more. Although 
+  this checker currently is in list of alpha checkers due to a false positive.
 
 .. _release-notes-ubsan:
 



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


[clang] b390173 - update the doc for the static analyzer checker

2022-05-06 Thread via cfe-commits

Author: Shivam
Date: 2022-05-07T01:19:46+05:30
New Revision: b39017340806ee68b305d5c8330cbc3e1d398a4d

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

LOG: update the doc for the static analyzer checker

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index aa8376eed7f8..ebc227cf2251 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -423,8 +423,8 @@ Static Analyzer
 ---
 
 - Added a new checker ``alpha.unix.cstring.UninitializedRead `` this will 
check for uninitialized reads
-  from common memory copy/manipulation functions such as:
- ``memcpy, mempcpy, memmove, memcmp, strcmp, strncmp, strcpy, strlen, strsep`` 
and many more. Although 
+  from common memory copy/manipulation functions such as ``memcpy``, 
``mempcpy``, ``memmove``, ``memcmp``, `
+  `strcmp``, ``strncmp``, ``strcpy``, ``strlen``, ``strsep`` and many more. 
Although 
   this checker currently is in list of alpha checkers due to a false positive.
 
 .. _release-notes-ubsan:



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


[clang] bbd0319 - Update ReleaseNotes.rst

2022-05-06 Thread via cfe-commits

Author: Shivam
Date: 2022-05-07T01:20:45+05:30
New Revision: bbd031943a3d1bd72fed362ee3e8456dbb901747

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

LOG: Update ReleaseNotes.rst

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ebc227cf2251..7cdd77b2df3a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -422,7 +422,7 @@ libclang
 Static Analyzer
 ---
 
-- Added a new checker ``alpha.unix.cstring.UninitializedRead `` this will 
check for uninitialized reads
+- Added a new checker ``alpha.unix.cstring.UninitializedRead`` this will check 
for uninitialized reads
   from common memory copy/manipulation functions such as ``memcpy``, 
``mempcpy``, ``memmove``, ``memcmp``, `
   `strcmp``, ``strncmp``, ``strcpy``, ``strlen``, ``strsep`` and many more. 
Although 
   this checker currently is in list of alpha checkers due to a false positive.



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


[clang] af4cf1c - [clang-format][NFC] Make all TokenAnnotator member functions const

2022-05-06 Thread via cfe-commits

Author: owenca
Date: 2022-05-06T14:46:32-07:00
New Revision: af4cf1c6b8ed0d8102fc5e69acdc2fcbbcdaa9a7

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

LOG: [clang-format][NFC] Make all TokenAnnotator member functions const

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 3714b9d3e0fc..8cbe157b1fb2 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2523,7 +2523,7 @@ class ExpressionParser {
 } // end anonymous namespace
 
 void TokenAnnotator::setCommentLineLevels(
-SmallVectorImpl &Lines) {
+SmallVectorImpl &Lines) const {
   const AnnotatedLine *NextNonCommentLine = nullptr;
   for (AnnotatedLine *Line : llvm::reverse(Lines)) {
 assert(Line->First);
@@ -2558,7 +2558,7 @@ static unsigned maxNestingDepth(const AnnotatedLine 
&Line) {
   return Result;
 }
 
-void TokenAnnotator::annotate(AnnotatedLine &Line) {
+void TokenAnnotator::annotate(AnnotatedLine &Line) const {
   for (auto &Child : Line.Children)
 annotate(*Child);
 
@@ -2725,7 +2725,7 @@ bool TokenAnnotator::mustBreakForReturnType(const 
AnnotatedLine &Line) const {
   return false;
 }
 
-void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
+void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const 
{
   for (AnnotatedLine *ChildLine : Line.Children)
 calculateFormattingInformation(*ChildLine);
 
@@ -2845,7 +2845,8 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
   LLVM_DEBUG({ printDebugInfo(Line); });
 }
 
-void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
+void TokenAnnotator::calculateUnbreakableTailLengths(
+AnnotatedLine &Line) const {
   unsigned UnbreakableTailLength = 0;
   FormatToken *Current = Line.Last;
   while (Current) {
@@ -2861,7 +2862,8 @@ void 
TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
   }
 }
 
-void TokenAnnotator::calculateArrayInitializerColumnList(AnnotatedLine &Line) {
+void TokenAnnotator::calculateArrayInitializerColumnList(
+AnnotatedLine &Line) const {
   if (Line.First == Line.Last)
 return;
   auto *CurrentToken = Line.First;
@@ -2881,7 +2883,7 @@ void 
TokenAnnotator::calculateArrayInitializerColumnList(AnnotatedLine &Line) {
 }
 
 FormatToken *TokenAnnotator::calculateInitializerColumnList(
-AnnotatedLine &Line, FormatToken *CurrentToken, unsigned Depth) {
+AnnotatedLine &Line, FormatToken *CurrentToken, unsigned Depth) const {
   while (CurrentToken != nullptr && CurrentToken != Line.Last) {
 if (CurrentToken->is(tok::l_brace))
   ++Depth;
@@ -2901,7 +2903,7 @@ FormatToken 
*TokenAnnotator::calculateInitializerColumnList(
 
 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
   const FormatToken &Tok,
-  bool InFunctionDecl) {
+  bool InFunctionDecl) const {
   const FormatToken &Left = *Tok.Previous;
   const FormatToken &Right = Tok;
 
@@ -3113,7 +3115,7 @@ bool TokenAnnotator::spaceRequiredBeforeParens(const 
FormatToken &Right) const {
 
 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
   const FormatToken &Left,
-  const FormatToken &Right) {
+  const FormatToken &Right) const {
   if (Left.is(tok::kw_return) &&
   !Right.isOneOf(tok::semi, tok::r_paren, tok::hashhash))
 return true;
@@ -3491,7 +3493,7 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
 }
 
 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
- const FormatToken &Right) {
+ const FormatToken &Right) const {
   const FormatToken &Left = *Right.Previous;
 
   // If the token is finalized don't touch it (as it could be in a
@@ -3930,7 +3932,7 @@ static const FormatToken *getFirstNonComment(const 
AnnotatedLine &Line) {
 }
 
 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
- const FormatToken &Right) {
+ const FormatToken &Right) const {
   const FormatToken &Left = *Right.Previous;
   if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
 return true;
@@ -4310,7 +4312,7 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine 
&Line,
 }
 
 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
-   

[clang] 5fdc4dd - [analyzer] refactor makeIntValWithPtrWidth, remove getZeroWithPtrWidth (NFC)

2022-03-23 Thread via cfe-commits

Author: Vince Bridgers
Date: 2022-03-23T08:26:37-05:00
New Revision: 5fdc4dd7770486c0127dc5919aafea3f8ff2e61e

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

LOG: [analyzer] refactor makeIntValWithPtrWidth, remove getZeroWithPtrWidth 
(NFC)

This is a NFC refactoring to change makeIntValWithPtrWidth
and remove getZeroWithPtrWidth to use types when forming values to match
pointer widths. Some targets may have different pointer widths depending
upon address space, so this needs to be comprehended.

Reviewed By: steakhal

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/lib/StaticAnalyzer/Core/SValBuilder.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
index 8a778389bcbe1..e7d64313ea42c 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
@@ -220,14 +220,6 @@ class BasicValueFactory {
 return getValue(0, Ctx.getTypeSize(T), true);
   }
 
-  const llvm::APSInt &getZeroWithPtrWidth(bool isUnsigned = true) {
-return getValue(0, Ctx.getTypeSize(Ctx.VoidPtrTy), isUnsigned);
-  }
-
-  const llvm::APSInt &getIntWithPtrWidth(uint64_t X, bool isUnsigned) {
-return getValue(X, Ctx.getTypeSize(Ctx.VoidPtrTy), isUnsigned);
-  }
-
   const llvm::APSInt &getTruthValue(bool b, QualType T) {
 return getValue(b ? 1 : 0, Ctx.getIntWidth(T),
 T->isUnsignedIntegerOrEnumerationType());

diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
index 1f02ee84c898a..8452cf0ab 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
@@ -332,9 +332,8 @@ class SValBuilder {
 return nonloc::ConcreteInt(BasicVals.getIntValue(integer, isUnsigned));
   }
 
-  NonLoc makeIntValWithPtrWidth(uint64_t integer, bool isUnsigned) {
-return nonloc::ConcreteInt(
-BasicVals.getIntWithPtrWidth(integer, isUnsigned));
+  NonLoc makeIntValWithWidth(QualType ptrType, uint64_t integer) {
+return nonloc::ConcreteInt(BasicVals.getValue(integer, ptrType));
   }
 
   NonLoc makeLocAsInteger(Loc loc, unsigned bits) {

diff  --git a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
index 63b1065ae4de0..790a2fa4059d1 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -2608,8 +2608,9 @@ MallocChecker::ReallocMemAux(CheckerContext &C, const 
CallEvent &Call,
 
   // Compare the size argument to 0.
   DefinedOrUnknownSVal SizeZero =
-svalBuilder.evalEQ(State, TotalSize.castAs(),
-   svalBuilder.makeIntValWithPtrWidth(0, false));
+  svalBuilder.evalEQ(State, TotalSize.castAs(),
+ svalBuilder.makeIntValWithWidth(
+ svalBuilder.getContext().getSizeType(), 0));
 
   ProgramStateRef StatePtrIsNull, StatePtrNotNull;
   std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);

diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index e38c90603299a..6ad6eaf6dd468 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -1345,8 +1345,9 @@ void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
 case Stmt::GNUNullExprClass: {
   // GNU __null is a pointer-width integer, not an actual pointer.
   ProgramStateRef state = Pred->getState();
-  state = state->BindExpr(S, Pred->getLocationContext(),
-  svalBuilder.makeIntValWithPtrWidth(0, false));
+  state = state->BindExpr(
+  S, Pred->getLocationContext(),
+  svalBuilder.makeIntValWithWidth(getContext().VoidPtrTy, 0));
   Bldr.generateNode(S, Pred, state);
   break;
 }

diff  --git a/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp 
b/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
index a4a65ad20b577..e9a1ec3173a94 100644
--- a/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ b/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -742,9 +742,6 @@ SVal SValBuilder::evalCastSubKind(loc::MemRegionVal V, 
QualType CastTy,

[clang] 9ef7ac5 - [analyzer] Fix crash in RangedConstraintManager.cpp

2022-03-23 Thread via cfe-commits

Author: Vince Bridgers
Date: 2022-03-23T08:26:40-05:00
New Revision: 9ef7ac51af67d08212dc69e5a932c4aa447ee9b7

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

LOG: [analyzer] Fix crash in RangedConstraintManager.cpp

This change fixes a crash in RangedConstraintManager.cpp:assumeSym due to an
unhandled BO_Div case.

clang: clang/lib/StaticAnalyzer/Core/RangedConstraintManager.cpp:51:
  virtual clang::ento::ProgramStateRef
  clang::ento::RangedConstraintManager::assumeSym(clang::ento::ProgramStateRef,
clang::ento::SymbolRef, bool):
  Assertion `BinaryOperator::isComparisonOp(Op)' failed.

Reviewed By: NoQ

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

Added: 
clang/test/Analysis/symbol-simplification-bo-div.c

Modified: 
clang/lib/StaticAnalyzer/Core/RangedConstraintManager.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/RangedConstraintManager.cpp 
b/clang/lib/StaticAnalyzer/Core/RangedConstraintManager.cpp
index 892d64ea4e4e2..4bbe933be2129 100644
--- a/clang/lib/StaticAnalyzer/Core/RangedConstraintManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RangedConstraintManager.cpp
@@ -48,47 +48,48 @@ ProgramStateRef 
RangedConstraintManager::assumeSym(ProgramStateRef State,
 
   if (const auto *SSE = dyn_cast(Sym)) {
 BinaryOperator::Opcode Op = SSE->getOpcode();
-assert(BinaryOperator::isComparisonOp(Op));
-
-// We convert equality operations for pointers only.
-if (Loc::isLocType(SSE->getLHS()->getType()) &&
-Loc::isLocType(SSE->getRHS()->getType())) {
-  // Translate "a != b" to "(b - a) != 0".
-  // We invert the order of the operands as a heuristic for how loop
-  // conditions are usually written ("begin != end") as compared to length
-  // calculations ("end - begin"). The more correct thing to do would be to
-  // canonicalize "a - b" and "b - a", which would allow us to treat
-  // "a != b" and "b != a" the same.
-
-  SymbolManager &SymMgr = getSymbolManager();
-  QualType DiffTy = SymMgr.getContext().getPointerDiffType();
-  SymbolRef Subtraction =
-  SymMgr.getSymSymExpr(SSE->getRHS(), BO_Sub, SSE->getLHS(), DiffTy);
-
-  const llvm::APSInt &Zero = getBasicVals().getValue(0, DiffTy);
-  Op = BinaryOperator::reverseComparisonOp(Op);
-  if (!Assumption)
-Op = BinaryOperator::negateComparisonOp(Op);
-  return assumeSymRel(State, Subtraction, Op, Zero);
-}
+if (BinaryOperator::isComparisonOp(Op)) {
+
+  // We convert equality operations for pointers only.
+  if (Loc::isLocType(SSE->getLHS()->getType()) &&
+  Loc::isLocType(SSE->getRHS()->getType())) {
+// Translate "a != b" to "(b - a) != 0".
+// We invert the order of the operands as a heuristic for how loop
+// conditions are usually written ("begin != end") as compared to 
length
+// calculations ("end - begin"). The more correct thing to do would be
+// to canonicalize "a - b" and "b - a", which would allow us to treat
+// "a != b" and "b != a" the same.
+
+SymbolManager &SymMgr = getSymbolManager();
+QualType DiffTy = SymMgr.getContext().getPointerDiffType();
+SymbolRef Subtraction =
+SymMgr.getSymSymExpr(SSE->getRHS(), BO_Sub, SSE->getLHS(), DiffTy);
+
+const llvm::APSInt &Zero = getBasicVals().getValue(0, DiffTy);
+Op = BinaryOperator::reverseComparisonOp(Op);
+if (!Assumption)
+  Op = BinaryOperator::negateComparisonOp(Op);
+return assumeSymRel(State, Subtraction, Op, Zero);
+  }
 
-if (BinaryOperator::isEqualityOp(Op)) {
-  SymbolManager &SymMgr = getSymbolManager();
+  if (BinaryOperator::isEqualityOp(Op)) {
+SymbolManager &SymMgr = getSymbolManager();
 
-  QualType ExprType = SSE->getType();
-  SymbolRef CanonicalEquality =
-  SymMgr.getSymSymExpr(SSE->getLHS(), BO_EQ, SSE->getRHS(), ExprType);
+QualType ExprType = SSE->getType();
+SymbolRef CanonicalEquality =
+SymMgr.getSymSymExpr(SSE->getLHS(), BO_EQ, SSE->getRHS(), 
ExprType);
 
-  bool WasEqual = SSE->getOpcode() == BO_EQ;
-  bool IsExpectedEqual = WasEqual == Assumption;
+bool WasEqual = SSE->getOpcode() == BO_EQ;
+bool IsExpectedEqual = WasEqual == Assumption;
 
-  const llvm::APSInt &Zero = getBasicVals().getValue(0, ExprType);
+const llvm::APSInt &Zero = getBasicVals().getValue(0, ExprType);
 
-  if (IsExpectedEqual) {
-return assumeSymNE(State, CanonicalEquality, Zero, Zero);
-  }
+if (IsExpectedEqual) {
+  return assumeSymNE(State, CanonicalEquality, Zero, Zero);
+}
 
-  return assumeSymEQ(State, CanonicalEquality, Zero, Zero);
+return a

[clang] f74413d - [clang-format] Fix invalid code generation with comments in lambda

2022-03-23 Thread via cfe-commits

Author: owenca
Date: 2022-03-23T19:40:24-07:00
New Revision: f74413d16345c8815c7d1e4676d6aaf732517b8d

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

LOG: [clang-format] Fix invalid code generation with comments in lambda

Fixes #51234 and #54496

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index a6ca459a53337..c657d80ba0d5f 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2762,12 +2762,16 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
   Current->SpacesRequiredBefore = 1;
 }
 
-Current->MustBreakBefore =
-Current->MustBreakBefore || mustBreakBefore(Line, *Current);
-
-if (!Current->MustBreakBefore && InFunctionDecl &&
-Current->is(TT_FunctionDeclarationName))
-  Current->MustBreakBefore = mustBreakForReturnType(Line);
+const auto &Children = Prev->Children;
+if (!Children.empty() && Children.back()->Last->is(TT_LineComment)) {
+  Current->MustBreakBefore = true;
+} else {
+  Current->MustBreakBefore =
+  Current->MustBreakBefore || mustBreakBefore(Line, *Current);
+  if (!Current->MustBreakBefore && InFunctionDecl &&
+  Current->is(TT_FunctionDeclarationName))
+Current->MustBreakBefore = mustBreakForReturnType(Line);
+}
 
 Current->CanBreakBefore =
 Current->MustBreakBefore || canBreakBefore(Line, *Current);

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index e36a267c01f4b..e837dbd566957 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -21934,6 +21934,30 @@ TEST_F(FormatTest, LambdaWithLineComments) {
   "auto k = []() // \n"
   "{ return; }",
   LLVMWithBeforeLambdaBody);
+
+  LLVMWithBeforeLambdaBody.ColumnLimit = 0;
+
+  verifyFormat("foo([]()\n"
+   "{\n"
+   "  bar();//\n"
+   "  return 1; // comment\n"
+   "}());",
+   "foo([]() {\n"
+   "  bar(); //\n"
+   "  return 1; // comment\n"
+   "}());",
+   LLVMWithBeforeLambdaBody);
+  verifyFormat("foo(\n"
+   "1, MACRO {\n"
+   "  baz();\n"
+   "  bar(); // comment\n"
+   "},\n"
+   "[]() {});",
+   "foo(\n"
+   "  1, MACRO { baz(); bar(); // comment\n"
+   "  }, []() {}\n"
+   ");",
+   LLVMWithBeforeLambdaBody);
 }
 
 TEST_F(FormatTest, EmptyLinesInLambdas) {



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


[clang-tools-extra] 39b80c8 - [clang-tidy] Add modernize-macro-to-enum check

2022-03-25 Thread via cfe-commits

Author: Richard
Date: 2022-03-25T09:45:55-06:00
New Revision: 39b80c8380c86539de391600efaa17184b5a52b4

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

LOG: [clang-tidy] Add modernize-macro-to-enum check

This check performs basic analysis of macros and replaces them
with an anonymous unscoped enum.  Using an unscoped anonymous enum
ensures that everywhere the macro token was used previously, the
enumerator name may be safely used.

Potential macros for replacement must meet the following constraints:
- Macros must expand only to integral literal tokens.  The unary
  operators plus, minus and tilde are recognized to allow for positive,
  negative and bitwise negated integers.
- Macros must be defined on sequential source file lines, or with
  only comment lines in between macro definitions.
- Macros must all be defined in the same source file.
- Macros must not be defined within a conditional compilation block.
- Macros must not be defined adjacent to other preprocessor directives.
- Macros must not be used in preprocessor conditions

Each cluster of macros meeting the above constraints is presumed to
be a set of values suitable for replacement by an anonymous enum.
>From there, a developer can give the anonymous enum a name and
continue refactoring to a scoped enum if desired.  Comments on the
same line as a macro definition or between subsequent macro definitions
are preserved in the output.  No formatting is assumed in the provided
replacements.

The check cppcoreguidelines-macro-to-enum is an alias for this check.

Fixes #27408

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

Added: 
clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.h
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines-macro-to-enum.rst
clang-tools-extra/docs/clang-tidy/checks/modernize-macro-to-enum.rst

clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-macro-to-enum/modernize-macro-to-enum.h

clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-macro-to-enum/modernize-macro-to-enum2.h

clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-macro-to-enum/modernize-macro-to-enum3.h
clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp

Modified: 
clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/list.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 147c2741d59e4..6bf20552e0182 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -11,6 +11,7 @@ add_clang_library(clangTidyModernizeModule
   DeprecatedIosBaseAliasesCheck.cpp
   LoopConvertCheck.cpp
   LoopConvertUtils.cpp
+  MacroToEnumCheck.cpp
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp

diff  --git a/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
new file mode 100644
index 0..834943483cffb
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
@@ -0,0 +1,482 @@
+//===--- MacroToEnumCheck.cpp - clang-tidy 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "MacroToEnumCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+#include "llvm/ADT/STLExtras.h"
+#include 
+#include 
+#include 
+#include 
+
+namespace clang {
+namespace tidy {
+namespace modernize {
+
+static bool hasOnlyComments(SourceLocation Loc, const LangOptions &Options,
+StringRef Text) {
+  // Use a lexer to look for tokens; if we find something other than a single
+  // hash, then there were intervening tokens between macro definitions.
+  std::string Buffer{Text};
+  Lexer Lex(Loc, Options, Buffer.c_str(), Buffer.c_str(),
+Buffer.c_str() + Buffer.size());
+  Token Tok;
+  bool SeenHash = false;
+  while (!Lex.LexFromRawLexer(Tok)) {
+if (Tok.getKind() == tok::hash && !SeenHash) {
+  SeenHash = true;
+  continue;
+}
+return false;
+  }
+
+  // Everything in between was whitespace, so now just look for two blank 
lines,
+  // consisting of two consecutive E

[clang] eee536d - [clang-format] Don't format qualifiers in PPDirective

2022-03-28 Thread via cfe-commits

Author: owenca
Date: 2022-03-28T14:28:14-07:00
New Revision: eee536dd31859058dba8a0d17d3b5f61d530d3bc

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

LOG: [clang-format] Don't format qualifiers in PPDirective

Fixes #54513

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

Added: 


Modified: 
clang/lib/Format/QualifierAlignmentFixer.cpp
clang/unittests/Format/QualifierFixerTest.cpp

Removed: 




diff  --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index 74802026690ef..fc37f18c790a4 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -407,6 +407,8 @@ LeftRightQualifierAlignmentFixer::analyze(
   assert(QualifierToken != tok::identifier && "Unrecognised Qualifier");
 
   for (AnnotatedLine *Line : AnnotatedLines) {
+if (Line->InPPDirective)
+  continue;
 FormatToken *First = Line->First;
 assert(First);
 if (First->Finalized)

diff  --git a/clang/unittests/Format/QualifierFixerTest.cpp 
b/clang/unittests/Format/QualifierFixerTest.cpp
index 167a30ec09d3f..cd796f48cb568 100755
--- a/clang/unittests/Format/QualifierFixerTest.cpp
+++ b/clang/unittests/Format/QualifierFixerTest.cpp
@@ -815,6 +815,7 @@ TEST_F(QualifierFixerTest, NoOpQualifierReplacements) {
   ReplacementCount = 0;
   EXPECT_EQ(ReplacementCount, 0);
   verifyFormat("static const uint32 foo[] = {0, 31};", Style);
+  verifyFormat("#define MACRO static const", Style);
   EXPECT_EQ(ReplacementCount, 0);
 }
 



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


[clang] a590040 - [RISCV][test] Make PATH empty when testing --gcc-toolchain is multilib_riscv_elf_sdk

2022-03-28 Thread via cfe-commits

Author: luxufan
Date: 2022-03-29T14:51:23+08:00
New Revision: a5900401b1475cdf98dbd210ac4bc362563cebbf

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

LOG: [RISCV][test] Make PATH empty when testing --gcc-toolchain is 
multilib_riscv_elf_sdk

Due to D79842, clang dirver would search possible tool name in both possible
locations, then moving to the next name. The gcc toolchain 
`llvm-project/clang/test/Driver/
Inputs/multilib_riscv_elf_sdk` don't have a `riscv64-unknown-elf-ld` executable 
in
`llvm-project/clang/test/Driver/Inputs/multilib_riscv_elf_sdk/bin/`. So when 
searching
`riscv64-unknown-elf-ld`, if there is a `riscv64-unknown-elf-ld` in `PATH`, the
test would fail.

This patch makes the `PATH` empty when testing it.

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

Added: 


Modified: 
clang/test/Driver/riscv32-toolchain.c
clang/test/Driver/riscv64-toolchain.c

Removed: 




diff  --git a/clang/test/Driver/riscv32-toolchain.c 
b/clang/test/Driver/riscv32-toolchain.c
index 4eefa006c129f..1e6c8deb3de37 100644
--- a/clang/test/Driver/riscv32-toolchain.c
+++ b/clang/test/Driver/riscv32-toolchain.c
@@ -1,3 +1,4 @@
+// UNSUPPORTED: system-windows
 // A basic clang -cc1 command-line, and simple environment check.
 
 // RUN: %clang %s -### -no-canonical-prefixes --target=riscv32 \
@@ -74,7 +75,7 @@
 // CXX-RV32-BAREMETAL-NOSYSROOT-ILP32: "-lstdc++" "--start-group" "-lc" 
"-lgloss" "--end-group" "-lgcc"
 // CXX-RV32-BAREMETAL-NOSYSROOT-ILP32: 
"{{.*}}/Inputs/basic_riscv32_tree/lib/gcc/riscv32-unknown-elf/8.0.1{{/|}}crtend.o"
 
-// RUN: %clang %s -### -fuse-ld=ld -no-pie \
+// RUN: env "PATH=" %clang %s -### -fuse-ld=ld -no-pie \
 // RUN:   --target=riscv32-unknown-linux-gnu --rtlib=platform -mabi=ilp32 \
 // RUN:   --gcc-toolchain=%S/Inputs/multilib_riscv_linux_sdk \
 // RUN:   --sysroot=%S/Inputs/multilib_riscv_linux_sdk/sysroot 2>&1 \
@@ -89,7 +90,7 @@
 // C-RV32-LINUX-MULTI-ILP32: 
"-L{{.*}}/Inputs/multilib_riscv_linux_sdk/sysroot/lib32/ilp32"
 // C-RV32-LINUX-MULTI-ILP32: 
"-L{{.*}}/Inputs/multilib_riscv_linux_sdk/sysroot/usr/lib32/ilp32"
 
-// RUN: %clang %s -### -fuse-ld=ld -no-pie \
+// RUN: env "PATH=" %clang %s -### -fuse-ld=ld -no-pie \
 // RUN:   --target=riscv32-unknown-linux-gnu --rtlib=platform -march=rv32imafd 
\
 // RUN:   --gcc-toolchain=%S/Inputs/multilib_riscv_linux_sdk \
 // RUN:   --sysroot=%S/Inputs/multilib_riscv_linux_sdk/sysroot 2>&1 \
@@ -104,7 +105,7 @@
 // C-RV32-LINUX-MULTI-ILP32D: 
"-L{{.*}}/Inputs/multilib_riscv_linux_sdk/sysroot/lib32/ilp32d"
 // C-RV32-LINUX-MULTI-ILP32D: 
"-L{{.*}}/Inputs/multilib_riscv_linux_sdk/sysroot/usr/lib32/ilp32d"
 
-// RUN: %clang %s -### -fuse-ld=ld \
+// RUN: env "PATH=" %clang %s -### -fuse-ld=ld \
 // RUN:   --target=riscv32-unknown-elf --rtlib=platform --sysroot= \
 // RUN:   --gcc-toolchain=%S/Inputs/multilib_riscv_elf_sdk 2>&1 \
 // RUN:   | FileCheck -check-prefix=C-RV32I-BAREMETAL-MULTI-ILP32 %s
@@ -118,7 +119,7 @@
 // C-RV32I-BAREMETAL-MULTI-ILP32: "--start-group" "-lc" "-lgloss" 
"--end-group" "-lgcc"
 // C-RV32I-BAREMETAL-MULTI-ILP32: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv32imac/ilp32{{/|}}crtend.o"
 
-// RUN: %clang %s -### -fuse-ld=ld \
+// RUN: env "PATH=" %clang %s -### -fuse-ld=ld \
 // RUN:   --target=riscv32-unknown-elf --rtlib=platform --sysroot= \
 // RUN:   -march=rv32im -mabi=ilp32\
 // RUN:   --gcc-toolchain=%S/Inputs/multilib_riscv_elf_sdk 2>&1 \
@@ -133,7 +134,7 @@
 // C-RV32IM-BAREMETAL-MULTI-ILP32: "--start-group" "-lc" "-lgloss" 
"--end-group" "-lgcc"
 // C-RV32IM-BAREMETAL-MULTI-ILP32: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv32im/ilp32{{/|}}crtend.o"
 
-// RUN: %clang %s -### -fuse-ld=ld \
+// RUN: env "PATH=" %clang %s -### -fuse-ld=ld \
 // RUN:   --target=riscv32-unknown-elf --rtlib=platform --sysroot= \
 // RUN:   -march=rv32iac -mabi=ilp32\
 // RUN:   --gcc-toolchain=%S/Inputs/multilib_riscv_elf_sdk 2>&1 \
@@ -148,7 +149,7 @@
 // C-RV32IAC-BAREMETAL-MULTI-ILP32: "--start-group" "-lc" "-lgloss" 
"--end-group" "-lgcc"
 // C-RV32IAC-BAREMETAL-MULTI-ILP32: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv32iac/ilp32{{/|}}crtend.o"
 
-// RUN: %clang %s -### -fuse-ld=ld \
+// RUN: env "PATH=" %clang %s -### -fuse-ld=ld \
 // RUN:   --target=riscv32-unknown-elf --rtlib=platform --sysroot= \
 // RUN:   -march=rv32imac -mabi=ilp32\
 // RUN:   --gcc-toolchain=%S/Inputs/multilib_riscv_elf_sdk 2>&1 \
@@ -163,7 +164,7 @@
 // C-RV32IMAC-BAREMETAL-MULTI-ILP32: "--start-group" "-lc" "-lgloss" 
"--end-group" "-lgcc"
 // C-RV32IMAC-BAREMETAL-MULTI-ILP32: 
"{{.*}}/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv32imac/ilp32{{/|}}crtend.o"
 
-// RUN: %clang 

[clang] f5c6667 - [doc] Rely on tblgen to dump supported options value when generating doc

2022-03-29 Thread via cfe-commits

Author: serge-sans-paille
Date: 2022-03-29T12:25:33+02:00
New Revision: f5c666742f7bb4ae79ec79c8acf61dced4d37cc9

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

LOG: [doc] Rely on tblgen to dump supported options value when generating doc

It was already the case for CLI help, also support it for rst output. As a side
effect remove redundant (and sometime inconsistent!) value help from HelpText in
clang/Driver/Options.td.

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

Added: 


Modified: 
clang/include/clang/Driver/Options.td
llvm/utils/TableGen/OptRSTEmitter.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 8c488f254b1ec..153badd971349 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -960,7 +960,7 @@ defm cuda_short_ptr : BoolFOption<"cuda-short-ptr",
   PosFlag,
   NegFlag>;
 def fgpu_default_stream_EQ : Joined<["-"], "fgpu-default-stream=">,
-  HelpText<"Specify default stream. Valid values are 'legacy' and 
'per-thread'. The default value is 'legacy'. (HIP only)">,
+  HelpText<"Specify default stream. The default value is 'legacy'. (HIP 
only)">,
   Flags<[CC1Option]>,
   Values<"legacy,per-thread">,
   NormalizedValuesScope<"LangOptions::GPUDefaultStreamKind">,
@@ -1173,7 +1173,7 @@ def fembed_offload_object_EQ : Joined<["-"], 
"fembed-offload-object=">,
   MarshallingInfoStringVector>;
 def fembed_bitcode_EQ : Joined<["-"], "fembed-bitcode=">,
 Group, Flags<[NoXarchOption, CC1Option, CC1AsOption]>, 
MetaVarName<"">,
-HelpText<"Embed LLVM bitcode (option: off, all, bitcode, marker)">,
+HelpText<"Embed LLVM bitcode">,
 Values<"off,all,bitcode,marker">, NormalizedValuesScope<"CodeGenOptions">,
 NormalizedValues<["Embed_Off", "Embed_All", "Embed_Bitcode", 
"Embed_Marker"]>,
 MarshallingInfoEnum, "Embed_Off">;
@@ -1299,7 +1299,7 @@ def fprofile_exclude_files_EQ : Joined<["-"], 
"fprofile-exclude-files=">,
 ShouldParseIf;
 def fprofile_update_EQ : Joined<["-"], "fprofile-update=">,
 Group, Flags<[CC1Option, CoreOption]>, 
Values<"atomic,prefer-atomic,single">,
-MetaVarName<"">, HelpText<"Set update method of profile counters 
(atomic,prefer-atomic,single)">,
+MetaVarName<"">, HelpText<"Set update method of profile counters">,
 MarshallingInfoFlag>;
 defm pseudo_probe_for_profiling : BoolFOption<"pseudo-probe-for-profiling",
   CodeGenOpts<"PseudoProbeForProfiling">, DefaultFalse,
@@ -1314,7 +1314,7 @@ def fprofile_list_EQ : Joined<["-"], "fprofile-list=">,
 MarshallingInfoStringVector>;
 def fswift_async_fp_EQ : Joined<["-"], "fswift-async-fp=">,
 Group, Flags<[CC1Option, CC1AsOption, CoreOption]>, 
MetaVarName<"">,
-HelpText<"Control emission of Swift async extended frame info (option: 
auto, always, never)">,
+HelpText<"Control emission of Swift async extended frame info">,
 Values<"auto,always,never">,
 NormalizedValuesScope<"CodeGenOptions::SwiftAsyncFramePointerKind">,
 NormalizedValues<["Auto", "Always", "Never"]>,
@@ -1485,7 +1485,7 @@ def fseh_exceptions : Flag<["-"], "fseh-exceptions">, 
Group,
 def fwasm_exceptions : Flag<["-"], "fwasm-exceptions">, Group,
   HelpText<"Use WebAssembly style exceptions">;
 def exception_model : Separate<["-"], "exception-model">,
-  Flags<[CC1Option, NoDriverOption]>, HelpText<"The exception model: 
dwarf|sjlj|seh|wasm">,
+  Flags<[CC1Option, NoDriverOption]>, HelpText<"The exception model">,
   Values<"dwarf,sjlj,seh,wasm">,
   NormalizedValuesScope<"LangOptions::ExceptionHandlingKind">,
   NormalizedValues<["DwarfCFI", "SjLj", "WinEH", "Wasm"]>,
@@ -1667,7 +1667,7 @@ def sanitize_address_use_after_return_EQ
   : Joined<["-"], "fsanitize-address-use-after-return=">,
 MetaVarName<"">,
 Flags<[CC1Option]>,
-HelpText<"Select the mode of detecting stack use-after-return in 
AddressSanitizer: never | runtime (default) | always">,
+HelpText<"Select the mode of detecting stack use-after-return in 
AddressSanitizer">,
 Group,
 Values<"never,runtime,always">,
 NormalizedValuesScope<"llvm::AsanDetectStackUseAfterReturnMode">,
@@ -1958,7 +1958,7 @@ def finstrument_function_entry_bare : Flag<["-"], 
"finstrument-function-entry-ba
   HelpText<"Instrument function entry only, after inlining, without arguments 
to the instrumentation call">,
   MarshallingInfoFlag>;
 def fcf_protection_EQ : Joined<["-"], "fcf-protection=">, Flags<[CoreOption, 
CC1Option]>, Group,
-  HelpText<"Instrument control-flow architecture protection. Options: return, 
branch, full, none.">, Values<"return,branch,full,none">;
+  HelpText<"Instrument control-flow architecture protection">, 
Values<"return,branch,full,none">;
 def fcf_protection : F

[clang] fe8b223 - [analyzer] Fix "RhsLoc and LhsLoc bitwidth must be same"

2022-03-29 Thread via cfe-commits

Author: Vince Bridgers
Date: 2022-03-29T17:08:19-05:00
New Revision: fe8b2236ef9cf873875135dcc41364911898698d

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

LOG: [analyzer] Fix "RhsLoc and LhsLoc bitwidth must be same"

clang: /clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:727:
void assertEqualBitWidths(clang::ento::ProgramStateRef,
  clang::ento::Loc, clang::ento::Loc): Assertion `RhsBitwidth ==
  LhsBitwidth && "RhsLoc and LhsLoc bitwidth must be same!"'

This change adjusts the bitwidth of the smaller operand for an evalBinOp
as a result of a comparison operation. This can occur in the specific
case represented by the test cases for a target with different pointer
sizes.

Reviewed By: NoQ

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

Added: 
clang/test/Analysis/addrspace-null.c

Modified: 
clang/lib/StaticAnalyzer/Core/SValBuilder.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp 
b/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
index e9a1ec3173a94..e045c9a91e60c 100644
--- a/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ b/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -682,8 +682,11 @@ SVal SValBuilder::evalCastSubKind(loc::ConcreteInt V, 
QualType CastTy,
   }
 
   // Pointer to any pointer.
-  if (Loc::isLocType(CastTy))
-return V;
+  if (Loc::isLocType(CastTy)) {
+llvm::APSInt Value = V.getValue();
+BasicVals.getAPSIntType(CastTy).apply(Value);
+return loc::ConcreteInt(BasicVals.getValue(Value));
+  }
 
   // Pointer to whatever else.
   return UnknownVal();

diff  --git a/clang/test/Analysis/addrspace-null.c 
b/clang/test/Analysis/addrspace-null.c
new file mode 100644
index 0..54d96b277db04
--- /dev/null
+++ b/clang/test/Analysis/addrspace-null.c
@@ -0,0 +1,47 @@
+// RUN: %clang_analyze_cc1 -triple amdgcn-unknown-unknown \
+// RUN: -analyze -analyzer-checker=core -DAMDGCN_TRIPLE \
+// RUN: -analyze -analyzer-checker=debug.ExprInspection \
+// RUN: -Wno-implicit-int -Wno-int-conversion -verify %s
+//
+// RUN: %clang_analyze_cc1 -triple amdgcn-unknown-unknown \
+// RUN: -analyze -analyzer-checker=core -DDEFAULT_TRIPLE \
+// RUN: -analyze -analyzer-checker=debug.ExprInspection \
+// RUN: -Wno-implicit-int -Wno-int-conversion -verify %s
+
+// From https://llvm.org/docs/AMDGPUUsage.html#address-spaces,
+// select address space 3 (local), since the pointer size is
+// 
diff erent than Generic.
+
+// expected-no-diagnostics
+
+#define DEVICE __attribute__((address_space(3)))
+
+#if defined(AMDGCN_TRIPLE)
+// this crashes
+int fn1() {
+  int val = 0;
+  DEVICE int *dptr = val;
+  return dptr == (void *)0;
+}
+
+// does not crash
+int fn2() {
+  int val = 0;
+  DEVICE int *dptr = val;
+  return dptr == (DEVICE void *)0;
+}
+
+// this crashes
+int fn3() {
+  int val = 0;
+  int *dptr = val;
+  return dptr == (DEVICE void *)0;
+}
+#endif
+
+// does not crash
+int fn4() {
+  int val = 0;
+  int *dptr = val;
+  return dptr == (void *)0;
+}



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


[clang] cebbfd3 - [RISCV] Add index check for vset/vget

2022-03-30 Thread via cfe-commits

Author: wangpc
Date: 2022-03-30T19:29:13+08:00
New Revision: cebbfd3d22b48cb3681a326bcbd23aaca1ec

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

LOG: [RISCV] Add index check for vset/vget

Index of vset/vget must be a constant integer and be
located in right range.

Reviewed By: kito-cheng

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

Added: 
clang/test/CodeGen/RISCV/rvv-intrinsics/vget-index-out-of-range.c
clang/test/CodeGen/RISCV/rvv-intrinsics/vset-index-out-of-range.c

Modified: 
clang/lib/Sema/SemaChecking.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 14e82e54eacb3..7e73988c33b74 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -4098,6 +4098,30 @@ bool Sema::CheckRISCVBuiltinFunctionCall(const 
TargetInfo &TI,
   case RISCVVector::BI__builtin_rvv_vsetvlimax:
 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
CheckRISCVLMUL(TheCall, 1);
+  case RISCVVector::BI__builtin_rvv_vget_v: {
+ASTContext::BuiltinVectorTypeInfo ResVecInfo =
+Context.getBuiltinVectorTypeInfo(cast(
+TheCall->getType().getCanonicalType().getTypePtr()));
+ASTContext::BuiltinVectorTypeInfo VecInfo =
+Context.getBuiltinVectorTypeInfo(cast(
+TheCall->getArg(0)->getType().getCanonicalType().getTypePtr()));
+unsigned MaxIndex =
+(VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors) /
+(ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors);
+return SemaBuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1);
+  }
+  case RISCVVector::BI__builtin_rvv_vset_v: {
+ASTContext::BuiltinVectorTypeInfo ResVecInfo =
+Context.getBuiltinVectorTypeInfo(cast(
+TheCall->getType().getCanonicalType().getTypePtr()));
+ASTContext::BuiltinVectorTypeInfo VecInfo =
+Context.getBuiltinVectorTypeInfo(cast(
+TheCall->getArg(2)->getType().getCanonicalType().getTypePtr()));
+unsigned MaxIndex =
+(ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors) /
+(VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors);
+return SemaBuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1);
+  }
   // Check if byteselect is in [0, 3]
   case RISCV::BI__builtin_riscv_aes32dsi_32:
   case RISCV::BI__builtin_riscv_aes32dsmi_32:

diff  --git a/clang/test/CodeGen/RISCV/rvv-intrinsics/vget-index-out-of-range.c 
b/clang/test/CodeGen/RISCV/rvv-intrinsics/vget-index-out-of-range.c
new file mode 100644
index 0..c8c086686c42e
--- /dev/null
+++ b/clang/test/CodeGen/RISCV/rvv-intrinsics/vget-index-out-of-range.c
@@ -0,0 +1,341 @@
+// REQUIRES: riscv-registered-target
+// RUN: %clang_cc1 -triple riscv64 -target-feature +f -target-feature +d \
+// RUN:   -target-feature +v -target-feature +zfh -target-feature 
+experimental-zvfh \
+// RUN:   -fsyntax-only -verify %s
+
+#include 
+
+vint8m1_t test_vget_v_index_not_constant(vint8m2_t src, int index) {
+  // expected-error@+1 {{argument to 'vget_v_i8m2_i8m1' must be a constant 
integer}}
+  return vget_v_i8m2_i8m1(src, index);
+}
+
+vint8m1_t test_vget_v_i8m2_i8m1(vint8m2_t src) {
+  // expected-error@+1 {{argument value 2 is outside the valid range [0, 1]}}
+  return vget_v_i8m2_i8m1(src, 2);
+}
+
+vint8m1_t test_vget_v_i8m4_i8m1(vint8m4_t src) {
+  // expected-error@+1 {{argument value 4 is outside the valid range [0, 3]}}
+  return vget_v_i8m4_i8m1(src, 4);
+}
+
+vint8m2_t test_vget_v_i8m4_i8m2(vint8m4_t src) {
+  // expected-error@+1 {{argument value 2 is outside the valid range [0, 1]}}
+  return vget_v_i8m4_i8m2(src, 2);
+}
+
+vint8m1_t test_vget_v_i8m8_i8m1(vint8m8_t src) {
+  // expected-error@+1 {{argument value 8 is outside the valid range [0, 7]}}
+  return vget_v_i8m8_i8m1(src, 8);
+}
+
+vint8m2_t test_vget_v_i8m8_i8m2(vint8m8_t src) {
+  // expected-error@+1 {{argument value 4 is outside the valid range [0, 3]}}
+  return vget_v_i8m8_i8m2(src, 4);
+}
+
+vint8m4_t test_vget_v_i8m8_i8m4(vint8m8_t src) {
+  // expected-error@+1 {{argument value 2 is outside the valid range [0, 1]}}
+  return vget_v_i8m8_i8m4(src, 2);
+}
+
+vint16m1_t test_vget_v_i16m2_i16m1(vint16m2_t src) {
+  // expected-error@+1 {{argument value 2 is outside the valid range [0, 1]}}
+  return vget_v_i16m2_i16m1(src, 2);
+}
+
+vint16m1_t test_vget_v_i16m4_i16m1(vint16m4_t src) {
+  // expected-error@+1 {{argument value 4 is outside the valid range [0, 3]}}
+  return vget_v_i16m4_i16m1(src, 4);
+}
+
+vint16m2_t test_vget_v_i16m4_i16m2(vint16m4_t src) {
+  // expected-error@+1 {{argument value 2 is outside the valid range [0, 1]}}
+  return vget_v_i16m4_i16m2(src, 2);
+}
+
+vint16m1_t test_vget_v_i16m8_i16m1(vint16m8_t src) {
+  // expected-error@+1 {{ar

[clang] f6740fe - [clang-format] Indent import statements in JavaScript.

2022-03-30 Thread via cfe-commits

Author: sstwcw
Date: 2022-03-30T23:17:27Z
New Revision: f6740fe483e9fa0c76aa9f176ff68f51f47a1302

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

LOG: [clang-format] Indent import statements in JavaScript.

[clang-format] Indent import statements in JavaScript.

Take for example this piece of code found at
.

```
for (const link of document.querySelectorAll("nav > a")) {
  link.addEventListener("click", e => {
e.preventDefault();

import('/modules/my-module.js')
.then(module => {
  module.loadPageInto(main);
})
.catch(err => {
  main.textContent = err.message;
});
  });
}
```

Previously the import line would be unindented, looking like this.

```
for (const link of document.querySelectorAll("nav > a")) {
  link.addEventListener("click", e => {
e.preventDefault();

import('/modules/my-module.js')
.then(module => {
  module.loadPageInto(main);
})
.catch(err => {
  main.textContent = err.message;
});
  });
}
```

Actually we were going to fix this along with fixing Verilog import
statements.  But the patch got too big.

Reviewed By: MyDeveloperDay, curdeius

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineFormatter.cpp
clang/unittests/Format/FormatTestJS.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 1393a2a321183..e2dbc35c22004 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -1431,8 +1431,10 @@ void UnwrappedLineFormatter::formatFirstToken(
   if (Newlines)
 Indent = NewlineIndent;
 
-  // Preprocessor directives get indented before the hash only if specified
-  if (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
+  // Preprocessor directives get indented before the hash only if specified. In
+  // Javascript import statements are indented like normal statements.
+  if (!Style.isJavaScript() &&
+  Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
   (Line.Type == LT_PreprocessorDirective ||
Line.Type == LT_ImportStatement))
 Indent = 0;

diff  --git a/clang/unittests/Format/FormatTestJS.cpp 
b/clang/unittests/Format/FormatTestJS.cpp
index 6077d21c5e582..9883aae62191a 100644
--- a/clang/unittests/Format/FormatTestJS.cpp
+++ b/clang/unittests/Format/FormatTestJS.cpp
@@ -1875,6 +1875,11 @@ TEST_F(FormatTestJS, Modules) {
   " myX} from 'm';");
   verifyFormat("import * as lib from 'some/module.js';");
   verifyFormat("var x = {import: 1};\nx.import = 2;");
+  // Ensure an import statement inside a block is at the correct level.
+  verifyFormat("function() {\n"
+   "  var x;\n"
+   "  import 'some/module.js';\n"
+   "}");
 
   verifyFormat("export function fn() {\n"
"  return 'fn';\n"



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


[clang] 907d3ac - [Clang][CodeGen]Beautify dump format, add indent for nested struct and struct members

2022-03-30 Thread via cfe-commits

Author: wangyihan
Date: 2022-03-31T07:38:37+08:00
New Revision: 907d3acefc3bdd6eb83f21589c6473ca7e88b3eb

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

LOG: [Clang][CodeGen]Beautify dump format, add indent for nested struct and 
struct members

Beautify dump format, add indent for nested struct and struct members, also fix 
test cases in dump-struct-builtin.c
for example:
struct:
```
  struct A {
int a;
struct B {
  int b;
  struct C {
struct D {
  int d;
  union E {
int x;
int y;
  } e;
} d;
int c;
  } c;
} b;
  };
```
Before:
```
struct A {
int a = 0
struct B {
int b = 0
struct C {
struct D {
int d = 0
union E {
int x = 0
int y = 0
}
}
int c = 0
}
}
}
```
After:
```
struct A {
int a = 0
struct B {
int b = 0
struct C {
struct D {
int d = 0
union E {
int x = 0
int y = 0
}
}
int c = 0
}
}
}
```

Reviewed By: erichkeane

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/CodeGen/CGBuiltin.cpp
clang/test/CodeGen/dump-struct-builtin.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 69806fa4407dc..acc433f2bc86b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -117,6 +117,7 @@ Non-comprehensive list of changes in this release
   - Support bitfields in struct and union.
   - Improve the dump format, dump both bitwidth(if its a bitfield) and field 
value.
   - Remove anonymous tag locations.
+  - Beautify dump format, add indent for nested struct and struct members.
 
 New Compiler Flags
 --

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 2159dd7139101..ffba93846958e 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -2049,11 +2049,12 @@ static llvm::Value *dumpRecord(CodeGenFunction &CGF, 
QualType RType,
   ASTContext &Context = CGF.getContext();
   RecordDecl *RD = RType->castAs()->getDecl()->getDefinition();
   std::string Pad = std::string(Lvl * 4, ' ');
+  std::string ElementPad = std::string((Lvl + 1) * 4, ' ');
 
   PrintingPolicy Policy(Context.getLangOpts());
   Policy.AnonymousTagLocations = false;
-  Value *GString =
-  CGF.Builder.CreateGlobalStringPtr(RType.getAsString(Policy) + " {\n");
+  Value *GString = CGF.Builder.CreateGlobalStringPtr(
+llvm::Twine(Pad).concat(RType.getAsString(Policy)).concat(" {\n").str());
   Value *Res = CGF.Builder.CreateCall(Func, {GString});
 
   static llvm::DenseMap Types;
@@ -2081,7 +2082,7 @@ static llvm::Value *dumpRecord(CodeGenFunction &CGF, 
QualType RType,
   for (const auto *FD : RD->fields()) {
 Value *TmpRes = nullptr;
 
-std::string Format = llvm::Twine(Pad)
+std::string Format = llvm::Twine(ElementPad)
  .concat(FD->getType().getAsString())
  .concat(llvm::Twine(' '))
  .concat(FD->getNameAsString())

diff  --git a/clang/test/CodeGen/dump-struct-builtin.c 
b/clang/test/CodeGen/dump-struct-builtin.c
index 8b5db4dbbe280..faa1fa7889f1c 100644
--- a/clang/test/CodeGen/dump-struct-builtin.c
+++ b/clang/test/CodeGen/dump-struct-builtin.c
@@ -5,93 +5,93 @@
 
 // CHECK: @__const.unit1.a = private unnamed_addr constant %struct.U1A { i16 
12 }, align 2
 // CHECK-NEXT: [[STRUCT_STR_U1:@[0-9]+]] = private unnamed_addr constant [14 x 
i8] c"struct U1A {\0A\00", align 1
-// CHECK-NEXT: [[FIELD_U1:@[0-9]+]] = private unnamed_addr constant [15 x i8] 
c"short a = %hd\0A\00", align 1
+// CHECK-NEXT: [[FIELD_U1:@[0-9]+]] = private unnamed_addr constant [19 x i8] 
c"short a = %hd\0A\00", align 1
 // CHECK-NEXT: [[END_STRUCT_U1:@[0-9]+]] = private unnamed_addr constant [3 x 
i8] c"}\0A\00", align 1
 
 // CHECK: @__const.unit2.a = private unnamed_addr constant %struct.U2A { i16 
12 }, align 2
 // CHECK-NEXT: [[STRUCT_STR_U2:@[0-9]+]] = private unnamed_addr constant [14 x 
i8] c"struct U2A {\0A\00", align 1
-// CHECK-NEXT: [[FIELD_U2:@[0-9]+]] = private unnamed_addr constant [24 x i8] 
c"unsigned short a = %hu\0A\00", align 1
+// CHECK-NEXT: [[FIELD_U2:@[0-9]+]] = private unnamed_addr constant [28 x i8] 
c"unsigned short a = %hu\0A\00", align 1
 // CHECK-NEXT: [[END_STRUCT_U2:@[0-9]+]] = private unnamed_addr constant [3 x 
i8] c"}\0A\00", align 1
 
 // CHECK: @__const.unit3.a = private unnamed_addr constant %struct.U3A { i32 
12 }, align 4
 // CHECK-NEXT: [[STR

[clang] 4d5b824 - [analyzer] Avoid checking addrspace pointers in cstring checker

2022-03-31 Thread via cfe-commits

Author: Vince Bridgers
Date: 2022-03-31T17:34:56+02:00
New Revision: 4d5b824e3df21c9cfa7a14ea746c83d0d41dd3ed

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

LOG: [analyzer] Avoid checking addrspace pointers in cstring checker

This change fixes an assert that occurs in the SMT layer when refuting a
finding that uses pointers of two different sizes. This was found in a
downstream build that supports two different pointer sizes, The CString
Checker was attempting to compute an overlap for the 'to' and 'from'
pointers, where the pointers were of different sizes.

In the downstream case where this was found, a specialized memcpy
routine patterned after memcpy_special is used. The analyzer core hits
on this builtin because it matches the 'memcpy' portion of that builtin.
This cannot be duplicated in the upstream test since there are no
specialized builtins that match that pattern, but the case does
reproduce in the accompanying LIT test case. The amdgcn target was used
for this reproducer. See the documentation for AMDGPU address spaces here
https://llvm.org/docs/AMDGPUUsage.html#address-spaces.

The assert seen is:

`*Solver->getSort(LHS) == *Solver->getSort(RHS) && "AST's must have the same 
sort!"'

Ack to steakhal for reviewing the fix, and creating the test case.

Reviewed By: steakhal

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

Added: 
clang/test/Analysis/cstring-addrspace.c

Modified: 
clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
index 23c10431a5dfb..dd2185270321e 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -460,6 +460,11 @@ ProgramStateRef 
CStringChecker::CheckOverlap(CheckerContext &C,
 
   ProgramStateRef stateTrue, stateFalse;
 
+  // Assume 
diff erent address spaces cannot overlap.
+  if (First.Expression->getType()->getPointeeType().getAddressSpace() !=
+  Second.Expression->getType()->getPointeeType().getAddressSpace())
+return state;
+
   // Get the buffer values and make sure they're known locations.
   const LocationContext *LCtx = C.getLocationContext();
   SVal firstVal = state->getSVal(First.Expression, LCtx);

diff  --git a/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp 
b/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
index 0bd47ced15a51..65c2564637c18 100644
--- a/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ b/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -715,11 +715,41 @@ static SVal evalBinOpFieldRegionFieldRegion(const 
FieldRegion *LeftFR,
   llvm_unreachable("Fields not found in parent record's definition");
 }
 
+// This is used in debug builds only for now because some downstream users
+// may hit this assert in their subsequent merges.
+// There are still places in the analyzer where equal bitwidth Locs
+// are compared, and need to be found and corrected. Recent previous fixes have
+// addressed the known problems of making NULLs with specific bitwidths
+// for Loc comparisons along with deprecation of APIs for the same purpose.
+//
+static void assertEqualBitWidths(ProgramStateRef State, Loc RhsLoc,
+ Loc LhsLoc) {
+  // Implements a "best effort" check for RhsLoc and LhsLoc bit widths
+  ASTContext &Ctx = State->getStateManager().getContext();
+  uint64_t RhsBitwidth =
+  RhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(RhsLoc.getType(Ctx));
+  uint64_t LhsBitwidth =
+  LhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(LhsLoc.getType(Ctx));
+  if (RhsBitwidth && LhsBitwidth &&
+  (LhsLoc.getSubKind() == RhsLoc.getSubKind())) {
+assert(RhsBitwidth == LhsBitwidth &&
+   "RhsLoc and LhsLoc bitwidth must be same!");
+  }
+}
+
 // FIXME: all this logic will change if/when we have MemRegion::getLocation().
 SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
   BinaryOperator::Opcode op,
   Loc lhs, Loc rhs,
   QualType resultTy) {
+
+  // Assert that bitwidth of lhs and rhs are the same.
+  // This can happen if two 
diff erent address spaces are used,
+  // and the bitwidths of the address spaces are 
diff erent.
+  // See LIT case clang/test/Analysis/cstring-checker-addressspace.c
+  // FIXME: See comment above in the function assertEqualBitWidths
+  assertEqualBitWidths(state, rhs, lhs);
+
   // Only comparisons and subtractions are valid operations on two pointers.
   // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
   // However, if a poin

[clang] 83bde93 - resolve typo in the manual.

2022-03-31 Thread via cfe-commits

Author: Shivam
Date: 2022-04-01T03:15:17+05:30
New Revision: 83bde93cef369f85ea0adc25a4cf2349ea65bb3a

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

LOG: resolve typo in the manual.

Added: 


Modified: 
clang/www/analyzer/checker_dev_manual.html

Removed: 




diff  --git a/clang/www/analyzer/checker_dev_manual.html 
b/clang/www/analyzer/checker_dev_manual.html
index 7b63efefe11a9..20b4f41765a84 100644
--- a/clang/www/analyzer/checker_dev_manual.html
+++ b/clang/www/analyzer/checker_dev_manual.html
@@ -814,7 +814,7 @@ Additional Sources of 
Information
 https://llvm.org/doxygen";>LLVM doxygen, when dealing with classes
 from LLVM.
 
-  The https://discourse.llvm.org/c/clang/";> Clang Frontent Discourse 
site.
+  The https://discourse.llvm.org/c/clang/";> Clang Frontend Discourse 
site.
   This is the primary forum discussing ideas and posting questions about Clang 
development.
   For posting Clang Static Analyzer specific questions, please visit the
   https://discourse.llvm.org/c/clang/static-analyzer/";> Static 
Analyzer subcategory



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


[clang-tools-extra] f547fc8 - [clang-tidy] Add modernize-macro-to-enum check

2022-04-01 Thread via cfe-commits

Author: Richard
Date: 2022-04-01T15:24:21-06:00
New Revision: f547fc89c0730e0fee220d790957791bdfd23fcd

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

LOG: [clang-tidy] Add modernize-macro-to-enum check

[buildbot issues fixed]

This check performs basic analysis of macros and replaces them
with an anonymous unscoped enum.  Using an unscoped anonymous enum
ensures that everywhere the macro token was used previously, the
enumerator name may be safely used.

Potential macros for replacement must meet the following constraints:
- Macros must expand only to integral literal tokens.  The unary
  operators plus, minus and tilde are recognized to allow for positive,
  negative and bitwise negated integers.
- Macros must be defined on sequential source file lines, or with
  only comment lines in between macro definitions.
- Macros must all be defined in the same source file.
- Macros must not be defined within a conditional compilation block.
- Macros must not be defined adjacent to other preprocessor directives.
- Macros must not be used in preprocessor conditions

Each cluster of macros meeting the above constraints is presumed to
be a set of values suitable for replacement by an anonymous enum.
>From there, a developer can give the anonymous enum a name and
continue refactoring to a scoped enum if desired.  Comments on the
same line as a macro definition or between subsequent macro definitions
are preserved in the output.  No formatting is assumed in the provided
replacements.

The check cppcoreguidelines-macro-to-enum is an alias for this check.

Fixes #27408

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

Added: 
clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.h
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines-macro-to-enum.rst
clang-tools-extra/docs/clang-tidy/checks/modernize-macro-to-enum.rst

clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-macro-to-enum/modernize-macro-to-enum.h

clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-macro-to-enum/modernize-macro-to-enum2.h

clang-tools-extra/test/clang-tidy/checkers/Inputs/modernize-macro-to-enum/modernize-macro-to-enum3.h
clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp

Modified: 
clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/list.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 147c2741d59e4..6bf20552e0182 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -11,6 +11,7 @@ add_clang_library(clangTidyModernizeModule
   DeprecatedIosBaseAliasesCheck.cpp
   LoopConvertCheck.cpp
   LoopConvertUtils.cpp
+  MacroToEnumCheck.cpp
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp

diff  --git a/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
new file mode 100644
index 0..e6115af77bd5e
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
@@ -0,0 +1,489 @@
+//===--- MacroToEnumCheck.cpp - clang-tidy 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "MacroToEnumCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+#include "llvm/ADT/STLExtras.h"
+#include 
+#include 
+#include 
+#include 
+
+namespace clang {
+namespace tidy {
+namespace modernize {
+
+static bool hasOnlyComments(SourceLocation Loc, const LangOptions &Options,
+StringRef Text) {
+  // Use a lexer to look for tokens; if we find something other than a single
+  // hash, then there were intervening tokens between macro definitions.
+  std::string Buffer{Text};
+  Lexer Lex(Loc, Options, Buffer.c_str(), Buffer.c_str(),
+Buffer.c_str() + Buffer.size());
+  Token Tok;
+  bool SeenHash = false;
+  while (!Lex.LexFromRawLexer(Tok)) {
+if (Tok.getKind() == tok::hash && !SeenHash) {
+  SeenHash = true;
+  continue;
+}
+return false;
+  }
+
+  // Everything in between was whitespace, so now just look for two blank 
lines,
+  // consis

[clang] 979d876 - [X86][AMX] enable amx cast intrinsics in FE.

2022-04-01 Thread via cfe-commits

Author: Luo, Yuanke
Date: 2022-04-02T14:02:35+08:00
New Revision: 979d876bb4e93db1be50360a4941b83319d4e114

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

LOG: [X86][AMX] enable amx cast intrinsics in FE.

We have some discission in D99152 and llvm-dev and finially come up with
a solution to add amx specific cast intrinsics. We've support the
intrinsics in llvm IR. This patch is to replace bitcast with amx cast
intrinsics in code emitting in FE.

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

Added: 


Modified: 
clang/lib/CodeGen/CGBuiltin.cpp
clang/test/CodeGen/X86/amx_api.c

Removed: 




diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index ffba93846958e..8ca4b2d0bf15d 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -5411,7 +5411,13 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 
 assert(PTy->canLosslesslyBitCastTo(FTy->getParamType(i)) &&
"Must be able to losslessly bit cast to param");
-ArgValue = Builder.CreateBitCast(ArgValue, PTy);
+// Cast vector type (e.g., v256i32) to x86_amx, this only happen
+// in amx intrinsics.
+if (PTy->isX86_AMXTy())
+  ArgValue = 
Builder.CreateIntrinsic(Intrinsic::x86_cast_vector_to_tile,
+ {ArgValue->getType()}, 
{ArgValue});
+else
+  ArgValue = Builder.CreateBitCast(ArgValue, PTy);
   }
 
   Args.push_back(ArgValue);
@@ -5435,7 +5441,13 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 
   assert(V->getType()->canLosslesslyBitCastTo(RetTy) &&
  "Must be able to losslessly bit cast result type");
-  V = Builder.CreateBitCast(V, RetTy);
+  // Cast x86_amx to vector type (e.g., v256i32), this only happen
+  // in amx intrinsics.
+  if (V->getType()->isX86_AMXTy())
+V = Builder.CreateIntrinsic(Intrinsic::x86_cast_tile_to_vector, 
{RetTy},
+{V});
+  else
+V = Builder.CreateBitCast(V, RetTy);
 }
 
 return RValue::get(V);

diff  --git a/clang/test/CodeGen/X86/amx_api.c 
b/clang/test/CodeGen/X86/amx_api.c
index fda6d6e8ee4f2..e5927f189fb78 100644
--- a/clang/test/CodeGen/X86/amx_api.c
+++ b/clang/test/CodeGen/X86/amx_api.c
@@ -11,9 +11,11 @@ char buf2[1024];
 // This is an example code and integration test.
 void test_api(int cond, short row, short col) {
   //CHECK-LABEL: @test_api
-  //CHECK: call x86_amx @llvm.x86.tileloadd64.internal
-  //CHECK: call x86_amx @llvm.x86.tdpbssd.internal
-  //CHECK: call void @llvm.x86.tilestored64.internal
+  //CHECK-DAG: call x86_amx @llvm.x86.tileloadd64.internal
+  //CHECK-DAG: call <256 x i32> @llvm.x86.cast.tile.to.vector.v256i32(x86_amx 
{{%.*}})
+  //CHECK-DAG: call x86_amx @llvm.x86.cast.vector.to.tile.v256i32(<256 x i32> 
{{%.*}})
+  //CHECK-DAG: call x86_amx @llvm.x86.tdpbssd.internal
+  //CHECK-DAG: call void @llvm.x86.tilestored64.internal
   __tile1024i a = {row, 8};
   __tile1024i b = {8, col};
   __tile1024i c = {row, col};
@@ -33,65 +35,70 @@ void test_api(int cond, short row, short col) {
 
 void test_tile_loadd(short row, short col) {
   //CHECK-LABEL: @test_tile_loadd
-  //CHECK: call x86_amx @llvm.x86.tileloadd64.internal
-  //CHECK-NEXT: {{%.*}} = bitcast x86_amx {{%.*}} to <256 x i32>
+  //CHECK-DAG: call x86_amx @llvm.x86.tileloadd64.internal
+  //CHECK-DAG: call <256 x i32> @llvm.x86.cast.tile.to.vector.v256i32(x86_amx 
{{%.*}})
   __tile1024i a = {row, col};
   __tile_loadd(&a, buf, STRIDE);
 }
 
 void test_tile_stream_loadd(short row, short col) {
   //CHECK-LABEL: @test_tile_stream_loadd
-  //CHECK: call x86_amx @llvm.x86.tileloaddt164.internal
-  //CHECK-NEXT: {{%.*}} = bitcast x86_amx {{%.*}} to <256 x i32>
+  //CHECK-DAG: call x86_amx @llvm.x86.tileloaddt164.internal
+  //CHECK-DAG: call <256 x i32> @llvm.x86.cast.tile.to.vector.v256i32(x86_amx 
{{%.*}})
   __tile1024i a = {row, col};
   __tile_stream_loadd(&a, buf, STRIDE);
 }
 
 void test_tile_dpbssd(__tile1024i a, __tile1024i b, __tile1024i c) {
   //CHECK-LABEL: @test_tile_dpbssd
-  //CHECK: call x86_amx @llvm.x86.tdpbssd.internal
-  //CHECK-NEXT: {{%.*}} = bitcast x86_amx {{%.*}} to <256 x i32>
+  //CHECK-DAG: call x86_amx @llvm.x86.cast.vector.to.tile.v256i32(<256 x i32> 
{{%.*}})
+  //CHECK-DAG: call x86_amx @llvm.x86.tdpbssd.internal
+  //CHECK-DAG: call <256 x i32> @llvm.x86.cast.tile.to.vector.v256i32(x86_amx 
{{%.*}})
   __tile_dpbssd(&c, a, b);
 }
 
 void test_tile_dpbsud(__tile1024i a, __tile1024i b, __tile1024i c) {
   //CHECK-LABEL: @test_tile_dpbsud
-  //CHECK: call x86_amx @llvm.x86.tdpbsud.internal
-  //CHECK-NEXT: {{%.*}} = bitcast

[clang] b93893e - [AArch64] Default HBC/MOPS features in clang

2022-04-02 Thread via cfe-commits

Author: tyb0807
Date: 2022-04-02T14:51:23+01:00
New Revision: b93893e60f0c860e5814cea6cc285c8e89e035af

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

LOG: [AArch64] Default HBC/MOPS features in clang

This implements minimum support in clang for default HBC/MOPS features
on v8.8-a/v9.3-a or later architectures.

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

Added: 


Modified: 
clang/lib/Basic/Targets/AArch64.cpp
clang/lib/Driver/ToolChains/Arch/AArch64.cpp
clang/test/Driver/aarch64-hbc.c
clang/test/Driver/aarch64-mops.c
clang/test/Preprocessor/aarch64-target-features.c

Removed: 




diff  --git a/clang/lib/Basic/Targets/AArch64.cpp 
b/clang/lib/Basic/Targets/AArch64.cpp
index 964cf5c824140..f4aecd3675b1d 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -226,8 +226,6 @@ void AArch64TargetInfo::getTargetDefinesARMV87A(const 
LangOptions &Opts,
 
 void AArch64TargetInfo::getTargetDefinesARMV88A(const LangOptions &Opts,
 MacroBuilder &Builder) const {
-  // FIXME: this does not handle the case where MOPS is disabled using +nomops
-  Builder.defineMacro("__ARM_FEATURE_MOPS", "1");
   // Also include the Armv8.7 defines
   getTargetDefinesARMV87A(Opts, Builder);
 }

diff  --git a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp 
b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
index a0be30f881e52..1691b7faf668a 100644
--- a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -461,13 +461,24 @@ void aarch64::getAArch64TargetFeatures(const Driver &D,
 }
   }
 
-  const char *Archs[] = {"+v8.6a", "+v8.7a", "+v8.8a",
- "+v9.1a", "+v9.2a", "+v9.3a"};
-  auto Pos = std::find_first_of(Features.begin(), Features.end(),
-std::begin(Archs), std::end(Archs));
+  // FIXME: these insertions should ideally be automated using default
+  // extensions support from the backend target parser.
+  const char *v8691OrLater[] = {"+v8.6a", "+v8.7a", "+v8.8a",
+"+v9.1a", "+v9.2a", "+v9.3a"};
+  auto Pos =
+  std::find_first_of(Features.begin(), Features.end(),
+ std::begin(v8691OrLater), std::end(v8691OrLater));
   if (Pos != std::end(Features))
 Pos = Features.insert(std::next(Pos), {"+i8mm", "+bf16"});
 
+  // For Armv8.8-a/Armv9.3-a or later, FEAT_HBC and FEAT_MOPS are enabled by
+  // default.
+  const char *v8893OrLater[] = {"+v8.8a", "+v9.3a"};
+  Pos = std::find_first_of(Features.begin(), Features.end(),
+   std::begin(v8893OrLater), std::end(v8893OrLater));
+  if (Pos != std::end(Features))
+Pos = Features.insert(std::next(Pos), {"+hbc", "+mops"});
+
   if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
options::OPT_munaligned_access)) {
 if (A->getOption().matches(options::OPT_mno_unaligned_access))

diff  --git a/clang/test/Driver/aarch64-hbc.c b/clang/test/Driver/aarch64-hbc.c
index 3681542ace471..b25e7c3f52809 100644
--- a/clang/test/Driver/aarch64-hbc.c
+++ b/clang/test/Driver/aarch64-hbc.c
@@ -1,6 +1,12 @@
 // Test that target feature hbc is implemented and available correctly
-// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a+hbc %s 
2>&1 | FileCheck %s
-// CHECK: "-target-feature" "+hbc"
-
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.7-a+hbc   %s 
2>&1 | FileCheck %s
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a   %s 
2>&1 | FileCheck %s
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a+hbc   %s 
2>&1 | FileCheck %s
 // RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a+nohbc %s 
2>&1 | FileCheck %s --check-prefix=NO_HBC
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv9.2-a+hbc   %s 
2>&1 | FileCheck %s
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv9.3-a   %s 
2>&1 | FileCheck %s
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv9.3-a+hbc   %s 
2>&1 | FileCheck %s
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv9.3-a+nohbc %s 
2>&1 | FileCheck %s --check-prefix=NO_HBC
+
+// CHECK: "-target-feature" "+hbc"
 // NO_HBC: "-target-feature" "-hbc"

diff  --git a/clang/test/Driver/aarch64-mops.c 
b/clang/test/Driver/aarch64-mops.c
index 4cd48143033d6..8ce3c21d9ddb3 100644
--- a/clang/test/Driver/aarch64-mops.c
+++ b/clang/test/Driver/aarch64-mops.c
@@ -1,6 +1,12 @@
 // Test that target feature mops is implemented and available correctly
-// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.8-a+mops %s 
2>&1 | FileCheck %s
-// CHECK: "-target-feature" "+mops"
-
+// RUN:

[clang] 9a015ee - [AArch64] Avoid scanning feature list for target parsing

2022-04-02 Thread via cfe-commits

Author: tyb0807
Date: 2022-04-02T14:51:23+01:00
New Revision: 9a015ee1f948755d69dc2ff52e7655229e2eed47

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

LOG: [AArch64] Avoid scanning feature list for target parsing

As discussed in https://reviews.llvm.org/D120111, this patch proposes an
alternative implementation to avoid scanning feature list for
architecture version over and over again. The insertion position for
default extensions is also captured during this single scan of the
feature list.

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/Arch/AArch64.cpp
clang/test/Driver/aarch64-cpus-2.c
clang/test/Preprocessor/aarch64-target-features.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp 
b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
index 1691b7faf668a..d82198ec678bf 100644
--- a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -347,28 +347,85 @@ void aarch64::getAArch64TargetFeatures(const Driver &D,
   Features.push_back("-crc");
   }
 
+  int V8Version = -1;
+  int V9Version = -1;
+  bool HasNoSM4 = false;
+  bool HasNoSHA3 = false;
+  bool HasNoSHA2 = false;
+  bool HasNoAES = false;
+  bool HasSM4 = false;
+  bool HasSHA3 = false;
+  bool HasSHA2 = false;
+  bool HasAES = false;
+  bool HasCrypto = false;
+  bool HasNoCrypto = false;
+  int FullFP16Pos = -1;
+  int NoFullFP16Pos = -1;
+  int FP16FMLPos = -1;
+  int NoFP16FMLPos = -1;
+  int ArchFeatPos = -1;
+
+  for (auto I = Features.begin(), E = Features.end(); I != E; I++) {
+if (*I == "+v8a")   V8Version = 0;
+else if (*I == "+v8.1a") V8Version = 1;
+else if (*I == "+v8.2a") V8Version = 2;
+else if (*I == "+v8.3a") V8Version = 3;
+else if (*I == "+v8.4a") V8Version = 4;
+else if (*I == "+v8.5a") V8Version = 5;
+else if (*I == "+v8.6a") V8Version = 6;
+else if (*I == "+v8.7a") V8Version = 7;
+else if (*I == "+v8.8a") V8Version = 8;
+else if (*I == "+v8.9a") V8Version = 9;
+else if (*I == "+v9a")   V9Version = 0;
+else if (*I == "+v9.1a") V9Version = 1;
+else if (*I == "+v9.2a") V9Version = 2;
+else if (*I == "+v9.3a") V9Version = 3;
+else if (*I == "+v9.4a") V9Version = 4;
+else if (*I == "+sm4")  HasSM4 = true;
+else if (*I == "+sha3") HasSHA3 = true;
+else if (*I == "+sha2") HasSHA2 = true;
+else if (*I == "+aes")  HasAES = true;
+else if (*I == "-sm4")  HasNoSM4 = true;
+else if (*I == "-sha3") HasNoSHA3 = true;
+else if (*I == "-sha2") HasNoSHA2 = true;
+else if (*I == "-aes")  HasNoAES = true;
+else if (*I == "+fp16fml")  FP16FMLPos = I - Features.begin();
+else if (*I == "-fp16fml")  NoFP16FMLPos = I - Features.begin();
+else if (*I == "-fullfp16") NoFullFP16Pos = I - Features.begin();
+else if (*I == "+fullfp16") FullFP16Pos = I - Features.begin();
+// Whichever option comes after (right-most option) will win
+else if (*I == "+crypto") {
+  HasCrypto = true;
+  HasNoCrypto = false;
+} else if (*I == "-crypto") {
+  HasCrypto = false;
+  HasNoCrypto = true;
+}
+// Register the iterator position if this is an architecture feature
+if (ArchFeatPos == -1 && (V8Version != -1 || V9Version != -1))
+  ArchFeatPos = I - Features.begin();
+  }
+
   // Handle (arch-dependent) fp16fml/fullfp16 relationship.
   // FIXME: this fp16fml option handling will be reimplemented after the
   // TargetParser rewrite.
-  const auto ItRNoFullFP16 = std::find(Features.rbegin(), Features.rend(), 
"-fullfp16");
-  const auto ItRFP16FML = std::find(Features.rbegin(), Features.rend(), 
"+fp16fml");
-  if (llvm::is_contained(Features, "+v8.4a")) {
-const auto ItRFullFP16  = std::find(Features.rbegin(), Features.rend(), 
"+fullfp16");
-if (ItRFullFP16 < ItRNoFullFP16 && ItRFullFP16 < ItRFP16FML) {
+  if (V8Version >= 4) {
+// "-fullfp16" "+fullfp16" && "+fp16fml" "+fullfp16" && no "+fullfp16" 
"-fp16fml" = "+fp16fml"
+if (FullFP16Pos > NoFullFP16Pos && FullFP16Pos > FP16FMLPos && FullFP16Pos 
> NoFP16FMLPos)
   // Only entangled feature that can be to the right of this +fullfp16 is 
-fp16fml.
   // Only append the +fp16fml if there is no -fp16fml after the +fullfp16.
-  if (std::find(Features.rbegin(), ItRFullFP16, "-fp16fml") == ItRFullFP16)
-Features.push_back("+fp16fml");
-}
+  Features.push_back("+fp16fml");
 else
   goto fp16_fml_fallthrough;
   } else {
 fp16_fml_fallthrough:
 // In both of these cases, putting the 'other' feature on the end of the 
vector will
 // result in the same effect as placing it immediately after the current 
feature.
-if (ItRNoFullFP16 < ItRFP16FML)

[clang] 357afd9 - [clang-format] Pass return code of git-clang-format by sys.exit()

2022-04-05 Thread via cfe-commits

Author: owenca
Date: 2022-04-05T09:52:01-07:00
New Revision: 357afd952852db0be3f690f8b647bd4b02f38cad

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

LOG: [clang-format] Pass return code of git-clang-format by sys.exit()

Fixes #54758

Added: 


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

Removed: 




diff  --git a/clang/tools/clang-format/git-clang-format 
b/clang/tools/clang-format/git-clang-format
index 7968c43875744..1d6f216240c1c 100755
--- a/clang/tools/clang-format/git-clang-format
+++ b/clang/tools/clang-format/git-clang-format
@@ -628,4 +628,4 @@ def convert_string(bytes_input):
 return str(bytes_input)
 
 if __name__ == '__main__':
-  main()
+  sys.exit(main())



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


[clang-tools-extra] ba7b6f4 - [docs][pp-trace] Remove FileNotFound callback

2022-05-11 Thread via cfe-commits

Author: CHIANG, YU-HSUN (Tommy Chiang, oToToT)
Date: 2022-05-11T18:14:25+08:00
New Revision: ba7b6f46b37b1926552e96bd102b995f6d36de04

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

LOG: [docs][pp-trace] Remove FileNotFound callback

`FileNotFound` preprocessor callback is removed in D119708.
We should also remove it from the documentation.

Reviewed by: jansvoboda11

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

Added: 


Modified: 
clang-tools-extra/docs/pp-trace.rst

Removed: 




diff  --git a/clang-tools-extra/docs/pp-trace.rst 
b/clang-tools-extra/docs/pp-trace.rst
index 20556cdc697e4..84a5ae6ed6c60 100644
--- a/clang-tools-extra/docs/pp-trace.rst
+++ b/clang-tools-extra/docs/pp-trace.rst
@@ -49,7 +49,6 @@ Command Line Options
 
   * FileChanged
   * FileSkipped
-  * FileNotFound
   * InclusionDirective
   * moduleImport
   * EndOfMainFile
@@ -200,26 +199,6 @@ Example:::
 FilenameTok: "filename.h"
 FileType: C_User
 
-`FileNotFound 
`_
 Callback
-^^
-
-FileNotFound is called when an inclusion directive results in a file-not-found 
error.
-
-Argument descriptions:
-
-==   ==   
== 
=
-Argument NameArgument Value SyntaxClang 
C++ Type Description
-==   ==   
== 
=
-FileName "(file)" 
StringRef  The name of the file being included, as written 
in the source code.
-RecoveryPath (path)   
SmallVectorImpl  If this client indicates that it can recover 
from this missing file, the client should set this as an additional header 
search patch.
-==   ==   
== 
=
-
-Example:::
-
-  - Callback: FileNotFound
-FileName: "/path/filename.h"
-RecoveryPath:
-
 `InclusionDirective 
`_
 Callback
 

 



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


[clang] 06a9832 - [ASTMatchers][NFC] Fix name of matcher in docs and add a missing test

2022-05-11 Thread via cfe-commits

Author: Whisperity
Date: 2022-05-11T14:15:53+02:00
New Revision: 06a98328fc7b70756782fafff5ebfbec815cf1f5

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

LOG: [ASTMatchers][NFC] Fix name of matcher in docs and add a missing test

Added: 


Modified: 
clang/docs/LibASTMatchersReference.html
clang/include/clang/ASTMatchers/ASTMatchers.h
clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp

Removed: 




diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index d552f4ccd7668..55c4da639a815 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -1012,7 +1012,7 @@ Node Matchers
 Matches a C++ 
static_assert declaration.
 
 Example:
-  staticAssertExpr()
+  staticAssertDecl()
 matches
   static_assert(sizeof(S) == sizeof(int))
 in

diff  --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index c16bc5f0eafde..221cab03b0ecb 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -2523,7 +2523,7 @@ extern const internal::VariadicDynCastAllOfMatcher
 /// Matches a C++ static_assert declaration.
 ///
 /// Example:
-///   staticAssertExpr()
+///   staticAssertDecl()
 /// matches
 ///   static_assert(sizeof(S) == sizeof(int))
 /// in

diff  --git a/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
index ed222a1fdf877..6723e1657c1ab 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
@@ -735,6 +735,17 @@ TEST_P(ASTMatchersTest, ParmVarDecl) {
   EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
 }
 
+TEST_P(ASTMatchersTest, StaticAssertDecl) {
+  if (!GetParam().isCXX11OrLater())
+return;
+
+  EXPECT_TRUE(matches("static_assert(true, \"\");", staticAssertDecl()));
+  EXPECT_TRUE(
+  notMatches("constexpr bool staticassert(bool B, const char *M) "
+ "{ return true; };\n void f() { staticassert(true, \"\"); }",
+ staticAssertDecl()));
+}
+
 TEST_P(ASTMatchersTest, Matcher_ConstructorCall) {
   if (!GetParam().isCXX()) {
 return;



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


[clang] b6d8c84 - [clang-format] Don't remove braces if a 1-statement body would wrap

2022-05-12 Thread via cfe-commits

Author: owenca
Date: 2022-05-12T03:53:08-07:00
New Revision: b6d8c84f28103104a5707091f970d80df423b6c9

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

LOG: [clang-format] Don't remove braces if a 1-statement body would wrap

Reimplement the RemoveBracesLLVM feature which handles a
single-statement block that would get wrapped.

Fixes #53543.

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index f90e8fcb834c7..6ba8edccbb117 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -14,6 +14,7 @@
 
 #include "UnwrappedLineParser.h"
 #include "FormatToken.h"
+#include "TokenAnnotator.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
@@ -460,6 +461,7 @@ bool UnwrappedLineParser::precededByCommentOrPPDirective() 
const {
   return Previous && Previous->is(tok::comment) &&
  (Previous->IsMultiline || Previous->NewlinesBefore > 0);
 }
+
 /// \brief Parses a level, that is ???.
 /// \param HasOpeningBrace If that level is started by an opening brace.
 /// \param CanContainBracedList If the content can contain (at any level) a
@@ -751,6 +753,50 @@ size_t UnwrappedLineParser::computePPHash() const {
   return h;
 }
 
+// Checks whether \p ParsedLine might fit on a single line. We must clone the
+// tokens of \p ParsedLine before running the token annotator on it so that we
+// can restore them afterward.
+bool UnwrappedLineParser::mightFitOnOneLine(UnwrappedLine &ParsedLine) const {
+  const auto ColumnLimit = Style.ColumnLimit;
+  if (ColumnLimit == 0)
+return true;
+
+  auto &Tokens = ParsedLine.Tokens;
+  assert(!Tokens.empty());
+  const auto *LastToken = Tokens.back().Tok;
+  assert(LastToken);
+
+  SmallVector SavedTokens(Tokens.size());
+
+  int Index = 0;
+  for (const auto &Token : Tokens) {
+assert(Token.Tok);
+auto &SavedToken = SavedTokens[Index++];
+SavedToken.Tok = new FormatToken;
+SavedToken.Tok->copyFrom(*Token.Tok);
+SavedToken.Children = std::move(Token.Children);
+  }
+
+  AnnotatedLine Line(ParsedLine);
+  assert(Line.Last == LastToken);
+
+  TokenAnnotator Annotator(Style, Keywords);
+  Annotator.annotate(Line);
+  Annotator.calculateFormattingInformation(Line);
+
+  const int Length = LastToken->TotalLength;
+
+  Index = 0;
+  for (auto &Token : Tokens) {
+const auto &SavedToken = SavedTokens[Index++];
+Token.Tok->copyFrom(*SavedToken.Tok);
+Token.Children = std::move(SavedToken.Children);
+delete SavedToken.Tok;
+  }
+
+  return Line.Level * Style.IndentWidth + Length <= ColumnLimit;
+}
+
 UnwrappedLineParser::IfStmtKind
 UnwrappedLineParser::parseBlock(bool MustBeDeclaration, unsigned AddLevels,
 bool MunchSemi, bool UnindentWhitesmithsBraces,
@@ -813,8 +859,11 @@ UnwrappedLineParser::parseBlock(bool MustBeDeclaration, 
unsigned AddLevels,
 const FormatToken *Previous = Tokens->getPreviousToken();
 assert(Previous);
 if (Previous->isNot(tok::r_brace) || Previous->Optional) {
-  Tok->MatchingParen = FormatTok;
-  FormatTok->MatchingParen = Tok;
+  assert(!CurrentLines->empty());
+  if (mightFitOnOneLine(CurrentLines->back())) {
+Tok->MatchingParen = FormatTok;
+FormatTok->MatchingParen = Tok;
+  }
 }
   }
 

diff  --git a/clang/lib/Format/UnwrappedLineParser.h 
b/clang/lib/Format/UnwrappedLineParser.h
index 3334b5bad97b4..aea999586ebe3 100644
--- a/clang/lib/Format/UnwrappedLineParser.h
+++ b/clang/lib/Format/UnwrappedLineParser.h
@@ -95,6 +95,7 @@ class UnwrappedLineParser {
   bool parseLevel(bool HasOpeningBrace, bool CanContainBracedList,
   IfStmtKind *IfKind = nullptr,
   TokenType NextLBracesType = TT_Unknown);
+  bool mightFitOnOneLine(UnwrappedLine &Line) const;
   IfStmtKind parseBlock(bool MustBeDeclaration = false, unsigned AddLevels = 
1u,
 bool MunchSemi = true,
 bool UnindentWhitesmithsBraces = false,

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 8f9c7215d6193..2a764b68b9129 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -25365,8 +25365,6 @@ TEST_F(FormatTest, RemoveBraces) {
"}",
Style);
 
-  // FIXME: See https://github.com/llvm/llvm-project/issues/53543.
-#if 0
   Style.ColumnLimit = 65;
 
   verifyFormat("if (condition) {\n"
@@ -25380

[clang] 6cd9633 - [clang-format] Handle comments below r_brace in RemoveBracesLLVM

2022-05-12 Thread via cfe-commits

Author: owenca
Date: 2022-05-12T16:51:18-07:00
New Revision: 6cd9633c1da5d2867306217af59bcc4b589bab02

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

LOG: [clang-format] Handle comments below r_brace in RemoveBracesLLVM

If a closing brace is followed by a non-trailing comment, the
newline before the closing brace must also be removed.

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index afa87a8bafe31..10945f455120e 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1898,8 +1898,9 @@ class BracesRemover : public TokenAnalyzer {
 assert(Token->isOneOf(tok::l_brace, tok::r_brace));
 assert(Token->Next || Token == Line->Last);
 const auto Start =
-Token == Line->Last || (Token->Next->is(tok::kw_else) &&
-Token->Next->NewlinesBefore > 0)
+Token == Line->Last ||
+(Token->Next->isOneOf(tok::kw_else, tok::comment) &&
+ Token->Next->NewlinesBefore > 0)
 ? Token->WhitespaceRange.getBegin()
 : Token->Tok.getLocation();
 const auto Range =

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 2a764b68b9129..8ac59dc4a5131 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -25348,6 +25348,20 @@ TEST_F(FormatTest, RemoveBraces) {
"}",
Style);
 
+  verifyFormat("if (a)\n"
+   "  foo();\n"
+   "// comment\n"
+   "else\n"
+   "  bar();",
+   "if (a) {\n"
+   "  foo();\n"
+   "}\n"
+   "// comment\n"
+   "else {\n"
+   "  bar();\n"
+   "}",
+   Style);
+
   verifyFormat("if (a) {\n"
"Label:\n"
"}",



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


[clang-tools-extra] 9add949 - [ASTMatchers][clang-tidy][NFC] Hoist `forEachTemplateArgument` matcher into the core library

2022-05-13 Thread via cfe-commits

Author: Whisperity
Date: 2022-05-13T12:55:48+02:00
New Revision: 9add949557d2cf603b8f541f0dbb83a8fa035d17

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

LOG: [ASTMatchers][clang-tidy][NFC] Hoist `forEachTemplateArgument` matcher 
into the core library

Fixes the `FIXME:` related to adding `forEachTemplateArgument` to the
core AST Matchers library.

Reviewed By: aaron.ballman

Differential Revision: http://reviews.llvm.org/D125383

Added: 


Modified: 
clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
clang/docs/LibASTMatchersReference.html
clang/docs/ReleaseNotes.rst
clang/include/clang/ASTMatchers/ASTMatchers.h
clang/lib/ASTMatchers/Dynamic/Registry.cpp
clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp 
b/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
index 9265504a7651..1ee757296d93 100644
--- a/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
@@ -18,26 +18,6 @@ namespace tidy {
 namespace misc {
 
 namespace {
-// FIXME: Move ASTMatcher library.
-AST_POLYMORPHIC_MATCHER_P(
-forEachTemplateArgument,
-AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
-TemplateSpecializationType, FunctionDecl),
-clang::ast_matchers::internal::Matcher, InnerMatcher) {
-  ArrayRef TemplateArgs =
-  clang::ast_matchers::internal::getTemplateSpecializationArgs(Node);
-  clang::ast_matchers::internal::BoundNodesTreeBuilder Result;
-  bool Matched = false;
-  for (const auto &Arg : TemplateArgs) {
-clang::ast_matchers::internal::BoundNodesTreeBuilder ArgBuilder(*Builder);
-if (InnerMatcher.matches(Arg, Finder, &ArgBuilder)) {
-  Matched = true;
-  Result.addMatch(ArgBuilder);
-}
-  }
-  *Builder = std::move(Result);
-  return Matched;
-}
 
 AST_MATCHER_P(DeducedTemplateSpecializationType, refsToTemplatedDecl,
   clang::ast_matchers::internal::Matcher, DeclMatcher) {

diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index 55c4da639a81..b6dcf26e 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -7391,6 +7391,32 @@ AST Traversal Matchers
 
 
 
+MatcherClassTemplateSpecializationDecl>forEachTemplateArgumentMatcherTemplateArgument>
 InnerMatcher
+Matches 
classTemplateSpecialization, templateSpecializationType and functionDecl nodes 
where the template argument matches the inner matcher.
+This matcher may produce multiple matches.
+
+Given
+  template 
+  struct Matrix {};
+
+  constexpr unsigned R = 2;
+  Matrix M;
+
+  template 
+  void f(T&& t, U&& u) {}
+
+  bool B = false;
+  f(R, B);
+
+templateSpecializationType(forEachTemplateArgument(isExpr(expr(
+  matches twice, with expr() matching 'R * 2' and 'R * 4'
+
+functionDecl(forEachTemplateArgument(refersToType(builtinType(
+  matches the specialization f twice, for 'unsigned'
+  and 'bool'
+
+
+
 MatcherClassTemplateSpecializationDecl>hasAnyTemplateArgumentMatcherTemplateArgument>
 InnerMatcher
 Matches 
classTemplateSpecializations, templateSpecializationType and
 functionDecl that have at least one TemplateArgument matching the given
@@ -8181,6 +8207,32 @@ AST Traversal Matchers
 
 
 
+MatcherFunctionDecl>forEachTemplateArgumentMatcherTemplateArgument>
 InnerMatcher
+Matches 
classTemplateSpecialization, templateSpecializationType and functionDecl nodes 
where the template argument matches the inner matcher.
+This matcher may produce multiple matches.
+
+Given
+  template 
+  struct Matrix {};
+
+  constexpr unsigned R = 2;
+  Matrix M;
+
+  template 
+  void f(T&& t, U&& u) {}
+
+  bool B = false;
+  f(R, B);
+
+templateSpecializationType(forEachTemplateArgument(isExpr(expr(
+  matches twice, with expr() matching 'R * 2' and 'R * 4'
+
+functionDecl(forEachTemplateArgument(refersToType(builtinType(
+  matches the specialization f twice, for 'unsigned'
+  and 'bool'
+
+
+
 Matcher

[clang] 2601355 - [clang-format][NFC] Format unit tests with insert/remove braces

2022-05-13 Thread via cfe-commits

Author: owenca
Date: 2022-05-13T16:16:20-07:00
New Revision: 2601355dc9822f8e04ad73212ed62e601e4f0368

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

LOG: [clang-format][NFC] Format unit tests with insert/remove braces

This patch is the result of running clang-format version 753fe33 in
clang/unittests/Format/:
clang-format -style="{InsertBraces: true, RemoveBracesLLVM: true}" -i *.cpp *.h

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

Added: 


Modified: 
clang/unittests/Format/FormatTestUtils.h
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTestUtils.h 
b/clang/unittests/Format/FormatTestUtils.h
index fb75070db1cd..ace5a4519d20 100644
--- a/clang/unittests/Format/FormatTestUtils.h
+++ b/clang/unittests/Format/FormatTestUtils.h
@@ -53,10 +53,9 @@ inline std::string messUp(llvm::StringRef Code) {
   std::string WithoutWhitespace;
   if (MessedUp[0] != ' ')
 WithoutWhitespace.push_back(MessedUp[0]);
-  for (unsigned i = 1, e = MessedUp.size(); i != e; ++i) {
+  for (unsigned i = 1, e = MessedUp.size(); i != e; ++i)
 if (MessedUp[i] != ' ' || MessedUp[i - 1] != ' ')
   WithoutWhitespace.push_back(MessedUp[i]);
-  }
   return WithoutWhitespace;
 }
 

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 138cab9b6b25..aa91f389a5d2 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -509,13 +509,15 @@ TEST_F(TokenAnnotatorTest, 
RequiresDoesNotChangeParsingOfTheRest) {
 NumberOfBaseTokens + NumberOfAdditionalRequiresClauseTokens)
   << ConstrainedTokens;
 
-  for (auto I = 0u; I < NumberOfBaseTokens; ++I)
-if (I < NumberOfTokensBeforeRequires)
+  for (auto I = 0u; I < NumberOfBaseTokens; ++I) {
+if (I < NumberOfTokensBeforeRequires) {
   EXPECT_EQ(*BaseTokens[I], *ConstrainedTokens[I]) << I;
-else
+} else {
   EXPECT_EQ(*BaseTokens[I],
 *ConstrainedTokens[I + NumberOfAdditionalRequiresClauseTokens])
   << I;
+}
+  }
 
   BaseTokens = annotate("template\n"
 "struct Bar;");
@@ -529,13 +531,15 @@ TEST_F(TokenAnnotatorTest, 
RequiresDoesNotChangeParsingOfTheRest) {
 NumberOfBaseTokens + NumberOfAdditionalRequiresClauseTokens)
   << ConstrainedTokens;
 
-  for (auto I = 0u; I < NumberOfBaseTokens; ++I)
-if (I < NumberOfTokensBeforeRequires)
+  for (auto I = 0u; I < NumberOfBaseTokens; ++I) {
+if (I < NumberOfTokensBeforeRequires) {
   EXPECT_EQ(*BaseTokens[I], *ConstrainedTokens[I]) << I;
-else
+} else {
   EXPECT_EQ(*BaseTokens[I],
 *ConstrainedTokens[I + NumberOfAdditionalRequiresClauseTokens])
   << I;
+}
+  }
 
   BaseTokens = annotate("template\n"
 "struct Bar {"
@@ -555,13 +559,15 @@ TEST_F(TokenAnnotatorTest, 
RequiresDoesNotChangeParsingOfTheRest) {
 NumberOfBaseTokens + NumberOfAdditionalRequiresClauseTokens)
   << ConstrainedTokens;
 
-  for (auto I = 0u; I < NumberOfBaseTokens; ++I)
-if (I < NumberOfTokensBeforeRequires)
+  for (auto I = 0u; I < NumberOfBaseTokens; ++I) {
+if (I < NumberOfTokensBeforeRequires) {
   EXPECT_EQ(*BaseTokens[I], *ConstrainedTokens[I]) << I;
-else
+} else {
   EXPECT_EQ(*BaseTokens[I],
 *ConstrainedTokens[I + NumberOfAdditionalRequiresClauseTokens])
   << I;
+}
+  }
 
   BaseTokens = annotate("template\n"
 "Bar(T) -> Bar;");
@@ -575,13 +581,15 @@ TEST_F(TokenAnnotatorTest, 
RequiresDoesNotChangeParsingOfTheRest) {
 NumberOfBaseTokens + NumberOfAdditionalRequiresClauseTokens)
   << ConstrainedTokens;
 
-  for (auto I = 0u; I < NumberOfBaseTokens; ++I)
-if (I < NumberOfTokensBeforeRequires)
+  for (auto I = 0u; I < NumberOfBaseTokens; ++I) {
+if (I < NumberOfTokensBeforeRequires) {
   EXPECT_EQ(*BaseTokens[I], *ConstrainedTokens[I]) << I;
-else
+} else {
   EXPECT_EQ(*BaseTokens[I],
 *ConstrainedTokens[I + NumberOfAdditionalRequiresClauseTokens])
   << I;
+}
+  }
 
   BaseTokens = annotate("template\n"
 "T foo();");
@@ -595,13 +603,15 @@ TEST_F(TokenAnnotatorTest, 
RequiresDoesNotChangeParsingOfTheRest) {
 NumberOfBaseTokens + NumberOfAdditionalRequiresClauseTokens)
   << ConstrainedTokens;
 
-  for (auto I = 0u; I < NumberOfBaseTokens; ++I)
-if (I < NumberOfTokensBeforeRequires)
+  for (auto I = 0u; I < NumberOfBaseTokens; ++I) {
+if (I < NumberOfTokensBeforeRequires) {
   EXPECT_EQ(*BaseTokens[I], *ConstrainedTokens[I]) << I;
-else
+} else {
  

[clang-tools-extra] 5122738 - [clang-tidy] Support expressions of literals in modernize-macro-to-enum

2022-05-13 Thread via cfe-commits

Author: Richard
Date: 2022-05-13T18:45:54-06:00
New Revision: 5122738331362b574baf0a5a17311cddd52a253e

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

LOG: [clang-tidy] Support expressions of literals in modernize-macro-to-enum

Add a recursive descent parser to match macro expansion tokens against
fully formed valid expressions of integral literals.  Partial
expressions will not be matched -- they can't be valid initializing
expressions for an enum.

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

Fixes #55055

Added: 
clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp
clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.h
clang-tools-extra/unittests/clang-tidy/ModernizeModuleTest.cpp

Modified: 
clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
clang-tools-extra/docs/clang-tidy/checks/modernize-macro-to-enum.rst
clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
clang-tools-extra/unittests/clang-tidy/CMakeLists.txt

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 6bf20552e0182..9d13001037b8e 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -9,6 +9,7 @@ add_clang_library(clangTidyModernizeModule
   ConcatNestedNamespacesCheck.cpp
   DeprecatedHeadersCheck.cpp
   DeprecatedIosBaseAliasesCheck.cpp
+  IntegralLiteralExpressionMatcher.cpp
   LoopConvertCheck.cpp
   LoopConvertUtils.cpp
   MacroToEnumCheck.cpp

diff  --git 
a/clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp 
b/clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp
new file mode 100644
index 0..91a10f8956e62
--- /dev/null
+++ 
b/clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp
@@ -0,0 +1,232 @@
+//===--- IntegralLiteralExpressionMatcher.cpp - clang-tidy 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "IntegralLiteralExpressionMatcher.h"
+
+#include 
+#include 
+
+namespace clang {
+namespace tidy {
+namespace modernize {
+
+// Validate that this literal token is a valid integer literal.  A literal 
token
+// could be a floating-point token, which isn't acceptable as a value for an
+// enumeration.  A floating-point token must either have a decimal point or an
+// exponent ('E' or 'P').
+static bool isIntegralConstant(const Token &Token) {
+  const char *Begin = Token.getLiteralData();
+  const char *End = Begin + Token.getLength();
+
+  // Not a hexadecimal floating-point literal.
+  if (Token.getLength() > 2 && Begin[0] == '0' && std::toupper(Begin[1]) == 
'X')
+return std::none_of(Begin + 2, End, [](char C) {
+  return C == '.' || std::toupper(C) == 'P';
+});
+
+  // Not a decimal floating-point literal or complex literal.
+  return std::none_of(Begin, End, [](char C) {
+return C == '.' || std::toupper(C) == 'E' || std::toupper(C) == 'I';
+  });
+}
+
+bool IntegralLiteralExpressionMatcher::advance() {
+  ++Current;
+  return Current != End;
+}
+
+bool IntegralLiteralExpressionMatcher::consume(tok::TokenKind Kind) {
+  if (Current->is(Kind)) {
+++Current;
+return true;
+  }
+
+  return false;
+}
+
+bool IntegralLiteralExpressionMatcher::nonTerminalChainedExpr(
+bool (IntegralLiteralExpressionMatcher::*NonTerminal)(),
+const std::function &IsKind) {
+  if (!(this->*NonTerminal)())
+return false;
+  if (Current == End)
+return true;
+
+  while (Current != End) {
+if (!IsKind(*Current))
+  break;
+
+if (!advance())
+  return false;
+
+if (!(this->*NonTerminal)())
+  return false;
+  }
+
+  return true;
+}
+
+// Advance over unary operators.
+bool IntegralLiteralExpressionMatcher::unaryOperator() {
+  if (Current->isOneOf(tok::TokenKind::minus, tok::TokenKind::plus,
+   tok::TokenKind::tilde, tok::TokenKind::exclaim)) {
+return advance();
+  }
+
+  return true;
+}
+
+bool IntegralLiteralExpressionMatcher::unaryExpr() {
+  if (!unaryOperator())
+return false;
+
+  if (consume(tok::TokenKind::l_paren)) {
+if (Current == End)
+  return false;
+
+if (!expr())
+  return false;
+
+if (Current == End)
+  return false;
+
+return consume(tok::TokenKind::r_paren);
+  }
+
+  if (!Current->isLiteral() || isStringLite

[clang-tools-extra] 9d99cf5 - [clang-tidy] Restore test parameter operator<< function (NFC)

2022-05-14 Thread via cfe-commits

Author: Richard
Date: 2022-05-14T14:04:32-06:00
New Revision: 9d99cf59a151a715ebebf3a4c4782dfdb48d7f4b

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

LOG: [clang-tidy] Restore test parameter operator<< function (NFC)

Clang erroneously flagged the function as "unused", but it is most
definitely used by gtest to pretty print the parameter value when
a test fails.

Make the pretty printing function a friend function in the parameter
class similar to other clang unit tests.

Added: 


Modified: 
clang-tools-extra/unittests/clang-tidy/ModernizeModuleTest.cpp

Removed: 




diff  --git a/clang-tools-extra/unittests/clang-tidy/ModernizeModuleTest.cpp 
b/clang-tools-extra/unittests/clang-tidy/ModernizeModuleTest.cpp
index 65bf0691372cc..b772c0054de40 100644
--- a/clang-tools-extra/unittests/clang-tidy/ModernizeModuleTest.cpp
+++ b/clang-tools-extra/unittests/clang-tidy/ModernizeModuleTest.cpp
@@ -48,6 +48,11 @@ namespace {
 struct Param {
   bool Matched;
   const char *Text;
+
+  friend std::ostream &operator<<(std::ostream &Str, const Param &Value) {
+return Str << "Matched: " << std::boolalpha << Value.Matched << ", Text: '"
+   << Value.Text << "'";
+  }
 };
 
 class MatcherTest : public ::testing::TestWithParam {};



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


[clang] 2cdabc0 - [clang-format] Handle "if consteval { ... }" for RemoveBracesLLVM

2022-05-15 Thread via cfe-commits

Author: owenca
Date: 2022-05-15T01:33:44-07:00
New Revision: 2cdabc0322929a3954b63c1f29f23959e2e50278

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

LOG: [clang-format] Handle "if consteval { ... }" for RemoveBracesLLVM

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

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 6ba8edccbb117..c5135222af698 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2473,7 +2473,12 @@ FormatToken 
*UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
   nextToken();
   if (FormatTok->is(tok::exclaim))
 nextToken();
+
+  bool KeepIfBraces = false;
+  bool KeepElseBraces = false;
   if (FormatTok->is(tok::kw_consteval)) {
+KeepIfBraces = true;
+KeepElseBraces = true;
 nextToken();
   } else {
 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
@@ -2501,10 +2506,10 @@ FormatToken 
*UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
 parseUnbracedBody();
   }
 
-  bool KeepIfBraces = false;
   if (Style.RemoveBracesLLVM) {
 assert(!NestedTooDeep.empty());
-KeepIfBraces = (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
+KeepIfBraces = KeepIfBraces ||
+   (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
IfBlockKind == IfStmtKind::IfElseIf;
   }
@@ -2558,8 +2563,9 @@ FormatToken 
*UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
 return nullptr;
 
   assert(!NestedTooDeep.empty());
-  const bool KeepElseBraces =
-  (ElseLeftBrace && !ElseLeftBrace->MatchingParen) || NestedTooDeep.back();
+  KeepElseBraces = KeepElseBraces ||
+   (ElseLeftBrace && !ElseLeftBrace->MatchingParen) ||
+   NestedTooDeep.back();
 
   NestedTooDeep.pop_back();
 

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 8ac59dc4a5131..e4fea9085b574 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -25379,6 +25379,25 @@ TEST_F(FormatTest, RemoveBraces) {
"}",
Style);
 
+  verifyFormat("if consteval {\n"
+   "  f();\n"
+   "} else {\n"
+   "  g();\n"
+   "}",
+   Style);
+
+  verifyFormat("if not consteval {\n"
+   "  f();\n"
+   "} else if (a) {\n"
+   "  g();\n"
+   "}",
+   Style);
+
+  verifyFormat("if !consteval {\n"
+   "  g();\n"
+   "}",
+   Style);
+
   Style.ColumnLimit = 65;
 
   verifyFormat("if (condition) {\n"



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


[clang] 924acb6 - [clang] Prevent folding of non-const compound expr

2022-05-15 Thread via cfe-commits

Author: serge-sans-paille
Date: 2022-05-16T07:50:39+02:00
New Revision: 924acb624f58030652ecc8c07db313fde0f31395

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

LOG: [clang] Prevent folding of non-const compound expr

When a non-const compound statement is used to initialize a constexpr pointer,
the pointed value is not const itself and cannot be folded at codegen time.

This matches GCC behavior for compound literal expr arrays.

Fix issue #39324.

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

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/test/SemaCXX/constant-expression-cxx11.cpp
clang/test/SemaTemplate/constexpr-instantiate.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 650ba305c48b1..519be84a342b3 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -4259,9 +4259,33 @@ handleLValueToRValueConversion(EvalInfo &Info, const 
Expr *Conv, QualType Type,
 Info.FFDiag(Conv);
 return false;
   }
+
   APValue Lit;
   if (!Evaluate(Lit, Info, CLE->getInitializer()))
 return false;
+
+  // According to GCC info page:
+  //
+  // 6.28 Compound Literals
+  //
+  // As an optimization, G++ sometimes gives array compound literals longer
+  // lifetimes: when the array either appears outside a function or has a
+  // const-qualified type. If foo and its initializer had elements of type
+  // char *const rather than char *, or if foo were a global variable, the
+  // array would have static storage duration. But it is probably safest
+  // just to avoid the use of array compound literals in C++ code.
+  //
+  // Obey that rule by checking constness for converted array types.
+
+  QualType CLETy = CLE->getType();
+  if (CLETy->isArrayType() && !Type->isArrayType()) {
+if (!CLETy.isConstant(Info.Ctx)) {
+  Info.FFDiag(Conv);
+  Info.Note(CLE->getExprLoc(), diag::note_declared_at);
+  return false;
+}
+  }
+
   CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
   return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
 } else if (isa(Base) || isa(Base)) {

diff  --git a/clang/test/SemaCXX/constant-expression-cxx11.cpp 
b/clang/test/SemaCXX/constant-expression-cxx11.cpp
index 733653af6369c..b03cb7696aae5 100644
--- a/clang/test/SemaCXX/constant-expression-cxx11.cpp
+++ b/clang/test/SemaCXX/constant-expression-cxx11.cpp
@@ -1596,8 +1596,13 @@ namespace CompoundLiteral {
   // Matching GCC, file-scope array compound literals initialized by constants
   // are lifetime-extended.
   constexpr int *p = (int*)(int[1]){3}; // expected-warning {{C99}}
-  static_assert(*p == 3, "");
+  static_assert(*p == 3, "");   // expected-error {{static_assert 
expression is not an integral constant expression}}
+// expected-note@-1 {{subexpression 
not valid}}
+// expected-note@-3 {{declared here}}
   static_assert((int[2]){1, 2}[1] == 2, ""); // expected-warning {{C99}}
+  // expected-error@-1 {{static_assert expression is not an integral constant 
expression}}
+  // expected-note@-2 {{subexpression not valid}}
+  // expected-note@-3 {{declared here}}
 
   // Other kinds are not.
   struct X { int a[2]; };

diff  --git a/clang/test/SemaTemplate/constexpr-instantiate.cpp 
b/clang/test/SemaTemplate/constexpr-instantiate.cpp
index 31dbdb617a6ac..0a34f63553aae 100644
--- a/clang/test/SemaTemplate/constexpr-instantiate.cpp
+++ b/clang/test/SemaTemplate/constexpr-instantiate.cpp
@@ -219,7 +219,9 @@ namespace Unevaluated {
   static int n;
 };
 template struct B {};
-template constexpr int A::k = *(int[N]){N}; // expected-error 
1+{{negative}}
+template  constexpr int A::k = *(int[N]){N}; // expected-error 
1+{{negative}} expected-note 1+{{not valid in a constant expression}} 
expected-note 1+{{declared here}}
+// expected-error@-1 1+{{must be initialized by a constant expression}}
+
 template int A::n = *(int[N]){0};
 
 template  void f() {
@@ -230,9 +232,9 @@ namespace Unevaluated {
 };
 
 decltype(A<-3>::k) d1 = 0; // ok
-decltype(char{A<-4>::k}) d2 = 0; // expected-note {{instantiation of }} 
expected-error {{narrow}} expected-note {{cast}}
-decltype(char{A<1>::k}) d3 = 0; // ok
-decltype(char{A<1 + (unsigned char)-1>::k}) d4 = 0; // expected-error 
{{narrow}} expected-note {{cast}}
+decltype(char{A<-4>::k}) d2 = 0;// expected-note 
1+{{instantiation of }} expected-error {{narrow}} expected-note {{cast}}
+decltype(char{A<1>::k}) d3 = 0; // expect

[clang] 9dffab9 - [clang-format][NFC] Don't call mightFitOnOneLine() unnecessarily

2022-05-16 Thread via cfe-commits

Author: owenca
Date: 2022-05-16T02:43:35-07:00
New Revision: 9dffab9d524a05742a765dea27aedc8a7080a402

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

LOG: [clang-format][NFC] Don't call mightFitOnOneLine() unnecessarily

Clean up UnwrappedLineParser for RemoveBracesLLVM to avoid calling
mightFitOnOneLine() as much as possible.

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index fa76da15a53d..9990933fcb20 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -43,12 +43,15 @@ namespace format {
   TYPE(ConflictAlternative)
\
   TYPE(ConflictEnd)
\
   TYPE(ConflictStart)  
\
+  /* l_brace of if/for/while */
\
+  TYPE(ControlStatementLBrace) 
\
   TYPE(CppCastLParen)  
\
   TYPE(CtorInitializerColon)   
\
   TYPE(CtorInitializerComma)   
\
   TYPE(DesignatedInitializerLSquare)   
\
   TYPE(DesignatedInitializerPeriod)
\
   TYPE(DictLiteral)
\
+  TYPE(ElseLBrace) 
\
   TYPE(EnumLBrace) 
\
   TYPE(FatArrow)   
\
   TYPE(ForEachMacro)   
\

diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index c5135222af69..bde543131931 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -394,7 +394,7 @@ void UnwrappedLineParser::parseFile() {
   if (Style.Language == FormatStyle::LK_TextProto)
 parseBracedList();
   else
-parseLevel(/*HasOpeningBrace=*/false, /*CanContainBracedList=*/true);
+parseLevel(/*OpeningBrace=*/nullptr, /*CanContainBracedList=*/true);
   // Make sure to format the remaining tokens.
   //
   // LK_TextProto is special since its top-level is parsed as the body of a
@@ -463,13 +463,13 @@ bool 
UnwrappedLineParser::precededByCommentOrPPDirective() const {
 }
 
 /// \brief Parses a level, that is ???.
-/// \param HasOpeningBrace If that level is started by an opening brace.
+/// \param OpeningBrace Opening brace (\p nullptr if absent) of that level
 /// \param CanContainBracedList If the content can contain (at any level) a
 /// braced list.
 /// \param NextLBracesType The type for left brace found in this level.
-/// \returns true if a simple block, or false otherwise. (A simple block has a
-/// single statement.)
-bool UnwrappedLineParser::parseLevel(bool HasOpeningBrace,
+/// \returns true if a simple block of if/else/for/while, or false otherwise.
+/// (A simple block has a single statement.)
+bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace,
  bool CanContainBracedList,
  IfStmtKind *IfKind,
  TokenType NextLBracesType) {
@@ -492,9 +492,9 @@ bool UnwrappedLineParser::parseLevel(bool HasOpeningBrace,
 else if (FormatTok->getType() == TT_MacroBlockEnd)
   kind = tok::r_brace;
 
-auto ParseDefault = [this, HasOpeningBrace, IfKind, NextLevelLBracesType,
+auto ParseDefault = [this, OpeningBrace, IfKind, NextLevelLBracesType,
  &HasLabel, &StatementCount] {
-  parseStructuralElement(IfKind, !HasOpeningBrace, NextLevelLBracesType,
+  parseStructuralElement(IfKind, !OpeningBrace, NextLevelLBracesType,
  HasLabel ? nullptr : &HasLabel);
   ++StatementCount;
   assert(StatementCount > 0 && "StatementCount overflow!");
@@ -519,16 +519,17 @@ bool UnwrappedLineParser::parseLevel(bool HasOpeningBrace,
   tryToParseBracedList())
 continue;
   parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u,
- /*MunchSemi=*/true, /*UnindentWhitesmithBraces=*/false,
- CanContainBracedList,
- /*NextLBracesType=*/NextLBracesType);
+ /*MunchSemi=*/

[clang] da201aa - [RISCV][NFC] Remove `*=` operator for LMULType

2022-05-19 Thread via cfe-commits

Author: eopXD
Date: 2022-05-19T23:47:44-07:00
New Revision: da201aa4242ebb06209296962a28f89297d0c9a1

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

LOG: [RISCV][NFC] Remove `*=` operator for LMULType

LMULType always manipulate on Log2LMUL, let all manipulations go
through LMULType::MulLog2LMUL.

Reviewed By: khchen

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

Added: 


Modified: 
clang/include/clang/Support/RISCVVIntrinsicUtils.h
clang/lib/Support/RISCVVIntrinsicUtils.cpp

Removed: 




diff  --git a/clang/include/clang/Support/RISCVVIntrinsicUtils.h 
b/clang/include/clang/Support/RISCVVIntrinsicUtils.h
index f1f06ba60786f..2de7f89f0 100644
--- a/clang/include/clang/Support/RISCVVIntrinsicUtils.h
+++ b/clang/include/clang/Support/RISCVVIntrinsicUtils.h
@@ -156,7 +156,6 @@ struct LMULType {
   std::string str() const;
   llvm::Optional getScale(unsigned ElementBitwidth) const;
   void MulLog2LMUL(int Log2LMUL);
-  LMULType &operator*=(uint32_t RHS);
 };
 
 class RVVType;

diff  --git a/clang/lib/Support/RISCVVIntrinsicUtils.cpp 
b/clang/lib/Support/RISCVVIntrinsicUtils.cpp
index 9f5c1ffe20221..43189f6cf9f50 100644
--- a/clang/lib/Support/RISCVVIntrinsicUtils.cpp
+++ b/clang/lib/Support/RISCVVIntrinsicUtils.cpp
@@ -77,12 +77,6 @@ VScaleVal LMULType::getScale(unsigned ElementBitwidth) const 
{
 
 void LMULType::MulLog2LMUL(int log2LMUL) { Log2LMUL += log2LMUL; }
 
-LMULType &LMULType::operator*=(uint32_t RHS) {
-  assert(isPowerOf2_32(RHS));
-  this->Log2LMUL = this->Log2LMUL + Log2_32(RHS);
-  return *this;
-}
-
 RVVType::RVVType(BasicType BT, int Log2LMUL,
  const PrototypeDescriptor &prototype)
 : BT(BT), LMUL(LMULType(Log2LMUL)) {
@@ -628,17 +622,17 @@ void RVVType::applyModifier(const PrototypeDescriptor 
&Transformer) {
   switch (static_cast(Transformer.VTM)) {
   case VectorTypeModifier::Widening2XVector:
 ElementBitwidth *= 2;
-LMUL *= 2;
+LMUL.MulLog2LMUL(1);
 Scale = LMUL.getScale(ElementBitwidth);
 break;
   case VectorTypeModifier::Widening4XVector:
 ElementBitwidth *= 4;
-LMUL *= 4;
+LMUL.MulLog2LMUL(2);
 Scale = LMUL.getScale(ElementBitwidth);
 break;
   case VectorTypeModifier::Widening8XVector:
 ElementBitwidth *= 8;
-LMUL *= 8;
+LMUL.MulLog2LMUL(3);
 Scale = LMUL.getScale(ElementBitwidth);
 break;
   case VectorTypeModifier::MaskVector:



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


[clang-tools-extra] 1fef69d - Avoid uninitialized Diag.ID (which we pass but never read)

2022-05-20 Thread via cfe-commits

Author: Sam McCall
Date: 2022-05-20T20:29:47+02:00
New Revision: 1fef69da0bfd51de916f0a869f97740c51211cc1

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

LOG: Avoid uninitialized Diag.ID (which we pass but never read)

Added: 


Modified: 
clang-tools-extra/clangd/Diagnostics.h

Removed: 




diff  --git a/clang-tools-extra/clangd/Diagnostics.h 
b/clang-tools-extra/clangd/Diagnostics.h
index 14627ea3d6a0..6004bb147361 100644
--- a/clang-tools-extra/clangd/Diagnostics.h
+++ b/clang-tools-extra/clangd/Diagnostics.h
@@ -69,7 +69,7 @@ struct DiagBase {
   // Since File is only descriptive, we store a separate flag to distinguish
   // diags from the main file.
   bool InsideMainFile = false;
-  unsigned ID; // e.g. member of clang::diag, or clang-tidy assigned ID.
+  unsigned ID = 0; // e.g. member of clang::diag, or clang-tidy assigned ID.
   // Feature modules can make use of this field to propagate data from a
   // diagnostic to a CodeAction request. Each module should only append to the
   // list.



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


[clang] 8bfccb9 - [clang-format] Fix an infinite loop in parseJavaEnumBody()

2022-05-21 Thread via cfe-commits

Author: owenca
Date: 2022-05-21T10:33:59-07:00
New Revision: 8bfccb963b3519393c0266b452a115a4bb46d207

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

LOG: [clang-format] Fix an infinite loop in parseJavaEnumBody()

Fixes #55623.

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index be081a9189600..18f476aca01ae 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3509,7 +3509,7 @@ void UnwrappedLineParser::parseJavaEnumBody() {
   ++Line->Level;
 
   // Parse the enum constants.
-  while (FormatTok) {
+  while (FormatTok->isNot(tok::eof)) {
 if (FormatTok->is(tok::l_brace)) {
   // Parse the constant's class body.
   parseBlock(/*MustBeDeclaration=*/true, /*AddLevels=*/1u,

diff  --git a/clang/unittests/Format/FormatTestJava.cpp 
b/clang/unittests/Format/FormatTestJava.cpp
index e778836e0fc9a..03e16ae0a00d3 100644
--- a/clang/unittests/Format/FormatTestJava.cpp
+++ b/clang/unittests/Format/FormatTestJava.cpp
@@ -197,6 +197,8 @@ TEST_F(FormatTestJava, EnumDeclarations) {
"  CDE;\n"
"  void f() {}\n"
"}");
+  verifyFormat("enum SomeThing {\n"
+   "  void f() {}");
   verifyFormat("enum SomeThing {\n"
"  ABC(1, \"ABC\"),\n"
"  CDE(2, \"CDE\");\n"



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


[clang] 1443dba - [clang-format] Handle "complex" conditionals in RemoveBracesLLVM

2022-05-21 Thread via cfe-commits

Author: owenca
Date: 2022-05-21T14:46:38-07:00
New Revision: 1443dbaba6f0e57be066995db9164f89fb57b413

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

LOG: [clang-format] Handle "complex" conditionals in RemoveBracesLLVM

Do not remove braces if the conditional of if/for/while might not
fit on a single line even after the opening brace is removed.

Examples:
// ColumnLimit: 20
// 45678901234567890
if (a) { /* Remove. */
  foo();
}
if (-b >= c) { // Keep.
  bar();
}

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 18f476aca01a..cb7a17f157ee 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -754,16 +754,19 @@ size_t UnwrappedLineParser::computePPHash() const {
   return h;
 }
 
-// Checks whether \p ParsedLine might fit on a single line. We must clone the
-// tokens of \p ParsedLine before running the token annotator on it so that we
-// can restore them afterward.
-bool UnwrappedLineParser::mightFitOnOneLine(UnwrappedLine &ParsedLine) const {
+// Checks whether \p ParsedLine might fit on a single line. If \p OpeningBrace
+// is not null, subtracts its length (plus the preceding space) when computing
+// the length of \p ParsedLine. We must clone the tokens of \p ParsedLine 
before
+// running the token annotator on it so that we can restore them afterward.
+bool UnwrappedLineParser::mightFitOnOneLine(
+UnwrappedLine &ParsedLine, const FormatToken *OpeningBrace) const {
   const auto ColumnLimit = Style.ColumnLimit;
   if (ColumnLimit == 0)
 return true;
 
   auto &Tokens = ParsedLine.Tokens;
   assert(!Tokens.empty());
+
   const auto *LastToken = Tokens.back().Tok;
   assert(LastToken);
 
@@ -785,7 +788,11 @@ bool UnwrappedLineParser::mightFitOnOneLine(UnwrappedLine 
&ParsedLine) const {
   Annotator.annotate(Line);
   Annotator.calculateFormattingInformation(Line);
 
-  const int Length = LastToken->TotalLength;
+  auto Length = LastToken->TotalLength;
+  if (OpeningBrace) {
+assert(OpeningBrace != Tokens.front().Tok);
+Length -= OpeningBrace->TokenText.size() + 1;
+  }
 
   Index = 0;
   for (auto &Token : Tokens) {
@@ -805,6 +812,8 @@ UnwrappedLineParser::IfStmtKind 
UnwrappedLineParser::parseBlock(
   assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
  "'{' or macro block token expected");
   FormatToken *Tok = FormatTok;
+  const bool FollowedByComment = Tokens->peekNextToken()->is(tok::comment);
+  auto Index = CurrentLines->size();
   const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
   FormatTok->setBlockKind(BK_Block);
 
@@ -854,14 +863,26 @@ UnwrappedLineParser::IfStmtKind 
UnwrappedLineParser::parseBlock(
 return IfKind;
   }
 
-  if (SimpleBlock && !KeepBraces &&
-  Tok->isOneOf(TT_ControlStatementLBrace, TT_ElseLBrace)) {
+  if (SimpleBlock && !KeepBraces) {
+assert(Tok->isOneOf(TT_ControlStatementLBrace, TT_ElseLBrace));
 assert(FormatTok->is(tok::r_brace));
 const FormatToken *Previous = Tokens->getPreviousToken();
 assert(Previous);
 if (Previous->isNot(tok::r_brace) || Previous->Optional) {
   assert(!CurrentLines->empty());
-  if (mightFitOnOneLine(CurrentLines->back())) {
+  const FormatToken *OpeningBrace = Tok;
+  if (!Tok->Previous) { // Wrapped l_brace.
+if (FollowedByComment) {
+  KeepBraces = true;
+} else {
+  assert(Index > 0);
+  --Index; // The line above the wrapped l_brace.
+  OpeningBrace = nullptr;
+}
+  }
+  if (!KeepBraces && mightFitOnOneLine(CurrentLines->back()) &&
+  (Tok->is(TT_ElseLBrace) ||
+   mightFitOnOneLine((*CurrentLines)[Index], OpeningBrace))) {
 Tok->MatchingParen = FormatTok;
 FormatTok->MatchingParen = Tok;
   }

diff  --git a/clang/lib/Format/UnwrappedLineParser.h 
b/clang/lib/Format/UnwrappedLineParser.h
index 2d32d8c6327b..ffba36cd0170 100644
--- a/clang/lib/Format/UnwrappedLineParser.h
+++ b/clang/lib/Format/UnwrappedLineParser.h
@@ -95,7 +95,8 @@ class UnwrappedLineParser {
   bool parseLevel(const FormatToken *OpeningBrace, bool CanContainBracedList,
   IfStmtKind *IfKind = nullptr,
   TokenType NextLBracesType = TT_Unknown);
-  bool mightFitOnOneLine(UnwrappedLine &Line) const;
+  bool mightFitOnOneLine(UnwrappedLine &Line,
+ const FormatToken *OpeningBrace = nullptr) const;
   IfStmtKind parseBlock(bool MustBeDeclaration = false, unsigned AddLevels = 

[clang] f4d52ca - [clang-format] Fix a bug in "AfterControlStatement: MultiLine"

2022-05-21 Thread via cfe-commits

Author: owenca
Date: 2022-05-21T15:10:21-07:00
New Revision: f4d52cad671380d9fa6c1637e1c82b7296fd7da0

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

LOG: [clang-format] Fix a bug in "AfterControlStatement: MultiLine"

Fixes #55582.

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 30755ef1086b..f92c36b449ae 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -404,8 +404,9 @@ class LineJoiner {
 // If possible, merge the next line's wrapped left brace with the
 // current line. Otherwise, leave it on the next line, as this is a
 // multi-line control statement.
-return (Style.ColumnLimit == 0 ||
-TheLine->Last->TotalLength <= Style.ColumnLimit)
+return (Style.ColumnLimit == 0 || TheLine->Level * Style.IndentWidth +
+  TheLine->Last->TotalLength <=
+  Style.ColumnLimit)
? 1
: 0;
   }

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 646a6ed17507..aebb44ee9acd 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -3096,6 +3096,14 @@ TEST_F(FormatTest, MultiLineControlStatements) {
 " baz);",
 format("do{foo();}while(bar&&baz);", Style));
   // Long lines should put opening brace on new line.
+  verifyFormat("void f() {\n"
+   "  if (a1 && a2 &&\n"
+   "  a3)\n"
+   "  {\n"
+   "quux();\n"
+   "  }\n"
+   "}",
+   "void f(){if(a1&&a2&&a3){quux();}}", Style);
   EXPECT_EQ("if (foo && bar &&\n"
 "baz)\n"
 "{\n"



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


[clang] 130a9cc - [clang-format] Fix a crash on lambda trailing return type

2022-05-21 Thread via cfe-commits

Author: owenca
Date: 2022-05-21T15:50:50-07:00
New Revision: 130a9cc0a5e25e3be8ff3738518e86ae3ae0b5ba

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

LOG: [clang-format] Fix a crash on lambda trailing return type

Fixes #55625.

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 9afe4f8fb086..7f1c4b8e61b6 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1185,7 +1185,8 @@ class AnnotatingParser {
   }
   break;
 case tok::arrow:
-  if (Tok->Previous && Tok->Previous->is(tok::kw_noexcept))
+  if (Tok->isNot(TT_LambdaArrow) && Tok->Previous &&
+  Tok->Previous->is(tok::kw_noexcept))
 Tok->setType(TT_TrailingReturnArrow);
   break;
 default:

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index aebb44ee9acd..83b8dbed75e3 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -21338,6 +21338,7 @@ TEST_F(FormatTest, FormatsLambdas) {
   verifyFormat("int c = []() -> int * { return 2; }();\n");
   verifyFormat("int c = []() -> vector { return {2}; }();\n");
   verifyFormat("Foo([]() -> std::vector { return {2}; }());");
+  verifyFormat("foo([]() noexcept -> int {});");
   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair {};");
   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");



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


[clang] 554efc2 - [clang-format] Format unit tests with InsertBraces/RemoveBracesLLVM

2022-05-21 Thread via cfe-commits

Author: owenca
Date: 2022-05-21T16:13:35-07:00
New Revision: 554efc225217272df755a962d841d57056af83f4

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

LOG: [clang-format] Format unit tests with InsertBraces/RemoveBracesLLVM

Added: 


Modified: 
clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp 
b/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
index cb24cc921bc0..45dd2fdc46b6 100644
--- a/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
+++ b/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
@@ -76,8 +76,9 @@ class DefinitionBlockSeparatorTest : public ::testing::Test {
   if (Result.size()) {
 auto LastChar = Result.back();
 if ((Char == '\n' && LastChar == '\n') ||
-(Char == '\r' && (LastChar == '\r' || LastChar == '\n')))
+(Char == '\r' && (LastChar == '\r' || LastChar == '\n'))) {
   continue;
+}
   }
   Result.push_back(Char);
 }

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 83b8dbed75e3..3621ba667818 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -19609,7 +19609,8 @@ TEST_F(FormatTest, UnderstandPragmaRegion) {
   auto Style = getLLVMStyleWithColumns(0);
   verifyFormat("#pragma region TEST(FOO : BAR)", Style);
 
-  EXPECT_EQ("#pragma region TEST(FOO : BAR)", format("#pragma region TEST(FOO 
: BAR)", Style));
+  EXPECT_EQ("#pragma region TEST(FOO : BAR)",
+format("#pragma region TEST(FOO : BAR)", Style));
 }
 
 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {



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


[clang-tools-extra] 89e663c - [clang-tidy] Improve add_new_check.py to recognize more checks

2022-05-23 Thread via cfe-commits

Author: Richard
Date: 2022-05-23T09:47:54-06:00
New Revision: 89e663c4f83a6736fc74a01ec48cb4f01210f86f

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

LOG: [clang-tidy] Improve add_new_check.py to recognize more checks

When looking for whether or not a check provides fixits, the script
examines the implementation of the check.  Some checks are not
implemented in source files that correspond one-to-one with the check
name, e.g. cert-dcl21-cpp.  So if we can't find the check implementation
directly from the check name, open up the corresponding module file and
look for the class name that is registered with the check.  Then consult
the file corresponding to the class name.

Some checks are derived from a base class that implements fixits.  So if
we can't find fixits in the implementation file for a check, scrape out
the name of it's base class.  If it's not ClangTidyCheck, then consult
the base class implementation to look for fixit support.

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

Fixes #55630

Added: 


Modified: 
clang-tools-extra/clang-tidy/add_new_check.py
clang-tools-extra/docs/clang-tidy/checks/list.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/add_new_check.py 
b/clang-tools-extra/clang-tidy/add_new_check.py
index fc83974486314..2e8684ca756dc 100644
--- a/clang-tools-extra/clang-tidy/add_new_check.py
+++ b/clang-tools-extra/clang-tidy/add_new_check.py
@@ -158,12 +158,17 @@ def write_implementation(module_path, module, namespace, 
check_name_camel):
'namespace': namespace})
 
 
-# Modifies the module to include the new check.
-def adapt_module(module_path, module, check_name, check_name_camel):
+# Returns the source filename that implements the module.
+def get_module_filename(module_path, module):
   modulecpp = list(filter(
   lambda p: p.lower() == module.lower() + 'tidymodule.cpp',
   os.listdir(module_path)))[0]
-  filename = os.path.join(module_path, modulecpp)
+  return os.path.join(module_path, modulecpp)
+
+
+# Modifies the module to include the new check.
+def adapt_module(module_path, module, check_name, check_name_camel):
+  filename = get_module_filename(module_path, module)
   with io.open(filename, 'r', encoding='utf8') as f:
 lines = f.readlines()
 
@@ -320,24 +325,100 @@ def update_checks_list(clang_tidy_path):
  os.listdir(docs_dir)))
   doc_files.sort()
 
+  # We couldn't find the source file from the check name, so try to find the
+  # class name that corresponds to the check in the module file.
+  def filename_from_module(module_name, check_name):
+module_path = os.path.join(clang_tidy_path, module_name)
+if not os.path.isdir(module_path):
+  return ''
+module_file = get_module_filename(module_path, module_name)
+if not os.path.isfile(module_file):
+  return ''
+with io.open(module_file, 'r') as f:
+  code = f.read()
+  full_check_name = module_name + '-' + check_name
+  name_pos = code.find('"' + full_check_name + '"')
+  if name_pos == -1:
+return ''
+  stmt_end_pos = code.find(';', name_pos)
+  if stmt_end_pos == -1:
+return ''
+  stmt_start_pos = code.rfind(';', 0, name_pos)
+  if stmt_start_pos == -1:
+stmt_start_pos = code.rfind('{', 0, name_pos)
+  if stmt_start_pos == -1:
+return ''
+  stmt = code[stmt_start_pos+1:stmt_end_pos]
+  matches = re.search('registerCheck<([^>:]*)>\(\s*"([^"]*)"\s*\)', stmt)
+  if matches and matches[2] == full_check_name:
+class_name = matches[1]
+if '::' in class_name:
+  parts = class_name.split('::')
+  class_name = parts[-1]
+  class_path = os.path.join(clang_tidy_path, module_name, '..', 
*parts[0:-1])
+else:
+  class_path = os.path.join(clang_tidy_path, module_name)
+return get_actual_filename(class_path, class_name + '.cpp')
+
+return ''
+
+  # Examine code looking for a c'tor definition to get the base class name.
+  def get_base_class(code, check_file):
+check_class_name = os.path.splitext(os.path.basename(check_file))[0]
+ctor_pattern = check_class_name + 
'\([^:]*\)\s*:\s*([A-Z][A-Za-z0-9]*Check)\('
+matches = re.search('\s+' + check_class_name + '::' + ctor_pattern, code)
+
+# The constructor might be inline in the header.
+if not matches:
+  header_file = os.path.splitext(check_file)[0] + '.h'
+  if not os.path.isfile(header_file):
+return ''
+  with io.open(header_file, encoding='utf8') as f:
+code = f.read()
+  matches = re.search(' ' + ctor_pattern, code)
+
+if matches and matches[1] != 'ClangTidyCheck':
+  return matches[1]
+return ''
+
+  # Some simple heuristics to figure out if a che

[clang] 232bf81 - [OpenMP] atomic compare fail : Parser & AST support

2022-05-24 Thread via cfe-commits

Author: Sunil Kuravinakop
Date: 2022-05-24T23:56:42-05:00
New Revision: 232bf8189ef7d574a468bd5bfd1e84e962f7f16e

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

LOG: [OpenMP] atomic compare fail : Parser & AST support

This is a support for " #pragma omp atomic compare fail ". It has Parser & AST 
support for now.

Reviewed By: tianshilei1992

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

Added: 


Modified: 
clang/include/clang/AST/ASTNodeTraverser.h
clang/include/clang/AST/OpenMPClause.h
clang/include/clang/AST/RecursiveASTVisitor.h
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/Sema.h
clang/lib/AST/OpenMPClause.cpp
clang/lib/AST/StmtProfile.cpp
clang/lib/Basic/OpenMPKinds.cpp
clang/lib/Parse/ParseOpenMP.cpp
clang/lib/Sema/SemaOpenMP.cpp
clang/lib/Sema/TreeTransform.h
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTWriter.cpp
clang/test/OpenMP/atomic_ast_print.cpp
clang/test/OpenMP/atomic_messages.cpp
clang/tools/libclang/CIndex.cpp
flang/lib/Semantics/check-omp-structure.cpp
llvm/include/llvm/Frontend/OpenMP/OMP.td

Removed: 




diff  --git a/clang/include/clang/AST/ASTNodeTraverser.h 
b/clang/include/clang/AST/ASTNodeTraverser.h
index f2c5c01ac88de..cb5bbeb644812 100644
--- a/clang/include/clang/AST/ASTNodeTraverser.h
+++ b/clang/include/clang/AST/ASTNodeTraverser.h
@@ -214,6 +214,10 @@ class ASTNodeTraverser
   }
 
   void Visit(const OMPClause *C) {
+if (OMPFailClause::classof(C)) {
+  Visit(static_cast(C));
+  return;
+}
 getNodeDelegate().AddChild([=] {
   getNodeDelegate().Visit(C);
   for (const auto *S : C->children())
@@ -221,6 +225,13 @@ class ASTNodeTraverser
 });
   }
 
+  void Visit(const OMPFailClause *C) {
+getNodeDelegate().AddChild([=] {
+  getNodeDelegate().Visit(C);
+  const OMPClause *MOC = C->const_getMemoryOrderClause();
+  Visit(MOC);
+});
+  }
   void Visit(const GenericSelectionExpr::ConstAssociation &A) {
 getNodeDelegate().AddChild([=] {
   getNodeDelegate().Visit(A);

diff  --git a/clang/include/clang/AST/OpenMPClause.h 
b/clang/include/clang/AST/OpenMPClause.h
index a745df1143468..aa9503c565779 100644
--- a/clang/include/clang/AST/OpenMPClause.h
+++ b/clang/include/clang/AST/OpenMPClause.h
@@ -2266,6 +2266,133 @@ class OMPCompareClause final : public OMPClause {
   }
 };
 
+/// This represents 'fail' clause in the '#pragma omp atomic'
+/// directive.
+///
+/// \code
+/// #pragma omp atomic compare fail
+/// \endcode
+/// In this example directive '#pragma omp atomic compare' has 'fail' clause.
+class OMPFailClause final
+: public OMPClause,
+  private llvm::TrailingObjects {
+  OMPClause *MemoryOrderClause;
+
+  friend class OMPClauseReader;
+  friend TrailingObjects;
+
+  /// Define the sizes of each trailing object array except the last one. This
+  /// is required for TrailingObjects to work properly.
+  size_t numTrailingObjects(OverloadToken) const {
+// 2 locations: for '(' and argument location.
+return 2;
+  }
+
+  /// Sets the location of '(' in fail clause.
+  void setLParenLoc(SourceLocation Loc) {
+*getTrailingObjects() = Loc;
+  }
+
+  /// Sets the location of memoryOrder clause argument in fail clause.
+  void setArgumentLoc(SourceLocation Loc) {
+*std::next(getTrailingObjects(), 1) = Loc;
+  }
+
+  /// Sets the mem_order clause for 'atomic compare fail' directive.
+  void setMemOrderClauseKind(OpenMPClauseKind MemOrder) {
+OpenMPClauseKind *MOCK = getTrailingObjects();
+*MOCK = MemOrder;
+  }
+
+  /// Sets the mem_order clause for 'atomic compare fail' directive.
+  void setMemOrderClause(OMPClause *MemoryOrderClauseParam) {
+MemoryOrderClause = MemoryOrderClauseParam;
+  }
+public:
+  /// Build 'fail' clause.
+  ///
+  /// \param StartLoc Starting location of the clause.
+  /// \param EndLoc Ending location of the clause.
+  OMPFailClause(SourceLocation StartLoc, SourceLocation EndLoc)
+  : OMPClause(llvm::omp::OMPC_fail, StartLoc, EndLoc) {}
+
+  /// Build an empty clause.
+  OMPFailClause()
+  : OMPClause(llvm::omp::OMPC_fail, SourceLocation(), SourceLocation()) {}
+
+  static OMPFailClause *CreateEmpty(const ASTContext &C);
+  static OMPFailClause *Create(const ASTContext &C, SourceLocation StartLoc,
+   SourceLocation EndLoc);
+
+  child_range children() {
+return child_range(child_iterator(), child_iterator());
+  }
+
+
+  const_child_range children() const {
+return const_child_range(const_child_iterator(), const_child_iterator());
+  }
+
+  child_range used_children() {
+return child_range(child_iterator(), child_iterato

[clang] ca27f3e - [Clang][OpenMP] Support for omp nothing

2022-05-24 Thread via cfe-commits

Author: Sunil Kuravinakop
Date: 2022-05-24T23:59:31-05:00
New Revision: ca27f3e3b26ed5389d4a361f274e3be516eb282d

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

LOG: [Clang][OpenMP] Support for omp nothing

Patch to support "#pragma omp nothing"

Reviewed By: tianshilei1992

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

Added: 
clang/test/OpenMP/nothing_messages.cpp

Modified: 
clang/lib/Basic/OpenMPKinds.cpp
clang/lib/Parse/ParseOpenMP.cpp
llvm/include/llvm/Frontend/OpenMP/OMP.td

Removed: 




diff  --git a/clang/lib/Basic/OpenMPKinds.cpp b/clang/lib/Basic/OpenMPKinds.cpp
index 5ff4e023fb3c1..dbfe2117b00a6 100644
--- a/clang/lib/Basic/OpenMPKinds.cpp
+++ b/clang/lib/Basic/OpenMPKinds.cpp
@@ -730,6 +730,9 @@ void clang::getOpenMPCaptureRegions(
   case OMPD_teams_loop:
 CaptureRegions.push_back(OMPD_teams);
 break;
+  case OMPD_nothing:
+CaptureRegions.push_back(OMPD_nothing);
+break;
   case OMPD_loop:
 // TODO: 'loop' may require 
diff erent capture regions depending on the bind
 // clause or the parent directive when there is no bind clause. Use

diff  --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp
index 3d5c9c949760b..1e484f5644170 100644
--- a/clang/lib/Parse/ParseOpenMP.cpp
+++ b/clang/lib/Parse/ParseOpenMP.cpp
@@ -2488,6 +2488,16 @@ StmtResult 
Parser::ParseOpenMPDeclarativeOrExecutableDirective(
   bool HasAssociatedStatement = true;
 
   switch (DKind) {
+  case OMPD_nothing:
+if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
+ParsedStmtContext())
+  Diag(Tok, diag::err_omp_immediate_directive)
+<< getOpenMPDirectiveName(DKind) << 0;
+ConsumeToken();
+skipUntilPragmaOpenMPEnd(DKind);
+if (Tok.is(tok::annot_pragma_openmp_end))
+  ConsumeAnnotationToken();
+break;
   case OMPD_metadirective: {
 ConsumeToken();
 SmallVector VMIs;

diff  --git a/clang/test/OpenMP/nothing_messages.cpp 
b/clang/test/OpenMP/nothing_messages.cpp
new file mode 100644
index 0..cd6d0defe492f
--- /dev/null
+++ b/clang/test/OpenMP/nothing_messages.cpp
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -verify=expected -fopenmp -ferror-limit 100 %s 
-Wuninitialized
+
+int mixed() {
+  int x = 0;
+  int d = 4;
+
+#pragma omp nothing
+  x=d;
+
+  if(!x) {
+#pragma omp nothing
+x=d;
+  }
+
+// expected-error@+2 {{#pragma omp nothing' cannot be an immediate 
substatement}}
+  if(!x)
+#pragma omp nothing
+x=d;
+
+// expected-warning@+2 {{extra tokens at the end of '#pragma omp nothing' are 
ignored}}
+  if(!x) {
+#pragma omp nothing seq_cst
+x=d;
+  }
+
+  return 0;
+}

diff  --git a/llvm/include/llvm/Frontend/OpenMP/OMP.td 
b/llvm/include/llvm/Frontend/OpenMP/OMP.td
index 8218be1f966bf..b4abc64bc2118 100644
--- a/llvm/include/llvm/Frontend/OpenMP/OMP.td
+++ b/llvm/include/llvm/Frontend/OpenMP/OMP.td
@@ -629,6 +629,7 @@ def OMP_Requires : Directive<"requires"> {
 VersionedClause
   ];
 }
+def OMP_Nothing : Directive<"nothing"> {}
 def OMP_TargetData : Directive<"target data"> {
   let allowedClauses = [
 VersionedClause,



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


[clang] 5221875 - [clang-format] Fix an invalid code generation in RemoveBracesLLVM

2022-05-26 Thread via cfe-commits

Author: owenca
Date: 2022-05-26T13:38:04-07:00
New Revision: 5221875a957da927a889a705276d4e073ff737b1

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

LOG: [clang-format] Fix an invalid code generation in RemoveBracesLLVM

Fixes #55706.

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

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 0611e9eace476..fe57141407c0d 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2587,10 +2587,13 @@ FormatToken 
*UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
   FormatTok->setFinalizedType(TT_ElseLBrace);
   ElseLeftBrace = FormatTok;
   CompoundStatementIndenter Indenter(this, Style, Line->Level);
-  if (parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u,
- /*MunchSemi=*/true,
- KeepElseBraces) == IfStmtKind::IfOnly) {
-Kind = IfStmtKind::IfElseIf;
+  const IfStmtKind ElseBlockKind =
+  parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u,
+ /*MunchSemi=*/true, KeepElseBraces);
+  if ((ElseBlockKind == IfStmtKind::IfOnly ||
+   ElseBlockKind == IfStmtKind::IfElseIf) &&
+  FormatTok->is(tok::kw_else)) {
+KeepElseBraces = true;
   }
   addUnwrappedLine();
 } else if (FormatTok->is(tok::kw_if)) {

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 44ef882fe7db4..c1257059c8649 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -25385,6 +25385,30 @@ TEST_F(FormatTest, RemoveBraces) {
"}",
Style);
 
+  verifyFormat("if (a)\n"
+   "  if (b)\n"
+   "c;\n"
+   "  else {\n"
+   "if (d)\n"
+   "  e;\n"
+   "  }\n"
+   "else\n"
+   "  f;",
+   Style);
+
+  verifyFormat("if (a)\n"
+   "  if (b)\n"
+   "c;\n"
+   "  else {\n"
+   "if (d)\n"
+   "  e;\n"
+   "else if (f)\n"
+   "  g;\n"
+   "  }\n"
+   "else\n"
+   "  h;",
+   Style);
+
   verifyFormat("if (a)\n"
"  b;\n"
"else if (c)\n"



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


[clang] 5bf44aa - [clang-format][NFC] Refactor UnwrappedLineParser::parseBlock()

2022-05-26 Thread via cfe-commits

Author: owenca
Date: 2022-05-26T13:56:47-07:00
New Revision: 5bf44aa434ffe4d2e49806be20683e32135f4e16

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

LOG: [clang-format][NFC] Refactor UnwrappedLineParser::parseBlock()

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index fe57141407c0..9a5d85cead88 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -871,30 +871,33 @@ UnwrappedLineParser::IfStmtKind 
UnwrappedLineParser::parseBlock(
 return IfKind;
   }
 
-  if (SimpleBlock && !KeepBraces) {
+  auto RemoveBraces = [=]() mutable {
+if (KeepBraces || !SimpleBlock)
+  return false;
 assert(Tok->isOneOf(TT_ControlStatementLBrace, TT_ElseLBrace));
 assert(FormatTok->is(tok::r_brace));
+const bool WrappedOpeningBrace = !Tok->Previous;
+if (WrappedOpeningBrace && FollowedByComment)
+  return false;
 const FormatToken *Previous = Tokens->getPreviousToken();
 assert(Previous);
-if (Previous->isNot(tok::r_brace) || Previous->Optional) {
-  assert(!CurrentLines->empty());
-  const FormatToken *OpeningBrace = Tok;
-  if (!Tok->Previous) { // Wrapped l_brace.
-if (FollowedByComment) {
-  KeepBraces = true;
-} else {
-  assert(Index > 0);
-  --Index; // The line above the wrapped l_brace.
-  OpeningBrace = nullptr;
-}
-  }
-  if (!KeepBraces && mightFitOnOneLine(CurrentLines->back()) &&
-  (Tok->is(TT_ElseLBrace) ||
-   mightFitOnOneLine((*CurrentLines)[Index], OpeningBrace))) {
-Tok->MatchingParen = FormatTok;
-FormatTok->MatchingParen = Tok;
-  }
+if (Previous->is(tok::r_brace) && !Previous->Optional)
+  return false;
+assert(!CurrentLines->empty());
+if (!mightFitOnOneLine(CurrentLines->back()))
+  return false;
+if (Tok->is(TT_ElseLBrace))
+  return true;
+if (WrappedOpeningBrace) {
+  assert(Index > 0);
+  --Index; // The line above the wrapped l_brace.
+  Tok = nullptr;
 }
+return mightFitOnOneLine((*CurrentLines)[Index], Tok);
+  };
+  if (RemoveBraces()) {
+Tok->MatchingParen = FormatTok;
+FormatTok->MatchingParen = Tok;
   }
 
   size_t PPEndHash = computePPHash();



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


[clang] 52992f1 - Add !nosanitize to FixedMetadataKinds

2022-05-26 Thread via cfe-commits

Author: Enna1
Date: 2022-05-27T09:46:13+08:00
New Revision: 52992f136b3bd421533ac909c520525e34058468

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

LOG: Add !nosanitize to FixedMetadataKinds

This patch adds !nosanitize metadata to FixedMetadataKinds.def, !nosanitize 
indicates that LLVM should not insert any sanitizer instrumentation.

Reviewed By: vitalybuka

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

Added: 


Modified: 
clang/lib/CodeGen/SanitizerMetadata.cpp
llvm/include/llvm/IR/FixedMetadataKinds.def
llvm/lib/Transforms/IPO/HotColdSplitting.cpp
llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/SanitizerMetadata.cpp 
b/clang/lib/CodeGen/SanitizerMetadata.cpp
index 9e26d242d3a7..51f67622c941 100644
--- a/clang/lib/CodeGen/SanitizerMetadata.cpp
+++ b/clang/lib/CodeGen/SanitizerMetadata.cpp
@@ -87,7 +87,7 @@ void 
SanitizerMetadata::disableSanitizerForGlobal(llvm::GlobalVariable *GV) {
 }
 
 void SanitizerMetadata::disableSanitizerForInstruction(llvm::Instruction *I) {
-  I->setMetadata(CGM.getModule().getMDKindID("nosanitize"),
+  I->setMetadata(llvm::LLVMContext::MD_nosanitize,
  llvm::MDNode::get(CGM.getLLVMContext(), None));
 }
 

diff  --git a/llvm/include/llvm/IR/FixedMetadataKinds.def 
b/llvm/include/llvm/IR/FixedMetadataKinds.def
index 31979cd2f9db..9a78fd895fe2 100644
--- a/llvm/include/llvm/IR/FixedMetadataKinds.def
+++ b/llvm/include/llvm/IR/FixedMetadataKinds.def
@@ -42,3 +42,4 @@ LLVM_FIXED_MD_KIND(MD_preserve_access_index, 
"llvm.preserve.access.index", 27)
 LLVM_FIXED_MD_KIND(MD_vcall_visibility, "vcall_visibility", 28)
 LLVM_FIXED_MD_KIND(MD_noundef, "noundef", 29)
 LLVM_FIXED_MD_KIND(MD_annotation, "annotation", 30)
+LLVM_FIXED_MD_KIND(MD_nosanitize, "nosanitize", 31)

diff  --git a/llvm/lib/Transforms/IPO/HotColdSplitting.cpp 
b/llvm/lib/Transforms/IPO/HotColdSplitting.cpp
index 670b67a5131b..95e8ae0fd22f 100644
--- a/llvm/lib/Transforms/IPO/HotColdSplitting.cpp
+++ b/llvm/lib/Transforms/IPO/HotColdSplitting.cpp
@@ -113,7 +113,8 @@ bool unlikelyExecuted(BasicBlock &BB) {
   // mark sanitizer traps as cold.
   for (Instruction &I : BB)
 if (auto *CB = dyn_cast(&I))
-  if (CB->hasFnAttr(Attribute::Cold) && !CB->getMetadata("nosanitize"))
+  if (CB->hasFnAttr(Attribute::Cold) &&
+  !CB->getMetadata(LLVMContext::MD_nosanitize))
 return true;
 
   // The block is cold if it has an unreachable terminator, unless it's

diff  --git a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
index 41ef29b28898..645ca9f257a1 100644
--- a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -1331,7 +1331,7 @@ bool AddressSanitizer::ignoreAccess(Instruction *Inst, 
Value *Ptr) {
 void AddressSanitizer::getInterestingMemoryOperands(
 Instruction *I, SmallVectorImpl &Interesting) {
   // Skip memory accesses inserted by another instrumentation.
-  if (I->hasMetadata("nosanitize"))
+  if (I->hasMetadata(LLVMContext::MD_nosanitize))
 return;
 
   // Do not instrument the load fetching the dynamic shadow address.
@@ -2771,7 +2771,8 @@ bool AddressSanitizer::instrumentFunction(Function &F,
 if (auto *CB = dyn_cast(&Inst)) {
   // A call inside BB.
   TempsToInstrument.clear();
-  if (CB->doesNotReturn() && !CB->hasMetadata("nosanitize"))
+  if (CB->doesNotReturn() &&
+  !CB->hasMetadata(LLVMContext::MD_nosanitize))
 NoReturnCalls.push_back(CB);
 }
 if (CallInst *CI = dyn_cast(&Inst))

diff  --git a/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
index 39a396f3c147..68e93cb934a7 100644
--- a/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
@@ -715,7 +715,7 @@ bool HWAddressSanitizer::ignoreAccess(Instruction *Inst, 
Value *Ptr) {
 void HWAddressSanitizer::getInterestingMemoryOperands(
 Instruction *I, SmallVectorImpl &Interesting) {
   // Skip memory accesses inserted by another instrumentation.
-  if (I->hasMetadata("nosanitize"))
+  if (I->hasMetadata(LLVMContext::MD_nosanitize))
 return;
 
   // Do not instrument the load fetching the dynamic shadow address.

diff  --git a/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
index bc1a340fdc

[clang] 2d82c9c - [clang-format][NFC] Fix braces in ClangFormat.cpp

2022-06-15 Thread via cfe-commits

Author: owenca
Date: 2022-06-15T12:57:48-07:00
New Revision: 2d82c9ccf32c9200b1a48de613869113e8655508

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

LOG: [clang-format][NFC] Fix braces in ClangFormat.cpp

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

Added: 


Modified: 
clang/tools/clang-format/ClangFormat.cpp

Removed: 




diff  --git a/clang/tools/clang-format/ClangFormat.cpp 
b/clang/tools/clang-format/ClangFormat.cpp
index 5f7d65f9a1b0c..b85cb1220d6ba 100644
--- a/clang/tools/clang-format/ClangFormat.cpp
+++ b/clang/tools/clang-format/ClangFormat.cpp
@@ -358,9 +358,10 @@ static void outputXML(const Replacements &Replaces,
   if (!Status.FormatComplete)
 outs() << " line='" << Status.Line << "'";
   outs() << ">\n";
-  if (Cursor.getNumOccurrences() != 0)
+  if (Cursor.getNumOccurrences() != 0) {
 outs() << "" << 
FormatChanges.getShiftedCodePosition(CursorPosition)
<< "\n";
+  }
 
   outputReplacementsXML(Replaces);
   outs() << "\n";
@@ -436,11 +437,11 @@ static bool format(StringRef FileName) {
   .Case("left", FormatStyle::QAS_Left)
   .Default(FormatStyle->QualifierAlignment);
 
-  if (FormatStyle->QualifierAlignment == FormatStyle::QAS_Left)
+  if (FormatStyle->QualifierAlignment == FormatStyle::QAS_Left) {
 FormatStyle->QualifierOrder = {"const", "volatile", "type"};
-  else if (FormatStyle->QualifierAlignment == FormatStyle::QAS_Right)
+  } else if (FormatStyle->QualifierAlignment == FormatStyle::QAS_Right) {
 FormatStyle->QualifierOrder = {"type", "const", "volatile"};
-  else if (QualifierAlignmentOrder.contains("type")) {
+  } else if (QualifierAlignmentOrder.contains("type")) {
 FormatStyle->QualifierAlignment = FormatStyle::QAS_Custom;
 SmallVector Qualifiers;
 QualifierAlignmentOrder.split(Qualifiers, " ", /*MaxSplit=*/-1,
@@ -463,9 +464,8 @@ static bool format(StringRef FileName) {
   if (FormatStyle->isJson() && !FormatStyle->DisableFormat) {
 auto Err = Replaces.add(tooling::Replacement(
 tooling::Replacement(AssumedFileName, 0, 0, "x = ")));
-if (Err) {
+if (Err)
   llvm::errs() << "Bad Json variable insertion\n";
-}
   }
 
   auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), 
Replaces);
@@ -480,11 +480,10 @@ static bool format(StringRef FileName) {
   reformat(*FormatStyle, *ChangedCode, Ranges, AssumedFileName, &Status);
   Replaces = Replaces.merge(FormatChanges);
   if (OutputXML || DryRun) {
-if (DryRun) {
+if (DryRun)
   return emitReplacementWarnings(Replaces, AssumedFileName, Code);
-} else {
+else
   outputXML(Replaces, FormatChanges, Status, Cursor, CursorPosition);
-}
   } else {
 IntrusiveRefCntPtr InMemoryFileSystem(
 new llvm::vfs::InMemoryFileSystem);
@@ -579,9 +578,8 @@ int main(int argc, const char **argv) {
 return 0;
   }
 
-  if (DumpConfig) {
+  if (DumpConfig)
 return dumpConfig();
-  }
 
   if (!Files.empty()) {
 std::ifstream ExternalFileOfFiles{std::string(Files)};
@@ -608,9 +606,10 @@ int main(int argc, const char **argv) {
 
   unsigned FileNo = 1;
   for (const auto &FileName : FileNames) {
-if (Verbose)
+if (Verbose) {
   errs() << "Formatting [" << FileNo++ << "/" << FileNames.size() << "] "
  << FileName << "\n";
+}
 Error |= clang::format::format(FileName);
   }
   return Error ? 1 : 0;



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


[clang] fc6b228 - [Static Analyzer][CFG] Introducing the source array in the CFG of DecompositionDecl

2022-06-17 Thread via cfe-commits

Author: isuckatcs
Date: 2022-06-17T18:34:34+02:00
New Revision: fc6b2281bfd747b3e24d23e2ee8de189f741770f

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

LOG: [Static Analyzer][CFG] Introducing the source array in the CFG of 
DecompositionDecl

For DecompositionDecl, the array, which is being decomposed was not present in 
the
CFG, which lead to the liveness analysis falsely detecting it as a dead symbol.

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

Added: 


Modified: 
clang/lib/Analysis/CFG.cpp
clang/test/Analysis/cfg.cpp

Removed: 




diff  --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index 8379e108fa27b..b16898d3ffa0b 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -609,6 +609,7 @@ class CFGBuilder {
   AddStmtChoice asc);
   CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
   CFGBlock *VisitWhileStmt(WhileStmt *W);
+  CFGBlock *VisitArrayInitLoopExpr(ArrayInitLoopExpr *A, AddStmtChoice asc);
 
   CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd,
   bool ExternallyDestructed = false);
@@ -2330,6 +2331,9 @@ CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc,
 
 case Stmt::WhileStmtClass:
   return VisitWhileStmt(cast(S));
+
+case Stmt::ArrayInitLoopExprClass:
+  return VisitArrayInitLoopExpr(cast(S), asc);
   }
 }
 
@@ -3881,6 +3885,27 @@ CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
   return EntryConditionBlock;
 }
 
+CFGBlock *CFGBuilder::VisitArrayInitLoopExpr(ArrayInitLoopExpr *A,
+ AddStmtChoice asc) {
+  if (asc.alwaysAdd(*this, A)) {
+autoCreateBlock();
+appendStmt(Block, A);
+  }
+
+  CFGBlock *B = Block;
+
+  if (CFGBlock *R = Visit(A->getSubExpr()))
+B = R;
+
+  auto *OVE = dyn_cast(A->getCommonExpr());
+  assert(OVE && "ArrayInitLoopExpr->getCommonExpr() should be wrapped in an "
+"OpaqueValueExpr!");
+  if (CFGBlock *R = Visit(OVE->getSourceExpr()))
+B = R;
+
+  return B;
+}
+
 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *CS) {
   // ObjCAtCatchStmt are treated like labels, so they are the first statement
   // in a block.

diff  --git a/clang/test/Analysis/cfg.cpp b/clang/test/Analysis/cfg.cpp
index 333ea565287b2..df4c7b32fb685 100644
--- a/clang/test/Analysis/cfg.cpp
+++ b/clang/test/Analysis/cfg.cpp
@@ -650,6 +650,22 @@ int crash_with_thread_local(char *p, int *q) {
   return 0;
 }
 
+// CHECK-LABEL: void DecompositionDecl()
+// CHECK:   [B1]
+// CHECK-NEXT:1: int arr[2];
+// CHECK-NEXT:2: arr
+// CHECK-NEXT:3: [B1.2] (ImplicitCastExpr, ArrayToPointerDecay, int *)
+// CHECK-NEXT:4: *
+// CHECK-NEXT:5: [B1.3]{{\[\[}}B1.4]]
+// CHECK-NEXT:6: [B1.5] (ImplicitCastExpr, LValueToRValue, int)
+// CHECK-NEXT:7: {{\{}}[B1.6]{{(\})}}
+// CHECK-NEXT:8: auto = {{\{}}arr[*]{{(\})}};
+void DecompositionDecl() {
+  int arr[2];
+
+  auto [a, b] = arr;
+}
+
 // CHECK-LABEL: template<> int *PR18472()
 // CHECK: [B2 (ENTRY)]
 // CHECK-NEXT:   Succs (1): B1



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


[clang] 92bf652 - [Static Analyzer] Small array binding policy

2022-06-17 Thread via cfe-commits

Author: isuckatcs
Date: 2022-06-17T18:56:13+02:00
New Revision: 92bf652d40740b947de6c41fe09f282ec0530dc5

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

LOG: [Static Analyzer] Small array binding policy

If a lazyCompoundVal to a struct is bound to the store, there is a policy which 
decides
whether a copy gets created instead.

This patch introduces a similar policy for arrays, which is required to model 
structured
binding to arrays without false negatives.

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
clang/lib/StaticAnalyzer/Core/RegionStore.cpp
clang/test/Analysis/analyzer-config.c

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def 
b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
index d7075fb39fc89..9974ea9392acb 100644
--- a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
+++ b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
@@ -440,11 +440,19 @@ ANALYZER_OPTION(
 ANALYZER_OPTION(
 unsigned, RegionStoreSmallStructLimit, "region-store-small-struct-limit",
 "The largest number of fields a struct can have and still be considered "
-"small This is currently used to decide whether or not it is worth forcing 
"
+"small. This is currently used to decide whether or not it is worth 
forcing "
 "a LazyCompoundVal on bind. To disable all small-struct-dependent "
 "behavior, set the option to 0.",
 2)
 
+ANALYZER_OPTION(
+unsigned, RegionStoreSmallArrayLimit, "region-store-small-array-limit",
+"The largest number of elements an array can have and still be considered "
+"small. This is currently used to decide whether or not it is worth 
forcing "
+"a LazyCompoundVal on bind. To disable all small-array-dependent "
+"behavior, set the option to 0.",
+5)
+
 
//===--===//
 // String analyzer options.
 
//===--===//

diff  --git a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp 
b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
index 8a50cb27c8d3a..b432247bad7d8 100644
--- a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -345,6 +345,16 @@ class RegionStoreManager : public StoreManager {
   /// To disable all small-struct-dependent behavior, set the option to "0".
   unsigned SmallStructLimit;
 
+  /// The largest number of element an array can have and still be
+  /// considered "small".
+  ///
+  /// This is currently used to decide whether or not it is worth "forcing" a
+  /// LazyCompoundVal on bind.
+  ///
+  /// This is controlled by 'region-store-small-struct-limit' option.
+  /// To disable all small-struct-dependent behavior, set the option to "0".
+  unsigned SmallArrayLimit;
+
   /// A helper used to populate the work list with the given set of
   /// regions.
   void populateWorkList(InvalidateRegionsWorker &W,
@@ -354,10 +364,11 @@ class RegionStoreManager : public StoreManager {
 public:
   RegionStoreManager(ProgramStateManager &mgr)
   : StoreManager(mgr), RBFactory(mgr.getAllocator()),
-CBFactory(mgr.getAllocator()), SmallStructLimit(0) {
+CBFactory(mgr.getAllocator()), SmallStructLimit(0), SmallArrayLimit(0) 
{
 ExprEngine &Eng = StateMgr.getOwningEngine();
 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
 SmallStructLimit = Options.RegionStoreSmallStructLimit;
+SmallArrayLimit = Options.RegionStoreSmallArrayLimit;
   }
 
   /// setImplicitDefaultValue - Set the default binding for the provided
@@ -487,6 +498,11 @@ class RegionStoreManager : public StoreManager {
   RegionBindingsRef bindVector(RegionBindingsConstRef B,
const TypedValueRegion* R, SVal V);
 
+  Optional tryBindSmallArray(RegionBindingsConstRef B,
+const TypedValueRegion *R,
+const ArrayType *AT,
+nonloc::LazyCompoundVal LCV);
+
   RegionBindingsRef bindArray(RegionBindingsConstRef B,
   const TypedValueRegion* R,
   SVal V);
@@ -2392,6 +2408,40 @@ 
RegionStoreManager::setImplicitDefaultValue(RegionBindingsConstRef B,
   return B.addBinding(R, BindingKey::Default, V);
 }
 
+Optional RegionStoreManager::tryBindSmallArray(
+RegionBindingsConstRef B, const TypedValueRegion *R, const ArrayType *AT,
+nonloc::LazyCompoundVal LCV) {
+
+  auto CAT = dyn_cast(AT);
+
+  // If we don't know the size, create a lazyCompoundVal

[clang] e77ac66 - [Static Analyzer] Structured binding to data members

2022-06-17 Thread via cfe-commits

Author: isuckatcs
Date: 2022-06-17T19:50:10+02:00
New Revision: e77ac66b8c1cf4f09f931d37749ed258f122d708

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

LOG: [Static Analyzer] Structured binding to data members

Introducing structured binding to data members.

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

Added: 
clang/test/Analysis/uninit-structured-binding-struct.cpp

Modified: 
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index a0c7dda896ef2..6ba19d52488c7 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2591,9 +2591,22 @@ void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, 
const NamedDecl *D,
 // operator&.
 return;
   }
-  if (isa(D)) {
-// FIXME: proper support for bound declarations.
-// For now, let's just prevent crashing.
+  if (const auto *BD = dyn_cast(D)) {
+const auto *DD = cast(BD->getDecomposedDecl());
+
+if (const auto *ME = dyn_cast(BD->getBinding())) {
+  const auto *Field = cast(ME->getMemberDecl());
+
+  SVal Base = state->getLValue(DD, LCtx);
+  if (DD->getType()->isReferenceType()) {
+Base = state->getSVal(Base.getAsRegion());
+  }
+
+  SVal V = state->getLValue(Field, Base);
+
+  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
+}
+
 return;
   }
 

diff  --git a/clang/test/Analysis/uninit-structured-binding-struct.cpp 
b/clang/test/Analysis/uninit-structured-binding-struct.cpp
new file mode 100644
index 0..fec82c0d8589d
--- /dev/null
+++ b/clang/test/Analysis/uninit-structured-binding-struct.cpp
@@ -0,0 +1,116 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection 
-std=c++17 -verify %s
+
+void clang_analyzer_eval(bool);
+
+struct s {
+  int a;
+  int b;
+};
+
+void a(void) {
+  s tst;
+
+  auto [i, j] = tst;
+
+  int x = i; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void b(void) {
+  s tst;
+  tst.a = 1;
+
+  auto [i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+  int y = j;   // expected-warning{{Assigned value is garbage 
or undefined}}
+}
+
+void c(void) {
+  s tst;
+
+  auto &[i, j] = tst;
+
+  int x = i; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void d(void) {
+  s tst;
+  tst.a = 1;
+
+  auto &[i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+  i = 2;
+  clang_analyzer_eval(tst.a == 2); // expected-warning{{TRUE}}
+
+  int y = j; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void e(void) {
+  s tst;
+  tst.a = 1;
+
+  auto &[i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+
+  tst.b = 2;
+  clang_analyzer_eval(j == 2); // expected-warning{{TRUE}}
+}
+
+void f(void) {
+  s tst;
+
+  auto &&[i, j] = tst;
+
+  int x = i; // expected-warning{{Assigned value is garbage or undefined}}
+}
+
+void g(void) {
+  s tst;
+  tst.a = 1;
+
+  auto &&[i, j] = tst;
+
+  clang_analyzer_eval(i == 1); // expected-warning{{TRUE}}
+  int y = j;   // expected-warning{{Assigned value is garbage 
or undefined}}
+}
+
+struct s2 {
+  int a = 1;
+  int b = 2;
+};
+
+struct s3 {
+  s x;
+  s2 y;
+};
+
+void h(void) {
+  s3 tst;
+
+  clang_analyzer_eval(tst.y.a == 1); // expected-warning{{TRUE}}
+
+  auto [i, j] = tst;
+
+  // FIXME: These should be undefined, but we have to fix
+  // reading undefined from lazy compound values first.
+  clang_analyzer_eval(i.a); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(i.b); // expected-warning{{UNKNOWN}}
+
+  clang_analyzer_eval(j.a == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(j.b == 2); // expected-warning{{TRUE}}
+}
+
+void i(void) {
+  s3 tst;
+
+  clang_analyzer_eval(tst.y.a == 1); // expected-warning{{TRUE}}
+
+  auto &[i, j] = tst;
+  j.a = 3;
+
+  clang_analyzer_eval(tst.y.a == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(tst.y.b == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(j.b == 2); // expected-warning{{TRUE}}
+}



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


[clang-tools-extra] b967a97 - [clang-tidy] Fix documentation (NFC)

2022-06-22 Thread via cfe-commits

Author: Richard
Date: 2022-06-22T10:49:00-06:00
New Revision: b967a9755064b9d494523c7991fd995bc14f7b4c

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

LOG: [clang-tidy] Fix documentation (NFC)

The documentation files were reorganized into subdirectories, but a new
check was added concurrently and wasn't rebased correctly before
submitting.  Sort the new clang-tidy checks by check name and fix the
indentation of bugprone-unchecked-optional-access.

Added: 
clang-tools-extra/docs/clang-tidy/checks/misc/confusable-identifiers.rst

Modified: 
clang-tools-extra/docs/ReleaseNotes.rst

Removed: 
clang-tools-extra/docs/clang-tidy/checks/misc-confusable-identifiers.rst



diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 15d142af8d34e..ec7b44405310d 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -123,8 +123,12 @@ New checks
 - New :doc:`bugprone-unchecked-optional-access
   ` check.
 
-   Warns when the code is unwrapping a `std::optional`, `absl::optional`,
-   or `base::Optional` object without assuring that it contains a value.
+  Warns when the code is unwrapping a `std::optional`, `absl::optional`,
+  or `base::Optional` object without assuring that it contains a value.
+
+- New :doc:`misc-confusable-identifiers 
` check.
+
+  Detects confusable Unicode identifiers.
 
 - New :doc:`modernize-macro-to-enum
   ` check.
@@ -139,10 +143,6 @@ New checks
   Future libc++ will remove the extension (`D120996
   `).
 
-- New :doc:`misc-confusable-identifiers 
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 8ef6280 - [analyzer] Structured binding to arrays

2022-06-23 Thread via cfe-commits

Author: isuckatcs
Date: 2022-06-23T11:38:21+02:00
New Revision: 8ef628088b54aebd4a8317ce3a0029e3283b3aa0

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

LOG: [analyzer] Structured binding to arrays

Introducing structured binding to data members and more.
To handle binding to arrays, ArrayInitLoopExpr is also
evaluated, which enables the analyzer to store information
in two more cases. These are:
  - when a lambda-expression captures an array by value
  - in the implicit copy/move constructor for a class
with an array member

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

Added: 
clang/test/Analysis/array-init-loop.cpp
clang/test/Analysis/uninit-structured-binding-array.cpp

Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
index 3787f8f01b34e..415fa05586edf 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -444,6 +444,10 @@ class ExprEngine {
   ///  other functions that handle specific kinds of statements.
   void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst);
 
+  /// VisitArrayInitLoopExpr - Transfer function for array init loop.
+  void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *Ex, ExplodedNode *Pred,
+  ExplodedNodeSet &Dst);
+
   /// VisitArraySubscriptExpr - Transfer function for array accesses.
   void VisitArraySubscriptExpr(const ArraySubscriptExpr *Ex,
ExplodedNode *Pred,

diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index 6ba19d52488c7..b4837cb95e183 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -1363,10 +1363,14 @@ void ExprEngine::Visit(const Stmt *S, ExplodedNode 
*Pred,
   break;
 }
 
+case Stmt::ArrayInitLoopExprClass:
+  Bldr.takeNodes(Pred);
+  VisitArrayInitLoopExpr(cast(S), Pred, Dst);
+  Bldr.addNodes(Dst);
+  break;
 // Cases not handled yet; but will handle some day.
 case Stmt::DesignatedInitExprClass:
 case Stmt::DesignatedInitUpdateExprClass:
-case Stmt::ArrayInitLoopExprClass:
 case Stmt::ArrayInitIndexExprClass:
 case Stmt::ExtVectorElementExprClass:
 case Stmt::ImaginaryLiteralClass:
@@ -2594,18 +2598,38 @@ void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, 
const NamedDecl *D,
   if (const auto *BD = dyn_cast(D)) {
 const auto *DD = cast(BD->getDecomposedDecl());
 
+SVal Base = state->getLValue(DD, LCtx);
+if (DD->getType()->isReferenceType()) {
+  Base = state->getSVal(Base.getAsRegion());
+}
+
+SVal V = UnknownVal();
+
+// Handle binding to data members
 if (const auto *ME = dyn_cast(BD->getBinding())) {
   const auto *Field = cast(ME->getMemberDecl());
+  V = state->getLValue(Field, Base);
+}
+// Handle binding to arrays
+else if (const auto *ASE = dyn_cast(BD->getBinding())) 
{
+  SVal Idx = state->getSVal(ASE->getIdx(), LCtx);
 
-  SVal Base = state->getLValue(DD, LCtx);
-  if (DD->getType()->isReferenceType()) {
-Base = state->getSVal(Base.getAsRegion());
-  }
-
-  SVal V = state->getLValue(Field, Base);
+  // Note: the index of an element in a structured binding is automatically
+  // created and it is a unique identifier of the specific element. Thus it
+  // cannot be a value that varies at runtime.
+  assert(Idx.isConstant() && "BindingDecl array index is not a constant!");
 
-  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
+  V = state->getLValue(BD->getType(), Idx, Base);
 }
+// Handle binding to tuple-like strcutures
+else if (BD->getHoldingVar()) {
+  // FIXME: handle tuples
+  return;
+} else
+  llvm_unreachable("An unknown case of structured binding encountered!");
+
+Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
+  ProgramPoint::PostLValueKind);
 
 return;
   }
@@ -2613,6 +2637,99 @@ void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, 
const NamedDecl *D,
   llvm_unreachable("Support for this Decl not implemented.");
 }
 
+/// VisitArrayInitLoopExpr - Transfer function for array init loop.
+void ExprEngine::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *Ex,
+ExplodedNode *Pred,
+ExplodedNodeSet &Dst) {
+  ExplodedNodeSet Check

[clang] 886715a - [clang] Introduce -fstrict-flex-arrays= for stricter handling of flexible arrays

2022-06-24 Thread via cfe-commits

Author: serge-sans-paille
Date: 2022-06-24T16:13:29+02:00
New Revision: 886715af962de2c92fac4bd37104450345711e4a

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

LOG: [clang] Introduce -fstrict-flex-arrays= for stricter handling of 
flexible arrays

Some code [0] consider that trailing arrays are flexible, whatever their size.
Support for these legacy code has been introduced in
f8f632498307d22e10fab0704548b270b15f1e1e but it prevents evaluation of
__builtin_object_size and __builtin_dynamic_object_size in some legit cases.

Introduce -fstrict-flex-arrays= to have stricter conformance when it is
desirable.

n = 0: current behavior, any trailing array member is a flexible array. The 
default.
n = 1: any trailing array member of undefined, 0 or 1 size is a flexible array 
member
n = 2: any trailing array member of undefined or 0 size is a flexible array 
member
n = 3: any trailing array member of undefined size is a flexible array member 
(strict c99 conformance)

Similar patch for gcc discuss here: 
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=101836

[0] 
https://docs.freebsd.org/en/books/developers-handbook/sockets/#sockets-essential-functions

Added: 
clang/test/CodeGen/object-size-flex-array.c
clang/test/SemaCXX/array-bounds-strict-flex-arrays.cpp

Modified: 
clang/docs/ClangCommandLineReference.rst
clang/docs/ReleaseNotes.rst
clang/include/clang/AST/Expr.h
clang/include/clang/Basic/LangOptions.def
clang/include/clang/Driver/Options.td
clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
clang/lib/AST/Expr.cpp
clang/lib/AST/ExprConstant.cpp
clang/lib/CodeGen/CGExpr.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Sema/SemaChecking.cpp
clang/lib/StaticAnalyzer/Core/MemRegion.cpp
clang/test/CodeGen/bounds-checking.c
clang/test/CodeGenObjC/ubsan-array-bounds.m
clang/test/Sema/array-bounds-ptr-arith.c

Removed: 




diff  --git a/clang/docs/ClangCommandLineReference.rst 
b/clang/docs/ClangCommandLineReference.rst
index 7e53f45c59689..17892e3461707 100644
--- a/clang/docs/ClangCommandLineReference.rst
+++ b/clang/docs/ClangCommandLineReference.rst
@@ -2639,6 +2639,12 @@ Enable unstable and experimental features
 
 .. option:: -fuse-init-array, -fno-use-init-array
 
+.. option:: -fstrict-flex-arrays=, -fno-strict-flex-arrays
+
+Control which arrays are considered as flexible arrays members. 
+can be 1 (array of size 0, 1 and undefined are considered), 2 (array of size 0
+and undefined are considered) or 3 (only array of undefined size are 
considered).
+
 .. option:: -fuse-ld=
 
 .. option:: -fuse-line-directives, -fno-use-line-directives

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6b4616d43bc29..1b0bd5e52b8fb 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -68,6 +68,11 @@ Major New Features
 
   Randomizing structure layout is a C-only feature.
 
+- Clang now supports the ``-fstrict-flex-arrays=`` option to control which
+  array bounds lead to flexible array members. The option yields more accurate
+  ``__builtin_object_size`` and ``__builtin_dynamic_object_size`` results in
+  most cases but may be overly conservative for some legacy code.
+
 Bug Fixes
 -
 - ``CXXNewExpr::getArraySize()`` previously returned a ``llvm::Optional``

diff  --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 574d2fad216ea..392c5bcb1e20a 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -443,6 +443,16 @@ class Expr : public ValueStmt {
 return (OK == OK_Ordinary || OK == OK_BitField);
   }
 
+  /// True when this expression refers to a flexible array member in a
+  /// struct. \c StrictFlexArraysLevel controls which array bounds are
+  /// acceptable for such arrays:
+  ///
+  /// - 0 => any array bound,
+  /// - 1 => [0], [1], [ ]
+  /// - 2 => [0], [ ]
+  /// - 3 => [ ]
+  bool isFlexibleArrayMember(ASTContext &Ctx, int StrictFlexArraysLevel) const;
+
   /// setValueKind - Set the value kind produced by this expression.
   void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
 

diff  --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c41b5ddc7fa11..ba6ce4e9250f4 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -424,6 +424,7 @@ LANGOPT(PaddingOnUnsignedFixedPoint, 1, 0,
 LANGOPT(RegisterStaticDestructors, 1, 1, "Register C++ static destructors")
 
 LANGOPT(MatrixTypes, 1, 0, "Enable or disable the builtin matrix type")
+LANGOPT(StrictFlexArrays, 2, 0, "Rely on strict definition of flexible arrays")
 
 COMPATIBLE_VALUE_LANGOPT(MaxTokens, 32, 0, "Max number of tokens p

[clang-tools-extra] 5e97788 - [clang-tidy] Update release notes (NFC)

2022-06-24 Thread via cfe-commits

Author: Richard
Date: 2022-06-24T10:48:47-06:00
New Revision: 5e97788a3eca62aa80cf42bdc697e93838554cda

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

LOG: [clang-tidy] Update release notes (NFC)

- Sort changes to existing checks by check name
- Correct check link

Added: 


Modified: 
clang-tools-extra/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 0d3f973c3bdeb..f148884e90c5d 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -165,6 +165,15 @@ Changes in existing checks
   ` when `sizeof(...)` is
   compared against a `__int128_t`.
 
+- Fixed bugs in :doc:`bugprone-use-after-move
+  `:
+
+  - Treat a move in a lambda capture as happening in the function that defines
+the lambda, not within the body of the lambda (as we were previously doing
+erroneously).
+
+  - Don't emit an erroneous warning on self-moves.
+
 - Made :doc:`cert-oop57-cpp ` more sensitive
   by checking for an arbitrary expression in the second argument of ``memset``.
 
@@ -210,6 +219,10 @@ Changes in existing checks
   ` to work when
   the vector is a member of a structure.
 
+- Fixed a crash in :doc:`performance-unnecessary-value-param
+  ` when the 
specialization
+  template has an unnecessary value parameter. Removed the fix for a template.
+
 - Fixed a crash in :doc:`readability-const-return-type
   ` when a pure virtual 
function
   overrided has a const return type. Removed the fix for a virtual function.
@@ -225,19 +238,6 @@ Changes in existing checks
   ` to simplify 
expressions
   using DeMorgan's Theorem.
 
-- Fixed a crash in :doc:`performance-unnecessary-value-param
-  ` when the 
specialization
-  template has an unnecessary value parameter. Removed the fix for a template.
-
-- Fixed bugs in :doc:`bugprone-use-after-move
-  `:
-
-  - Treat a move in a lambda capture as happening in the function that defines
-the lambda, not within the body of the lambda (as we were previously doing
-erroneously).
-
-  - Don't emit an erroneous warning on self-moves.
-
 Removed checks
 ^^
 



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


[clang] 1f69f7e - [clang-format] NFC Sort names of format token types

2022-06-25 Thread via cfe-commits

Author: sstwcw
Date: 2022-06-25T12:09:49Z
New Revision: 1f69f7ea9af4bd4e8001a25044aa026557f366f7

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

LOG: [clang-format] NFC Sort names of format token types

Suggested by HazardyKnusperkeks in D126845.

Reviewed By: HazardyKnusperkeks, owenpan

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

Added: 


Modified: 
clang/lib/Format/FormatToken.h

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 71acdf2f094ba..145ae39ddb62c 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -46,6 +46,13 @@ namespace format {
   /* l_brace of if/for/while */
\
   TYPE(ControlStatementLBrace) 
\
   TYPE(CppCastLParen)  
\
+  TYPE(CSharpGenericTypeConstraint)
\
+  TYPE(CSharpGenericTypeConstraintColon)   
\
+  TYPE(CSharpGenericTypeConstraintComma)   
\
+  TYPE(CSharpNamedArgumentColon)   
\
+  TYPE(CSharpNullable) 
\
+  TYPE(CSharpNullConditionalLSquare)   
\
+  TYPE(CSharpStringLiteral)
\
   TYPE(CtorInitializerColon)   
\
   TYPE(CtorInitializerComma)   
\
   TYPE(DesignatedInitializerLSquare)   
\
@@ -68,6 +75,7 @@ namespace format {
   TYPE(InlineASMColon) 
\
   TYPE(InlineASMSymbolicNameLSquare)   
\
   TYPE(JavaAnnotation) 
\
+  TYPE(JsAndAndEqual)  
\
   TYPE(JsComputedPropertyName) 
\
   TYPE(JsExponentiation)   
\
   TYPE(JsExponentiationEqual)  
\
@@ -76,7 +84,6 @@ namespace format {
   TYPE(JsTypeColon)
\
   TYPE(JsTypeOperator) 
\
   TYPE(JsTypeOptionalQuestion) 
\
-  TYPE(JsAndAndEqual)  
\
   TYPE(LambdaArrow)
\
   TYPE(LambdaLBrace)   
\
   TYPE(LambdaLSquare)  
\
@@ -101,6 +108,7 @@ namespace format {
   TYPE(OverloadedOperator) 
\
   TYPE(OverloadedOperatorLParen)   
\
   TYPE(PointerOrReference) 
\
+  TYPE(ProtoExtensionLSquare)  
\
   TYPE(PureVirtualSpecifier)   
\
   TYPE(RangeBasedForLoopColon) 
\
   TYPE(RecordLBrace)   
\
@@ -119,7 +127,6 @@ namespace format {
   TYPE(TemplateCloser) 
\
   TYPE(TemplateOpener) 
\
   TYPE(TemplateString) 
\
-  TYPE(ProtoExtensionLSquare)  
\
   TYPE(TrailingAnnotation) 
\
   TYPE(TrailingReturnArrow)
\
   TYPE(TrailingUnaryOperator)  
\
@@ -128,13 +135,6 @@ namespace format {
   TYPE(UnaryOperator)  
\
   TYPE(UnionLBrace)
\
   TYPE(UntouchableMacroFunc)   
\
-  TYPE(CSharpStringLiteral)
\
-  TYPE(CSharpNamedArgumentColon)   
\
-  TYPE(CSharpNullable) 
\
-  TYPE(CSharpNullConditi

[clang-tools-extra] b2cb7e8 - [clang-tidy] cppcoreguidelines-virtual-class-destructor: Fix crash when "virtual" keyword is expanded from a macro

2022-06-25 Thread via cfe-commits

Author: Joachim Priesner
Date: 2022-06-25T15:50:13-06:00
New Revision: b2cb7e81f8978ccce5c5e7b316480b88785ca9cc

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

LOG: [clang-tidy] cppcoreguidelines-virtual-class-destructor: Fix crash when 
"virtual" keyword is expanded from a macro

Check llvm::Optional before dereferencing it.

Compute VirtualEndLoc differently to avoid an assertion failure
in clang::SourceManager::getFileIDLoaded:

Assertion `0 && "Invalid SLocOffset or bad function choice"' failed

Added: 


Modified: 

clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp

clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/virtual-class-destructor.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp
 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp
index e730fb6fa01d..92b38bcfd81d 100644
--- 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp
@@ -54,13 +54,17 @@ getVirtualKeywordRange(const CXXDestructorDecl &Destructor,
 return None;
 
   SourceLocation VirtualBeginLoc = Destructor.getBeginLoc();
-  SourceLocation VirtualEndLoc = VirtualBeginLoc.getLocWithOffset(
-  Lexer::MeasureTokenLength(VirtualBeginLoc, SM, LangOpts));
+  SourceLocation VirtualBeginSpellingLoc =
+  SM.getSpellingLoc(Destructor.getBeginLoc());
+  SourceLocation VirtualEndLoc = VirtualBeginSpellingLoc.getLocWithOffset(
+  Lexer::MeasureTokenLength(VirtualBeginSpellingLoc, SM, LangOpts));
 
   /// Range ends with \c StartOfNextToken so that any whitespace after \c
   /// virtual is included.
-  SourceLocation StartOfNextToken =
-  Lexer::findNextToken(VirtualEndLoc, SM, LangOpts)->getLocation();
+  Optional NextToken = Lexer::findNextToken(VirtualEndLoc, SM, 
LangOpts);
+  if (!NextToken)
+return None;
+  SourceLocation StartOfNextToken = NextToken->getLocation();
 
   return CharSourceRange::getCharRange(VirtualBeginLoc, StartOfNextToken);
 }

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/virtual-class-destructor.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/virtual-class-destructor.cpp
index fcf558dcac8e..61e565075b15 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/virtual-class-destructor.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/virtual-class-destructor.cpp
@@ -272,6 +272,7 @@ DerivedFromTemplateNonVirtualBaseStruct2Typedef 
InstantiationWithPublicNonVirtua
 } // namespace Bugzilla_51912
 
 namespace macro_tests {
+#define MY_VIRTUAL virtual
 #define CONCAT(x, y) x##y
 
 // CHECK-MESSAGES: :[[@LINE+2]]:7: warning: destructor of 'FooBar1' is 
protected and virtual [cppcoreguidelines-virtual-class-destructor]
@@ -317,8 +318,17 @@ class FooBar5 {
 protected:
   XMACRO(CONCAT(vir, tual), ~CONCAT(Foo, Bar5());) // no-crash, no-fixit
 };
+
+// CHECK-MESSAGES: :[[@LINE+2]]:7: warning: destructor of 'FooBar6' is 
protected and virtual [cppcoreguidelines-virtual-class-destructor]
+// CHECK-MESSAGES: :[[@LINE+1]]:7: note: make it protected and non-virtual
+class FooBar6 {
+protected:
+  MY_VIRTUAL ~FooBar6(); // FIXME: We should have a fixit for this.
+};
+
 #undef XMACRO
 #undef CONCAT
+#undef MY_VIRTUAL
 } // namespace macro_tests
 
 namespace FinalClassCannotBeBaseClass {



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


[clang] 370bee4 - [clang-format] Fix whitespace counting stuff

2022-06-25 Thread via cfe-commits

Author: sstwcw
Date: 2022-06-26T01:27:27Z
New Revision: 370bee480139bd37fe8c0c8c03ecd19ed9223f01

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

LOG: [clang-format] Fix whitespace counting stuff

The current way of counting whitespace would count backticks as
whitespace.  For Verilog stuff we need backticks to be handled
correctly.  For JavaScript the current way is to compare the entire
token text to see if it's a backtick.  However, when the backtick is the
first token following an escaped newline, the escaped newline will be
part of the tok::unknown token.  Verilog has macros and escaped newlines
unlike JavaScript.  So we can't regard an entire tok::unknown token as
whitespace.  Previously, the start of every token would be matched for
newlines.  Now, it is all whitespace instead of just newlines.

The column counting problem has already been fixed for JavaScript in
e71b4cbdd140f059667f84464bd0ac0ebc348387 by counting columns elsewhere.

Reviewed By: HazardyKnusperkeks

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

Added: 


Modified: 
clang/lib/Format/FormatTokenLexer.cpp
clang/lib/Format/FormatTokenLexer.h

Removed: 




diff  --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index 214a52780888b..8aee794b3f4f7 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -840,6 +840,56 @@ FormatToken *FormatTokenLexer::getStashedToken() {
   return FormatTok;
 }
 
+/// Truncate the current token to the new length and make the lexer continue
+/// from the end of the truncated token. Used for other languages that have
+/// 
diff erent token boundaries, like JavaScript in which a comment ends at a
+/// line break regardless of whether the line break follows a backslash. Also
+/// used to set the lexer to the end of whitespace if the lexer regards
+/// whitespace and an unrecognized symbol as one token.
+void FormatTokenLexer::truncateToken(size_t NewLen) {
+  assert(NewLen <= FormatTok->TokenText.size());
+  resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(
+  Lex->getBufferLocation() - FormatTok->TokenText.size() + NewLen)));
+  FormatTok->TokenText = FormatTok->TokenText.substr(0, NewLen);
+  FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
+  FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
+  Encoding);
+  FormatTok->Tok.setLength(NewLen);
+}
+
+/// Count the length of leading whitespace in a token.
+static size_t countLeadingWhitespace(StringRef Text) {
+  // Basically counting the length matched by this regex.
+  // "^([\n\r\f\v \t]|(|\\?\\?/)[\n\r])+"
+  // Directly using the regex turned out to be slow. With the regex
+  // version formatting all files in this directory took about 1.25
+  // seconds. This version took about 0.5 seconds.
+  const char *Cur = Text.begin();
+  while (Cur < Text.end()) {
+if (isspace(Cur[0])) {
+  ++Cur;
+} else if (Cur[0] == '\\' && (Cur[1] == '\n' || Cur[1] == '\r')) {
+  // A '\' followed by a newline always escapes the newline, regardless
+  // of whether there is another '\' before it.
+  // The source has a null byte at the end. So the end of the entire input
+  // isn't reached yet. Also the lexer doesn't break apart an escaped
+  // newline.
+  assert(Text.end() - Cur >= 2);
+  Cur += 2;
+} else if (Cur[0] == '?' && Cur[1] == '?' && Cur[2] == '/' &&
+   (Cur[3] == '\n' || Cur[3] == '\r')) {
+  // Newlines can also be escaped by a '?' '?' '/' trigraph. By the way, 
the
+  // characters are quoted individually in this comment because if we write
+  // them together some compilers warn that we have a trigraph in the code.
+  assert(Text.end() - Cur >= 4);
+  Cur += 4;
+} else {
+  break;
+}
+  }
+  return Cur - Text.begin();
+}
+
 FormatToken *FormatTokenLexer::getNextToken() {
   if (StateStack.top() == LexerState::TOKEN_STASHED) {
 StateStack.pop();
@@ -854,34 +904,33 @@ FormatToken *FormatTokenLexer::getNextToken() {
   IsFirstToken = false;
 
   // Consume and record whitespace until we find a significant token.
+  // Some tok::unknown tokens are not just whitespace, e.g. whitespace
+  // followed by a symbol such as backtick. Those symbols may be
+  // significant in other languages.
   unsigned WhitespaceLength = TrailingWhitespace;
-  while (FormatTok->is(tok::unknown)) {
+  while (FormatTok->isNot(tok::eof)) {
+auto LeadingWhitespace = countLeadingWhitespace(FormatTok->TokenText);
+if (LeadingWhitespace == 0)
+  break;
+if (LeadingWhitespace < FormatTok->TokenText.size())
+  truncateToken(LeadingWhitespace);
 StringRef Text = FormatTok->TokenText;
-auto EscapesNewline = [&

[clang] 9ed2e68 - [clang-format] Parse Verilog if statements

2022-06-25 Thread via cfe-commits

Author: sstwcw
Date: 2022-06-26T01:52:15Z
New Revision: 9ed2e68c9ae5cf346f938cc095e5448c1ff60f51

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

LOG: [clang-format] Parse Verilog if statements

This patch mainly handles treating `begin` as block openers.

While and for statements will be handled in another patch.

Reviewed By: HazardyKnusperkeks

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

Added: 
clang/unittests/Format/FormatTestVerilog.cpp

Modified: 
clang/docs/ClangFormat.rst
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/lib/Format/FormatToken.h
clang/lib/Format/UnwrappedLineParser.cpp
clang/tools/clang-format/ClangFormat.cpp
clang/unittests/Format/CMakeLists.txt
clang/unittests/Format/FormatTestUtils.h

Removed: 




diff  --git a/clang/docs/ClangFormat.rst b/clang/docs/ClangFormat.rst
index 745c66efa9e0e..16b316cdf0667 100644
--- a/clang/docs/ClangFormat.rst
+++ b/clang/docs/ClangFormat.rst
@@ -43,6 +43,17 @@ to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# 
code.
 --assume-filename= - Override filename used to determine the 
language.
  When reading from stdin, clang-format 
assumes this
  filename to determine the language.
+ Unrecognized filenames are treated as C++.
+ supported:
+   CSharp: .cs
+   Java: .java
+   JavaScript: .mjs .js .ts
+   Json: .json
+   Objective-C: .m .mm
+   Proto: .proto .protodevel
+   TableGen: .td
+   TextProto: .textpb .pb.txt .textproto 
.asciipb
+   Verilog: .sv .svh .v .vh
 --cursor=- The position of the cursor when invoking
  clang-format from an editor integration
 --dry-run  - If set, do not actually make the 
formatting changes

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 8249060dc7c04..f8a4b069b2e75 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -2589,12 +2589,17 @@ struct FormatStyle {
 LK_TableGen,
 /// Should be used for Protocol Buffer messages in text format
 /// (https://developers.google.com/protocol-buffers/).
-LK_TextProto
+LK_TextProto,
+/// Should be used for Verilog and SystemVerilog.
+/// https://standards.ieee.org/ieee/1800/6700/
+/// https://sci-hub.st/10.1109/IEEESTD.2018.8299595
+LK_Verilog
   };
   bool isCpp() const { return Language == LK_Cpp || Language == LK_ObjC; }
   bool isCSharp() const { return Language == LK_CSharp; }
   bool isJson() const { return Language == LK_Json; }
   bool isJavaScript() const { return Language == LK_JavaScript; }
+  bool isVerilog() const { return Language == LK_Verilog; }
 
   /// Language, this format style is targeted at.
   /// \version 3.5
@@ -4285,6 +4290,8 @@ inline StringRef 
getLanguageName(FormatStyle::LanguageKind Language) {
 return "TableGen";
   case FormatStyle::LK_TextProto:
 return "TextProto";
+  case FormatStyle::LK_Verilog:
+return "Verilog";
   default:
 return "Unknown";
   }

diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index df1aa9da16e39..51526dc2a6817 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3471,6 +3471,12 @@ static FormatStyle::LanguageKind 
getLanguageByFileName(StringRef FileName) {
 return FormatStyle::LK_CSharp;
   if (FileName.endswith_insensitive(".json"))
 return FormatStyle::LK_Json;
+  if (FileName.endswith_insensitive(".sv") ||
+  FileName.endswith_insensitive(".svh") ||
+  FileName.endswith_insensitive(".v") ||
+  FileName.endswith_insensitive(".vh")) {
+return FormatStyle::LK_Verilog;
+  }
   return FormatStyle::LK_Cpp;
 }
 

diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 145ae39ddb62c..92fa0798f699e 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -979,6 +979,118 @@ struct AdditionalKeywords {
 kw_when = &IdentTable.get("when");
 kw_where = &IdentTable.get("where");
 
+kw_always = &IdentTable.get("always");
+kw_always_comb = &IdentTable.get("always_comb");
+kw_always_ff = &IdentTable.get("always_ff");
+kw_always_latch = &IdentTable.get("always_latch");
+kw_assign = &IdentTable.get("as

[clang] 2e32ff1 - [clang-format] Handle Verilog preprocessor directives

2022-06-25 Thread via cfe-commits

Author: sstwcw
Date: 2022-06-26T02:02:29Z
New Revision: 2e32ff106e740c76601004493816d0ed7c483056

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

LOG: [clang-format] Handle Verilog preprocessor directives

Verilog uses the backtick instead of the hash.  In this revision
backticks are lexed manually and then get labeled as hashes so the logic
for handling C preprocessor stuff don't have to change.  Hashes get
labeled as identifiers for Verilog-specific stuff like delays.

Reviewed By: HazardyKnusperkeks

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

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/FormatTokenLexer.cpp
clang/lib/Format/FormatTokenLexer.h
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestVerilog.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 92fa0798f699..b6cc021affae 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -988,6 +988,7 @@ struct AdditionalKeywords {
 kw_automatic = &IdentTable.get("automatic");
 kw_before = &IdentTable.get("before");
 kw_begin = &IdentTable.get("begin");
+kw_begin_keywords = &IdentTable.get("begin_keywords");
 kw_bins = &IdentTable.get("bins");
 kw_binsof = &IdentTable.get("binsof");
 kw_casex = &IdentTable.get("casex");
@@ -999,10 +1000,20 @@ struct AdditionalKeywords {
 kw_cover = &IdentTable.get("cover");
 kw_covergroup = &IdentTable.get("covergroup");
 kw_coverpoint = &IdentTable.get("coverpoint");
+kw_default_decay_time = &IdentTable.get("default_decay_time");
+kw_default_nettype = &IdentTable.get("default_nettype");
+kw_default_trireg_strength = &IdentTable.get("default_trireg_strength");
+kw_delay_mode_distributed = &IdentTable.get("delay_mode_distributed");
+kw_delay_mode_path = &IdentTable.get("delay_mode_path");
+kw_delay_mode_unit = &IdentTable.get("delay_mode_unit");
+kw_delay_mode_zero = &IdentTable.get("delay_mode_zero");
 kw_disable = &IdentTable.get("disable");
 kw_dist = &IdentTable.get("dist");
+kw_elsif = &IdentTable.get("elsif");
 kw_end = &IdentTable.get("end");
+kw_end_keywords = &IdentTable.get("end_keywords");
 kw_endcase = &IdentTable.get("endcase");
+kw_endcelldefine = &IdentTable.get("endcelldefine");
 kw_endchecker = &IdentTable.get("endchecker");
 kw_endclass = &IdentTable.get("endclass");
 kw_endclocking = &IdentTable.get("endclocking");
@@ -1043,6 +1054,7 @@ struct AdditionalKeywords {
 kw_macromodule = &IdentTable.get("macromodule");
 kw_matches = &IdentTable.get("matches");
 kw_medium = &IdentTable.get("medium");
+kw_nounconnected_drive = &IdentTable.get("nounconnected_drive");
 kw_output = &IdentTable.get("output");
 kw_packed = &IdentTable.get("packed");
 kw_parameter = &IdentTable.get("parameter");
@@ -1058,6 +1070,7 @@ struct AdditionalKeywords {
 kw_randcase = &IdentTable.get("randcase");
 kw_randsequence = &IdentTable.get("randsequence");
 kw_repeat = &IdentTable.get("repeat");
+kw_resetall = &IdentTable.get("resetall");
 kw_sample = &IdentTable.get("sample");
 kw_scalared = &IdentTable.get("scalared");
 kw_sequence = &IdentTable.get("sequence");
@@ -1073,12 +1086,15 @@ struct AdditionalKeywords {
 kw_table = &IdentTable.get("table");
 kw_tagged = &IdentTable.get("tagged");
 kw_task = &IdentTable.get("task");
+kw_timescale = &IdentTable.get("timescale");
 kw_tri = &IdentTable.get("tri");
 kw_tri0 = &IdentTable.get("tri0");
 kw_tri1 = &IdentTable.get("tri1");
 kw_triand = &IdentTable.get("triand");
 kw_trior = &IdentTable.get("trior");
 kw_trireg = &IdentTable.get("trireg");
+kw_unconnected_drive = &IdentTable.get("unconnected_drive");
+kw_undefineall = &IdentTable.get("undefineall");
 kw_unique = &IdentTable.get("unique");
 kw_unique0 = &IdentTable.get("unique0");
 kw_uwire = &IdentTable.get("uwire");
@@ -1091,6 +1107,10 @@ struct AdditionalKeywords {
 kw_with = &IdentTable.get("with");
 kw_wor = &IdentTable.get("wor");
 
+// Symbols that are treated as keywords.
+kw_verilogHash = &IdentTable.get("#");
+kw_verilogHashHash = &IdentTable.get("##");
+
 // Keep this at the end of the constructor to make sure everything here
 // is
 // already initialized.
@@ -1118,38 +1138,132 @@ struct AdditionalKeywords {
 // Some keywords are not included here because they don't need special
 // treatment like `showcancelled` or they should be treated as identifiers
 // like `int` and `logic`.
-VerilogExtraKeywords = std::unordered_set(
-{kw_

[clang] 282059b - Update LibASTImporter.rst

2022-06-26 Thread via cfe-commits

Author: Shivam
Date: 2022-06-26T19:22:52+05:30
New Revision: 282059b44d003a3e044bdc5c8884797f92bf2eab

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

LOG: Update LibASTImporter.rst

As my last commit changed the name of ImportError to ASTImportError , this 
section also needs to be updated so changed it.

Added: 


Modified: 
clang/docs/LibASTImporter.rst

Removed: 




diff  --git a/clang/docs/LibASTImporter.rst b/clang/docs/LibASTImporter.rst
index bedaf527f5e9..515eff7ebe33 100644
--- a/clang/docs/LibASTImporter.rst
+++ b/clang/docs/LibASTImporter.rst
@@ -468,7 +468,7 @@ Note, there may be several 
diff erent ASTImporter objects which import into the s
 cxxRecordDecl(hasName("Y"), isDefinition()), ToUnit);
 ToYDef->dump();
 // An error is set for "ToYDef" in the shared state.
-Optional OptErr =
+Optional OptErr =
 ImporterState->getImportDeclErrorIfAny(ToYDef);
 assert(OptErr);
 



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


[clang] 664ce34 - [clang-format] Quit analyzing solution space for large state count

2022-06-26 Thread via cfe-commits

Author: owenca
Date: 2022-06-26T13:15:07-07:00
New Revision: 664ce34e81d98af7859754f127b28030b45c8893

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

LOG: [clang-format] Quit analyzing solution space for large state count

Fixes #56043.

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineFormatter.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index b8a535b8d527f..22509a5042465 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -1163,6 +1163,10 @@ class OptimizingLineFormatter : public LineFormatter {
 
 // While not empty, take first element and follow edges.
 while (!Queue.empty()) {
+  // Quit if we still haven't found a solution by now.
+  if (Count > 2500)
+return 0;
+
   Penalty = Queue.top().first.first;
   StateNode *Node = Queue.top().second;
   if (!Node->State.NextToken) {



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


[clang] 141ad3b - [clang-format] Fix uninitialized memory problem

2022-06-26 Thread via cfe-commits

Author: sstwcw
Date: 2022-06-26T22:23:50Z
New Revision: 141ad3ba05711cc8396a34fce6b26648d216eb8e

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

LOG: [clang-format] Fix uninitialized memory problem

The setLength function checks for the token kind which could be
uninitialized in the previous version.

The problem was introduced in 2e32ff106e.

Reviewed By: MyDeveloperDay, owenpan

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

Added: 


Modified: 
clang/lib/Format/FormatTokenLexer.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index e3af9548b015..88b0d3b1970f 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -1128,11 +1128,12 @@ bool 
FormatTokenLexer::readRawTokenVerilogSpecific(Token &Tok) {
 return false;
   size_t Len = Matches[0].size();
 
-  Tok.setLength(Len);
-  Tok.setLocation(Lex->getSourceLocation(Start, Len));
   // The kind has to be an identifier so we can match it against those defined
-  // in Keywords.
+  // in Keywords. The kind has to be set before the length because the 
setLength
+  // function checks that the kind is not an annotation.
   Tok.setKind(tok::raw_identifier);
+  Tok.setLength(Len);
+  Tok.setLocation(Lex->getSourceLocation(Start, Len));
   Tok.setRawIdentifierData(Start);
   Lex->seek(Lex->getCurrentBufferOffset() + Len, /*IsAtStartofline=*/false);
   return true;



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


[clang] b646f09 - [clang-format] Fix misplacement of `*` in declaration of pointer to struct

2022-06-29 Thread via cfe-commits

Author: Huang Zhen-Hong
Date: 2022-06-29T15:21:02+08:00
New Revision: b646f0955574c6ad4c156c9db522e46f597cfda9

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

LOG: [clang-format] Fix misplacement of `*` in declaration of pointer to struct

Fixes #55810

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1ee95f26d1fc7..029cb9097871c 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2314,6 +2314,31 @@ class AnnotatingParser {
 if (NextToken->isOneOf(tok::comma, tok::semi))
   return TT_PointerOrReference;
 
+// After right braces, star tokens are likely to be pointers to struct,
+// union, or class.
+//   struct {} *ptr;
+if (PrevToken->is(tok::r_brace) && Tok.is(tok::star))
+  return TT_PointerOrReference;
+
+// For "} &&"
+if (PrevToken->is(tok::r_brace) && Tok.is(tok::ampamp)) {
+  const FormatToken *MatchingLBrace = PrevToken->MatchingParen;
+
+  // We check whether there is a TemplateCloser(">") to indicate it's a
+  // template or not. If it's not a template, "&&" is likely a reference
+  // operator.
+  //   struct {} &&ref = {};
+  if (!MatchingLBrace)
+return TT_PointerOrReference;
+  FormatToken *BeforeLBrace = MatchingLBrace->getPreviousNonComment();
+  if (!BeforeLBrace || BeforeLBrace->isNot(TT_TemplateCloser))
+return TT_PointerOrReference;
+
+  // If it is a template, "&&" is a binary operator.
+  //   enable_if<>{} && ...
+  return TT_BinaryOperator;
+}
+
 if (PrevToken->Tok.isLiteral() ||
 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
tok::kw_false, tok::r_brace)) {

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 972f3f195d856..d6deafe1093c8 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -10431,6 +10431,67 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   "void F();",
   getGoogleStyleWithColumns(68));
 
+  FormatStyle Style = getLLVMStyle();
+  Style.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("struct {\n"
+   "}* ptr;",
+   Style);
+  verifyFormat("union {\n"
+   "}* ptr;",
+   Style);
+  verifyFormat("class {\n"
+   "}* ptr;",
+   Style);
+  verifyFormat("struct {\n"
+   "}&& ptr = {};",
+   Style);
+  verifyFormat("union {\n"
+   "}&& ptr = {};",
+   Style);
+  verifyFormat("class {\n"
+   "}&& ptr = {};",
+   Style);
+
+  Style.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("struct {\n"
+   "} * ptr;",
+   Style);
+  verifyFormat("union {\n"
+   "} * ptr;",
+   Style);
+  verifyFormat("class {\n"
+   "} * ptr;",
+   Style);
+  verifyFormat("struct {\n"
+   "} && ptr = {};",
+   Style);
+  verifyFormat("union {\n"
+   "} && ptr = {};",
+   Style);
+  verifyFormat("class {\n"
+   "} && ptr = {};",
+   Style);
+
+  Style.PointerAlignment = FormatStyle::PAS_Right;
+  verifyFormat("struct {\n"
+   "} *ptr;",
+   Style);
+  verifyFormat("union {\n"
+   "} *ptr;",
+   Style);
+  verifyFormat("class {\n"
+   "} *ptr;",
+   Style);
+  verifyFormat("struct {\n"
+   "} &&ptr = {};",
+   Style);
+  verifyFormat("union {\n"
+   "} &&ptr = {};",
+   Style);
+  verifyFormat("class {\n"
+   "} &&ptr = {};",
+   Style);
+
   verifyIndependentOfContext("MACRO(int *i);");
   verifyIndependentOfContext("MACRO(auto *a);");
   verifyIndependentOfContext("MACRO(const A *a);");

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 2dbc5da07d4db..df1b052267478 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -85,6 +85,32 @@ TEST_F(TokenAnnotatorTest, UnderstandsUsesOfStarAndAmp) {
   Tokens = annotate("case &x:");
   EXPECT_EQ(Tokens.size(), 5u) << Tokens;
   EXPECT_TOKEN(Tokens[1], tok::amp, TT_UnaryOperator);
+
+  Tokens = annotate("struct {\n"
+"} *ptr;");
+  EXPECT_EQ(Tokens.size(), 7u) << Tokens;
+  EXPECT_TOK

[clang] 9d2e830 - [analyzer] Fix BindingDecl evaluation for reference types

2022-06-29 Thread via cfe-commits

Author: isuckatcs
Date: 2022-06-29T13:01:19+02:00
New Revision: 9d2e830737bcf8035cf263e4b4cb279b7b07cf24

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

LOG: [analyzer] Fix BindingDecl evaluation for reference types

The case when the bound variable is reference type in a
BindingDecl wasn't handled, which lead to false positives.

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/test/Analysis/structured_bindings.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index 1d99236a50379..b03d02640a87b 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2630,6 +2630,9 @@ void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, 
const NamedDecl *D,
 } else
   llvm_unreachable("An unknown case of structured binding encountered!");
 
+if (BD->getType()->isReferenceType())
+  V = state->getSVal(V.getAsRegion());
+
 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
   ProgramPoint::PostLValueKind);
 

diff  --git a/clang/test/Analysis/structured_bindings.cpp 
b/clang/test/Analysis/structured_bindings.cpp
index 3e8ff1c2aa6ab..7004c2e7dcf43 100644
--- a/clang/test/Analysis/structured_bindings.cpp
+++ b/clang/test/Analysis/structured_bindings.cpp
@@ -1,9 +1,32 @@
-// RUN: %clang_analyze_cc1 -std=c++17 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -std=c++17 
-analyzer-checker=core,debug.ExprInspection -verify %s
+
+void clang_analyzer_eval(bool);
 
 struct s { int a; };
 int foo() {
-auto[a] = s{1}; // FIXME: proper modelling
-if (a) {
-}
+  auto [a] = s{1};
+  clang_analyzer_eval(a == 1); // expected-warning{{TRUE}}
 } // expected-warning{{non-void function does not return a value}}
 
+struct s2 {
+  int &x;
+};
+
+int *foo2(s2 in) {
+  auto [a] = in;
+  return &a;
+}
+
+void bar() {
+  int i = 1;
+  s2 a{i};
+
+  auto *x = foo2(a);
+
+  clang_analyzer_eval(*x == i); // expected-warning{{TRUE}}
+
+  *x = 2;
+
+  clang_analyzer_eval(*x == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(i == 2);  // expected-warning{{TRUE}}
+}



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


[clang-tools-extra] c98b3a8 - Fix `performance-unnecessary-value-param` for template specialization

2022-05-29 Thread via cfe-commits

Author: Sockke
Date: 2022-05-30T09:55:53+08:00
New Revision: c98b3a8cd9856f2fcc7ba1f9ed9896b291bbab7b

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

LOG: Fix `performance-unnecessary-value-param` for template specialization

The checker missed a check for parameter type of primary template of 
specialization template and this could cause build breakages.

Reviewed By: aaron.ballman, flx

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param-delayed.cpp

clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp 
b/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
index ba2b89c291214..00f4b00f53819 100644
--- a/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
+++ b/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
@@ -51,18 +51,6 @@ bool hasLoopStmtAncestor(const DeclRefExpr &DeclRef, const 
Decl &Decl,
   return Matches.empty();
 }
 
-bool isExplicitTemplateSpecialization(const FunctionDecl &Function) {
-  if (const auto *SpecializationInfo = 
Function.getTemplateSpecializationInfo())
-if (SpecializationInfo->getTemplateSpecializationKind() ==
-TSK_ExplicitSpecialization)
-  return true;
-  if (const auto *Method = llvm::dyn_cast(&Function))
-if (Method->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
-Method->getMemberSpecializationInfo()->isExplicitSpecialization())
-  return true;
-  return false;
-}
-
 } // namespace
 
 UnnecessaryValueParamCheck::UnnecessaryValueParamCheck(
@@ -147,11 +135,12 @@ void UnnecessaryValueParamCheck::check(const 
MatchFinder::MatchResult &Result) {
   // 2. the function is virtual as it might break overrides
   // 3. the function is referenced outside of a call expression within the
   //compilation unit as the signature change could introduce build errors.
-  // 4. the function is an explicit template specialization.
+  // 4. the function is a primary template or an explicit template
+  // specialization.
   const auto *Method = llvm::dyn_cast(Function);
   if (Param->getBeginLoc().isMacroID() || (Method && Method->isVirtual()) ||
   isReferencedOutsideOfCallExpr(*Function, *Result.Context) ||
-  isExplicitTemplateSpecialization(*Function))
+  (Function->getTemplatedKind() != FunctionDecl::TK_NonTemplate))
 return;
   for (const auto *FunctionDecl = Function; FunctionDecl != nullptr;
FunctionDecl = FunctionDecl->getPreviousDecl()) {

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 787f535dedb64..5196c53291d19 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -202,6 +202,10 @@ Changes in existing checks
   ` to simplify 
expressions
   using DeMorgan's Theorem.
 
+- Fixed a crash in :doc:`performance-unnecessary-value-param
+  ` when the 
specialization
+  template has an unnecessary value paramter. Removed the fix for a template.
+
 Removed checks
 ^^
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param-delayed.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param-delayed.cpp
index 623bf8b30829e..53ec8713be338 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param-delayed.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param-delayed.cpp
@@ -69,7 +69,7 @@ struct PositiveConstValueConstructor {
 
 template  void templateWithNonTemplatizedParameter(const 
ExpensiveToCopyType S, T V) {
   // CHECK-MESSAGES: [[@LINE-1]]:90: warning: the const qualified parameter 'S'
-  // CHECK-FIXES: template  void 
templateWithNonTemplatizedParameter(const ExpensiveToCopyType& S, T V) {
+  // CHECK-FIXES-NOT: template  void 
templateWithNonTemplatizedParameter(const ExpensiveToCopyType& S, T V) {
 }
 
 void instantiated() {

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp
index f801494cf0ff5..d578eedd94a39 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s performance-unnecessary-value-param %t
+/

[clang-tools-extra] 3f3a235 - [clang-apply-replacements] Added an option to ignore insert conflict.

2022-05-29 Thread via cfe-commits

Author: Sockke
Date: 2022-05-30T13:02:25+08:00
New Revision: 3f3a235aa2e610b5ba393228a666d55a8135ef4a

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

LOG: [clang-apply-replacements] Added an option to ignore insert conflict.

If two different texts are inserted at the same offset, 
clang-apply-replacements prints the conflict error and discards all fixes. This 
patch adds support for adjusting conflict offset and keeps running to 
continually fix them.

https://godbolt.org/z/P938EGoxj doesn't have any fixes when I run 
run-clang-tidy.py to generate a YAML file with clang-tidy and fix them with 
clang-apply-replacements. The YAML file has two different header texts 
insertions at the same offset, unlike clang-tidy with '-fix', 
clang-apply-replacements does not adjust for this conflict.

Reviewed By: aaron.ballman

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

Added: 

clang-tools-extra/test/clang-apply-replacements/Inputs/ignore-conflict/file1.yaml

clang-tools-extra/test/clang-apply-replacements/Inputs/ignore-conflict/ignore-conflict.cpp
clang-tools-extra/test/clang-apply-replacements/ignore-conflict.cpp

Modified: 

clang-tools-extra/clang-apply-replacements/include/clang-apply-replacements/Tooling/ApplyReplacements.h
clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp

clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp
clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
clang/include/clang/Tooling/Refactoring/AtomicChange.h

Removed: 




diff  --git 
a/clang-tools-extra/clang-apply-replacements/include/clang-apply-replacements/Tooling/ApplyReplacements.h
 
b/clang-tools-extra/clang-apply-replacements/include/clang-apply-replacements/Tooling/ApplyReplacements.h
index e37768277c5a4..b0cf7317c0ed8 100644
--- 
a/clang-tools-extra/clang-apply-replacements/include/clang-apply-replacements/Tooling/ApplyReplacements.h
+++ 
b/clang-tools-extra/clang-apply-replacements/include/clang-apply-replacements/Tooling/ApplyReplacements.h
@@ -87,7 +87,8 @@ std::error_code collectReplacementsFromDirectory(
 ///  \li false If there were conflicts.
 bool mergeAndDeduplicate(const TUReplacements &TUs, const TUDiagnostics &TUDs,
  FileToChangesMap &FileChanges,
- clang::SourceManager &SM);
+ clang::SourceManager &SM,
+ bool IgnoreInsertConflict = false);
 
 /// Apply \c AtomicChange on File and rewrite it.
 ///

diff  --git 
a/clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp 
b/clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp
index b13b83cf3f000..e25c8e2449dc8 100644
--- 
a/clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp
+++ 
b/clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp
@@ -202,7 +202,7 @@ groupReplacements(const TUReplacements &TUs, const 
TUDiagnostics &TUDs,
 
 bool mergeAndDeduplicate(const TUReplacements &TUs, const TUDiagnostics &TUDs,
  FileToChangesMap &FileChanges,
- clang::SourceManager &SM) {
+ clang::SourceManager &SM, bool IgnoreInsertConflict) {
   auto GroupedReplacements = groupReplacements(TUs, TUDs, SM);
   bool ConflictDetected = false;
 
@@ -231,7 +231,24 @@ bool mergeAndDeduplicate(const TUReplacements &TUs, const 
TUDiagnostics &TUDs,
 // For now, printing directly the error reported by `AtomicChange` is
 // the easiest solution.
 errs() << llvm::toString(std::move(Err)) << "\n";
-ConflictDetected = true;
+if (IgnoreInsertConflict) {
+  tooling::Replacements &Replacements = FileChange.getReplacements();
+  unsigned NewOffset =
+  Replacements.getShiftedCodePosition(R.getOffset());
+  unsigned NewLength = Replacements.getShiftedCodePosition(
+   R.getOffset() + R.getLength()) -
+   NewOffset;
+  if (NewLength == R.getLength()) {
+tooling::Replacement RR = tooling::Replacement(
+R.getFilePath(), NewOffset, NewLength, R.getReplacementText());
+Replacements = Replacements.merge(tooling::Replacements(RR));
+  } else {
+llvm::errs()
+<< "Can't resolve conflict, skipping the replacement.\n";
+ConflictDetected = true;
+  }
+} else
+  ConflictDetected = true;
   }
 }
 FileChanges.try_emplace(Entry,

diff  --git 
a/clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp
 
b/clang-tools-extra/clang-apply-replacements/tool/Cl

[clang] b1b86b6 - [Clang][Driver] More explicit message when failing to find sanitizer resource file

2022-06-01 Thread via cfe-commits

Author: serge-sans-paille
Date: 2022-06-01T10:54:20+02:00
New Revision: b1b86b63943305f71e5fb522da168c9dbac1d39d

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

LOG: [Clang][Driver] More explicit message when failing to find sanitizer 
resource file

Compiler-rt doesn't provide support file for cfi on s390x ad ppc64le (at least).
When trying to use the flag, we get a file error.

This is an attempt at making the error more explicit.

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

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/lib/Driver/SanitizerArgs.cpp
clang/test/Driver/fsanitize-ignorelist.c

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 618e748da444..1012551651c5 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -212,6 +212,8 @@ def err_drv_invalid_libcxx_deployment : Error<
   "invalid deployment target for -stdlib=libc++ (requires %0 or later)">;
 def err_drv_invalid_argument_to_option : Error<
   "invalid argument '%0' to -%1">;
+def err_drv_missing_sanitizer_ignorelist : Error<
+  "missing sanitizer ignorelist: '%0'">;
 def err_drv_malformed_sanitizer_ignorelist : Error<
   "malformed sanitizer ignorelist: '%0'">;
 def err_drv_malformed_sanitizer_coverage_allowlist : Error<

diff  --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index b63c6e463706..fbabd1a3e38a 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -168,7 +168,7 @@ static void addDefaultIgnorelists(const Driver &D, 
SanitizerMask Kinds,
 else if (BL.Mask == SanitizerKind::CFI && DiagnoseErrors)
   // If cfi_ignorelist.txt cannot be found in the resource dir, driver
   // should fail.
-  D.Diag(clang::diag::err_drv_no_such_file) << Path;
+  D.Diag(clang::diag::err_drv_missing_sanitizer_ignorelist) << Path;
   }
   validateSpecialCaseListFormat(
   D, IgnorelistFiles, clang::diag::err_drv_malformed_sanitizer_ignorelist,

diff  --git a/clang/test/Driver/fsanitize-ignorelist.c 
b/clang/test/Driver/fsanitize-ignorelist.c
index 17c4f5abcedc..22e8e724be75 100644
--- a/clang/test/Driver/fsanitize-ignorelist.c
+++ b/clang/test/Driver/fsanitize-ignorelist.c
@@ -64,7 +64,7 @@
 
 // If cfi_ignorelist.txt cannot be found in the resource dir, driver should 
fail.
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=cfi -flto 
-fvisibility=default -resource-dir=/dev/null %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-MISSING-CFI-IGNORELIST
-// CHECK-MISSING-CFI-IGNORELIST: error: no such file or directory: 
'{{.*}}cfi_ignorelist.txt'
+// CHECK-MISSING-CFI-IGNORELIST: error: missing sanitizer ignorelist: 
'{{.*}}cfi_ignorelist.txt'
 
 // -fno-sanitize-ignorelist disables checking for cfi_ignorelist.txt in the 
resource dir.
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=cfi -flto 
-fvisibility=default -fno-sanitize-ignorelist -resource-dir=/dev/null %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-MISSING-CFI-NO-IGNORELIST



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


[clang-tools-extra] b418ef5 - [clang-tidy] Reject invalid enum initializers in C files

2022-06-01 Thread via cfe-commits

Author: Richard
Date: 2022-06-01T22:25:39-06:00
New Revision: b418ef5cb90b32657dee46b068ac367787a8d2d6

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

LOG: [clang-tidy] Reject invalid enum initializers in C files

C requires that enum values fit into an int.  Scan the macro tokens
present in an initializing expression and reject macros that contain
tokens that have suffixes making them larger than int.

C forbids the comma operator in enum initializing expressions, so
optionally reject comma operator.

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

Fixes #55467

Added: 
clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.c

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

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp 
b/clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp
index 91a10f8956e62..ca0e99fc787a1 100644
--- 
a/clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp
+++ 
b/clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp
@@ -8,6 +8,7 @@
 
 #include "IntegralLiteralExpressionMatcher.h"
 
+#include 
 #include 
 #include 
 
@@ -81,6 +82,50 @@ bool IntegralLiteralExpressionMatcher::unaryOperator() {
   return true;
 }
 
+static LiteralSize literalTokenSize(const Token &Tok) {
+  unsigned int Length = Tok.getLength();
+  if (Length <= 1)
+return LiteralSize::Int;
+
+  bool SeenUnsigned = false;
+  bool SeenLong = false;
+  bool SeenLongLong = false;
+  const char *Text = Tok.getLiteralData();
+  for (unsigned int End = Length - 1; End > 0; --End) {
+if (std::isdigit(Text[End]))
+  break;
+
+if (std::toupper(Text[End]) == 'U')
+  SeenUnsigned = true;
+else if (std::toupper(Text[End]) == 'L') {
+  if (SeenLong)
+SeenLongLong = true;
+  SeenLong = true;
+}
+  }
+
+  if (SeenLongLong) {
+if (SeenUnsigned)
+  return LiteralSize::UnsignedLongLong;
+
+return LiteralSize::LongLong;
+  }
+  if (SeenLong) {
+if (SeenUnsigned)
+  return LiteralSize::UnsignedLong;
+
+return LiteralSize::Long;
+  }
+  if (SeenUnsigned)
+return LiteralSize::UnsignedInt;
+
+  return LiteralSize::Int;
+}
+
+static bool operator<(LiteralSize LHS, LiteralSize RHS) {
+  return static_cast(LHS) < static_cast(RHS);
+}
+
 bool IntegralLiteralExpressionMatcher::unaryExpr() {
   if (!unaryOperator())
 return false;
@@ -102,7 +147,10 @@ bool IntegralLiteralExpressionMatcher::unaryExpr() {
   !isIntegralConstant(*Current)) {
 return false;
   }
+
+  LargestSize = std::max(LargestSize, literalTokenSize(*Current));
   ++Current;
+
   return true;
 }
 
@@ -217,14 +265,24 @@ bool IntegralLiteralExpressionMatcher::conditionalExpr() {
 }
 
 bool IntegralLiteralExpressionMatcher::commaExpr() {
-  return nonTerminalChainedExpr(
-  &IntegralLiteralExpressionMatcher::conditionalExpr);
+  auto Pred = CommaAllowed
+  ? std::function(
+[](Token Tok) { return Tok.is(tok::TokenKind::comma); 
})
+  : std::function([](Token) { return false; });
+  return nonTerminalChainedExpr(
+  &IntegralLiteralExpressionMatcher::conditionalExpr, Pred);
 }
 
 bool IntegralLiteralExpressionMatcher::expr() { return commaExpr(); }
 
 bool IntegralLiteralExpressionMatcher::match() {
-  return expr() && Current == End;
+  // Top-level allowed expression is conditionalExpr(), not expr(), because
+  // comma operators are only valid initializers when used inside parentheses.
+  return conditionalExpr() && Current == End;
+}
+
+LiteralSize IntegralLiteralExpressionMatcher::largestLiteralSize() const {
+  return LargestSize;
 }
 
 } // namespace modernize

diff  --git 
a/clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.h 
b/clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.h
index 9202cc1ed4574..4499ef983ea4e 100644
--- a/clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.h
+++ b/clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.h
@@ -16,15 +16,27 @@ namespace clang {
 namespace tidy {
 namespace modernize {
 
+enum class LiteralSize {
+  Unknown = 0,
+  Int,
+  UnsignedInt,
+  Long,
+  UnsignedLong,
+  LongLong,
+  UnsignedLongLong
+};
+
 // Parses an array of tokens and returns true if they conform to the rules of
 // C++ for whole expressions involving

[clang] db15e31 - [clang-format] Handle do-while loops for RemoveBracesLLVM

2022-06-02 Thread via cfe-commits

Author: owenca
Date: 2022-06-02T01:08:40-07:00
New Revision: db15e31212436ae51c04e8b5fcc2f140db4d6626

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

LOG: [clang-format] Handle do-while loops for RemoveBracesLLVM

Also updates the unit tests to match the updated LLVM Coding
Standards.

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 9a5d85cead889..8de7fae9ae51d 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -480,6 +480,7 @@ bool UnwrappedLineParser::parseLevel(const FormatToken 
*OpeningBrace,
   : TT_Unknown;
   const bool IsPrecededByCommentOrPPDirective =
   !Style.RemoveBracesLLVM || precededByCommentOrPPDirective();
+  bool HasDoWhile = false;
   bool HasLabel = false;
   unsigned StatementCount = 0;
   bool SwitchLabelEncountered = false;
@@ -495,8 +496,9 @@ bool UnwrappedLineParser::parseLevel(const FormatToken 
*OpeningBrace,
   kind = tok::r_brace;
 
 auto ParseDefault = [this, OpeningBrace, IfKind, NextLevelLBracesType,
- &HasLabel, &StatementCount] {
+ &HasDoWhile, &HasLabel, &StatementCount] {
   parseStructuralElement(IfKind, !OpeningBrace, NextLevelLBracesType,
+ HasDoWhile ? nullptr : &HasDoWhile,
  HasLabel ? nullptr : &HasLabel);
   ++StatementCount;
   assert(StatementCount > 0 && "StatementCount overflow!");
@@ -536,7 +538,7 @@ bool UnwrappedLineParser::parseLevel(const FormatToken 
*OpeningBrace,
   return false;
 }
 if (FormatTok->isNot(tok::r_brace) || StatementCount != 1 || HasLabel 
||
-IsPrecededByCommentOrPPDirective ||
+HasDoWhile || IsPrecededByCommentOrPPDirective ||
 precededByCommentOrPPDirective()) {
   return false;
 }
@@ -1415,6 +1417,7 @@ void UnwrappedLineParser::readTokenWithJavaScriptASI() {
 void UnwrappedLineParser::parseStructuralElement(IfStmtKind *IfKind,
  bool IsTopLevel,
  TokenType NextLBracesType,
+ bool *HasDoWhile,
  bool *HasLabel) {
   if (Style.Language == FormatStyle::LK_TableGen &&
   FormatTok->is(tok::pp_include)) {
@@ -1476,6 +1479,8 @@ void 
UnwrappedLineParser::parseStructuralElement(IfStmtKind *IfKind,
   break;
 }
 parseDoWhile();
+if (HasDoWhile)
+  *HasDoWhile = true;
 return;
   case tok::kw_switch:
 if (Style.isJavaScript() && Line->MustBeDeclaration) {

diff  --git a/clang/lib/Format/UnwrappedLineParser.h 
b/clang/lib/Format/UnwrappedLineParser.h
index ffba36cd01706..38f83a896e1d6 100644
--- a/clang/lib/Format/UnwrappedLineParser.h
+++ b/clang/lib/Format/UnwrappedLineParser.h
@@ -115,6 +115,7 @@ class UnwrappedLineParser {
   void parseStructuralElement(IfStmtKind *IfKind = nullptr,
   bool IsTopLevel = false,
   TokenType NextLBracesType = TT_Unknown,
+  bool *HasDoWhile = nullptr,
   bool *HasLabel = nullptr);
   bool tryToParseBracedList();
   bool parseBracedList(bool ContinueOnSemicolons = false, bool IsEnum = false,

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index c1257059c8649..f8f2715c39768 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -25100,12 +25100,12 @@ TEST_F(FormatTest, RemoveBraces) {
   FormatStyle Style = getLLVMStyle();
   Style.RemoveBracesLLVM = true;
 
-  // The following eight test cases are fully-braced versions of the examples 
at
+  // The following test cases are fully-braced versions of the examples at
   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
   // statement-bodies-of-if-else-loop-statements".
 
-  // 1. Omit the braces, since the body is simple and clearly associated with
-  // the if.
+  // Omit the braces since the body is simple and clearly associated with the
+  // `if`.
   verifyFormat("if (isa(D))\n"
"  handleFunctionDecl(D);\n"
"else if (isa(D))\n"
@@ -25117,7 +25117,7 @@ TEST_F(FormatTest, RemoveBraces) {
"}",
Style);
 
-  // 2. Here we document the condition itself and not the body.
+  

[clang-tools-extra] 8df2b1a - [pp-trace] Print HashLoc in InclusionDirective callback

2022-06-03 Thread via cfe-commits

Author: CHIANG, YU-HSUN (Tommy Chiang, oToToT)
Date: 2022-06-03T19:29:59+08:00
New Revision: 8df2b1a866800b41984bd7721b244a9821810764

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

LOG: [pp-trace] Print HashLoc in InclusionDirective callback

The HashLoc in InclusionDirective callback is an unused parameter.
Since pp-trace is also used as a test of Clang’s PPCallbacks interface,
add it to the output of pp-trace could avoid some unintended change on
it.

This shuold resolves PR52673

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/pp-trace.rst
clang-tools-extra/pp-trace/PPCallbacksTracker.cpp
clang-tools-extra/test/pp-trace/pp-trace-include.cpp

Removed: 




diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 7e8ef092fad1..b8321dd0c365 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -239,7 +239,7 @@ The improvements are...
 Improvements to pp-trace
 
 
-The improvements are...
+- Added `HashLoc` information to `InclusionDirective` callback output.
 
 Clang-tidy Visual Studio plugin
 ---

diff  --git a/clang-tools-extra/docs/pp-trace.rst 
b/clang-tools-extra/docs/pp-trace.rst
index 84a5ae6ed6c6..7339d8084c34 100644
--- a/clang-tools-extra/docs/pp-trace.rst
+++ b/clang-tools-extra/docs/pp-trace.rst
@@ -223,6 +223,7 @@ Imported ((module name)|(null)) 
  const Modu
 Example:::
 
   - Callback: InclusionDirective
+HashLoc: 
"D:/Clang/llvmnewmod/clang-tools-extra/test/pp-trace/pp-trace-include.cpp:4:1"
 IncludeTok: include
 FileName: "Input/Level1B.h"
 IsAngled: false

diff  --git a/clang-tools-extra/pp-trace/PPCallbacksTracker.cpp 
b/clang-tools-extra/pp-trace/PPCallbacksTracker.cpp
index 63a07914f207..c1434558698d 100644
--- a/clang-tools-extra/pp-trace/PPCallbacksTracker.cpp
+++ b/clang-tools-extra/pp-trace/PPCallbacksTracker.cpp
@@ -137,6 +137,7 @@ void PPCallbacksTracker::InclusionDirective(
 llvm::StringRef SearchPath, llvm::StringRef RelativePath,
 const Module *Imported, SrcMgr::CharacteristicKind FileType) {
   beginCallback("InclusionDirective");
+  appendArgument("HashLoc", HashLoc);
   appendArgument("IncludeTok", IncludeTok);
   appendFilePathArgument("FileName", FileName);
   appendArgument("IsAngled", IsAngled);

diff  --git a/clang-tools-extra/test/pp-trace/pp-trace-include.cpp 
b/clang-tools-extra/test/pp-trace/pp-trace-include.cpp
index d5578cf16f59..96b4014025b7 100644
--- a/clang-tools-extra/test/pp-trace/pp-trace-include.cpp
+++ b/clang-tools-extra/test/pp-trace/pp-trace-include.cpp
@@ -51,6 +51,7 @@
 // CHECK-NEXT:   FileType: C_User
 // CHECK-NEXT:   PrevFID: (getFileEntryForID failed)
 // CHECK-NEXT: - Callback: InclusionDirective
+// CHECK-NEXT:   HashLoc: "{{.*}}{{[/\\]}}pp-trace-include.cpp:3:1"
 // CHECK-NEXT:   IncludeTok: include
 // CHECK-NEXT:   FileName: "Inputs/Level1A.h"
 // CHECK-NEXT:   IsAngled: false
@@ -65,6 +66,7 @@
 // CHECK-NEXT:   FileType: C_User
 // CHECK-NEXT:   PrevFID: (invalid)
 // CHECK-NEXT: - Callback: InclusionDirective
+// CHECK-NEXT:   HashLoc: "{{.*}}{{[/\\]}}Inputs/Level1A.h:1:1"
 // CHECK-NEXT:   IncludeTok: include
 // CHECK-NEXT:   FileName: "Level2A.h"
 // CHECK-NEXT:   IsAngled: false
@@ -95,6 +97,7 @@
 // CHECK-NEXT:   FileType: C_User
 // CHECK-NEXT:   PrevFID: "{{.*}}{{[/\\]}}Inputs/Level1A.h"
 // CHECK-NEXT: - Callback: InclusionDirective
+// CHECK-NEXT:   HashLoc: "{{.*}}{{[/\\]}}pp-trace-include.cpp:4:1"
 // CHECK-NEXT:   IncludeTok: include
 // CHECK-NEXT:   FileName: "Inputs/Level1B.h"
 // CHECK-NEXT:   IsAngled: false
@@ -109,6 +112,7 @@
 // CHECK-NEXT:   FileType: C_User
 // CHECK-NEXT:   PrevFID: (invalid)
 // CHECK-NEXT: - Callback: InclusionDirective
+// CHECK-NEXT:   HashLoc: "{{.*}}{{[/\\]}}Inputs/Level1B.h:1:1"
 // CHECK-NEXT:   IncludeTok: include
 // CHECK-NEXT:   FileName: "Level2B.h"
 // CHECK-NEXT:   IsAngled: false



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


[clang] 436fef2 - [NFC] Fix issue on CMake Xcode build configuration.

2022-06-03 Thread via cfe-commits

Author: python3kgae
Date: 2022-06-03T11:03:02-07:00
New Revision: 436fef21efe35833622c71da705a9a50db246294

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

LOG: [NFC] Fix issue on CMake Xcode build configuration.

add missing dependency for hlsl-resource-headers and clang-resource-headers.

Reviewed By: rastogishubham

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

Added: 


Modified: 
clang/lib/Headers/CMakeLists.txt

Removed: 




diff  --git a/clang/lib/Headers/CMakeLists.txt 
b/clang/lib/Headers/CMakeLists.txt
index fc321684f0c69..dfa3602b557b1 100644
--- a/clang/lib/Headers/CMakeLists.txt
+++ b/clang/lib/Headers/CMakeLists.txt
@@ -378,6 +378,7 @@ add_dependencies("clang-resource-headers"
  "cuda-resource-headers"
  "hexagon-resource-headers"
  "hip-resource-headers"
+ "hlsl-resource-headers"
  "mips-resource-headers"
  "ppc-resource-headers"
  "ppc-htm-resource-headers"



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


[clang] fc1c160 - [clang-format] Handle attributes for for/while loops

2022-06-05 Thread via cfe-commits

Author: owenca
Date: 2022-06-05T15:45:25-07:00
New Revision: fc1c160f73304d474198d9a21e857b47df2acd3a

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

LOG: [clang-format] Handle attributes for for/while loops

Fixes #55853.

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

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 8de7fae9ae51d..30bdbdfb2c702 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2889,6 +2889,7 @@ void UnwrappedLineParser::parseForOrWhileLoop() {
   if (FormatTok->is(tok::l_paren))
 parseParens();
 
+  handleAttributes();
   parseLoopBody(KeepBraces, /*WrapRightBrace=*/true);
 }
 

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index f8f2715c39768..264f50ab980ea 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -23846,6 +23846,22 @@ TEST_F(FormatTest, LikelyUnlikely) {
"  return 29;\n",
Style);
 
+  verifyFormat("while (limit > 0) [[unlikely]] {\n"
+   "  --limit;\n"
+   "}",
+   Style);
+  verifyFormat("for (auto &limit : limits) [[likely]] {\n"
+   "  --limit;\n"
+   "}",
+   Style);
+
+  verifyFormat("for (auto &limit : limits) [[unlikely]]\n"
+   "  --limit;",
+   Style);
+  verifyFormat("while (limit > 0) [[likely]]\n"
+   "  --limit;",
+   Style);
+
   Style.AttributeMacros.push_back("UNLIKELY");
   Style.AttributeMacros.push_back("LIKELY");
   verifyFormat("if (argc > 5) UNLIKELY\n"
@@ -23874,6 +23890,22 @@ TEST_F(FormatTest, LikelyUnlikely) {
"  return 42;\n"
"}\n",
Style);
+
+  verifyFormat("for (auto &limit : limits) UNLIKELY {\n"
+   "  --limit;\n"
+   "}",
+   Style);
+  verifyFormat("while (limit > 0) LIKELY {\n"
+   "  --limit;\n"
+   "}",
+   Style);
+
+  verifyFormat("while (limit > 0) UNLIKELY\n"
+   "  --limit;",
+   Style);
+  verifyFormat("for (auto &limit : limits) LIKELY\n"
+   "  --limit;",
+   Style);
 }
 
 TEST_F(FormatTest, PenaltyIndentedWhitespace) {



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


[clang] ec90bc0 - [clang-format][NFC] Clean up the unwrapped line parser

2022-06-07 Thread via cfe-commits

Author: owenca
Date: 2022-06-07T02:58:57-07:00
New Revision: ec90bc0ea4386849f9eea54f44d25b49d4673cd6

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

LOG: [clang-format][NFC] Clean up the unwrapped line parser

Change the signatures of parseBlock(), parseLevel(), and
parseStructuralElement() to support combining else and if when
removing braces. See #55663.

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 30bdbdfb2c702..f581005e8c3ca 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -395,7 +395,7 @@ void UnwrappedLineParser::parseFile() {
   if (Style.Language == FormatStyle::LK_TextProto)
 parseBracedList();
   else
-parseLevel(/*OpeningBrace=*/nullptr, /*CanContainBracedList=*/true);
+parseLevel();
   // Make sure to format the remaining tokens.
   //
   // LK_TextProto is special since its top-level is parsed as the body of a
@@ -469,12 +469,13 @@ bool 
UnwrappedLineParser::precededByCommentOrPPDirective() const {
 /// \param CanContainBracedList If the content can contain (at any level) a
 /// braced list.
 /// \param NextLBracesType The type for left brace found in this level.
+/// \param IfKind The if statement kind in the level.
 /// \returns true if a simple block of if/else/for/while, or false otherwise.
 /// (A simple block has a single statement.)
 bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace,
  bool CanContainBracedList,
- IfStmtKind *IfKind,
- TokenType NextLBracesType) {
+ TokenType NextLBracesType,
+ IfStmtKind *IfKind) {
   auto NextLevelLBracesType = NextLBracesType == TT_CompoundRequirementLBrace
   ? TT_BracedListLBrace
   : TT_Unknown;
@@ -484,6 +485,7 @@ bool UnwrappedLineParser::parseLevel(const FormatToken 
*OpeningBrace,
   bool HasLabel = false;
   unsigned StatementCount = 0;
   bool SwitchLabelEncountered = false;
+
   do {
 if (FormatTok->getType() == TT_AttributeMacro) {
   nextToken();
@@ -495,9 +497,9 @@ bool UnwrappedLineParser::parseLevel(const FormatToken 
*OpeningBrace,
 else if (FormatTok->getType() == TT_MacroBlockEnd)
   kind = tok::r_brace;
 
-auto ParseDefault = [this, OpeningBrace, IfKind, NextLevelLBracesType,
+auto ParseDefault = [this, OpeningBrace, NextLevelLBracesType, IfKind,
  &HasDoWhile, &HasLabel, &StatementCount] {
-  parseStructuralElement(IfKind, !OpeningBrace, NextLevelLBracesType,
+  parseStructuralElement(!OpeningBrace, NextLevelLBracesType, IfKind,
  HasDoWhile ? nullptr : &HasDoWhile,
  HasLabel ? nullptr : &HasLabel);
   ++StatementCount;
@@ -524,7 +526,7 @@ bool UnwrappedLineParser::parseLevel(const FormatToken 
*OpeningBrace,
 continue;
   }
   parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u,
- /*MunchSemi=*/true, /*KeepBraces=*/true,
+ /*MunchSemi=*/true, /*KeepBraces=*/true, /*IfKind=*/nullptr,
  /*UnindentWhitesmithsBraces=*/false, CanContainBracedList,
  NextLBracesType);
   ++StatementCount;
@@ -593,6 +595,7 @@ bool UnwrappedLineParser::parseLevel(const FormatToken 
*OpeningBrace,
   break;
 }
   } while (!eof());
+
   return false;
 }
 
@@ -815,10 +818,12 @@ bool UnwrappedLineParser::mightFitOnOneLine(
   return Line.Level * Style.IndentWidth + Length <= ColumnLimit;
 }
 
-UnwrappedLineParser::IfStmtKind UnwrappedLineParser::parseBlock(
-bool MustBeDeclaration, unsigned AddLevels, bool MunchSemi, bool 
KeepBraces,
-bool UnindentWhitesmithsBraces, bool CanContainBracedList,
-TokenType NextLBracesType) {
+void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, unsigned 
AddLevels,
+ bool MunchSemi, bool KeepBraces,
+ IfStmtKind *IfKind,
+ bool UnindentWhitesmithsBraces,
+ bool CanContainBracedList,
+ TokenType NextLBracesType) {
   assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
  "'{' or macro block token expected");
   FormatToken *Tok = FormatTok;
@@ -859,18 +864,17 @@ UnwrappedLineParser::IfStmtKind 
UnwrappedLineParser::

[clang] c7fa4e8 - [analyzer] Fix null pointer deref in CastValueChecker

2022-06-07 Thread via cfe-commits

Author: Vince Bridgers
Date: 2022-06-07T13:34:06-04:00
New Revision: c7fa4e8a8bc41e52cc49a27e0495d67d730fa167

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

LOG: [analyzer] Fix null pointer deref in CastValueChecker

A crash was seen in CastValueChecker due to a null pointer dereference.

The fix uses QualType::getAsString to avoid the null dereference
when a CXXRecordDecl cannot be obtained. A small reproducer is added,
and cast value notes LITs are updated for the new debug messages.

Reviewed By: steakhal

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
clang/test/Analysis/cast-value-notes.cpp
clang/test/Analysis/cast-value-state-dump.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
index e2b99fca7d148..45f9a82a9d0a4 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
@@ -108,7 +108,7 @@ static const NoteTag *getNoteTag(CheckerContext &C,
  bool CastSucceeds, bool IsKnownCast) {
   std::string CastToName =
   CastInfo ? CastInfo->to()->getAsCXXRecordDecl()->getNameAsString()
-   : CastToTy->getPointeeCXXRecordDecl()->getNameAsString();
+   : CastToTy.getAsString();
   Object = Object->IgnoreParenImpCasts();
 
   return C.getNoteTag(
@@ -163,9 +163,9 @@ static const NoteTag *getNoteTag(CheckerContext &C,
 bool First = true;
 for (QualType CastToTy: CastToTyVec) {
   std::string CastToName =
-CastToTy->getAsCXXRecordDecl() ?
-CastToTy->getAsCXXRecordDecl()->getNameAsString() :
-CastToTy->getPointeeCXXRecordDecl()->getNameAsString();
+  CastToTy->getAsCXXRecordDecl()
+  ? CastToTy->getAsCXXRecordDecl()->getNameAsString()
+  : CastToTy.getAsString();
   Out << ' ' << ((CastToTyVec.size() == 1) ? "not" :
  (First ? "neither" : "nor")) << " a '" << CastToName
   << '\'';

diff  --git a/clang/test/Analysis/cast-value-notes.cpp 
b/clang/test/Analysis/cast-value-notes.cpp
index ddfaf07b2a0af..b3d32552e6ec8 100644
--- a/clang/test/Analysis/cast-value-notes.cpp
+++ b/clang/test/Analysis/cast-value-notes.cpp
@@ -73,7 +73,7 @@ void clang_analyzer_printState();
 #if defined(X86)
 void evalReferences(const Shape &S) {
   const auto &C = dyn_cast(S);
-  // expected-note@-1 {{Assuming 'S' is not a 'Circle'}}
+  // expected-note@-1 {{Assuming 'S' is not a 'const class clang::Circle &'}}
   // expected-note@-2 {{Dereference of null pointer}}
   // expected-warning@-3 {{Dereference of null pointer}}
   clang_analyzer_printState();
@@ -93,7 +93,7 @@ void evalReferences_addrspace(const Shape &S) {
 #if defined(NOT_SUPPRESSED)
 void evalReferences_addrspace(const Shape &S) {
   const auto &C = dyn_cast(S);
-  // expected-note@-1 {{Assuming 'S' is not a 'Circle'}}
+  // expected-note@-1 {{Assuming 'S' is not a 'const 
__attribute__((address_space(3))) class clang::Circle &'}}
   // expected-note@-2 {{Dereference of null pointer}}
   // expected-warning@-3 {{Dereference of null pointer}}
   clang_analyzer_printState();
@@ -105,7 +105,7 @@ void evalReferences_addrspace(const Shape &S) {
 #elif defined(MIPS)
 void evalReferences(const Shape &S) {
   const auto &C = dyn_cast(S);
-  // expected-note@-1 {{Assuming 'S' is not a 'Circle'}}
+  // expected-note@-1 {{Assuming 'S' is not a 'const class clang::Circle &'}}
   // expected-note@-2 {{Dereference of null pointer}}
   // expected-warning@-3 {{Dereference of null pointer}}
 }
@@ -122,25 +122,25 @@ void evalNonNullParamNonNullReturnReference(const Shape 
&S) {
   // expected-note@-1 {{'C' initialized here}}
 
   if (!dyn_cast_or_null(C)) {
-// expected-note@-1 {{'C' is a 'Circle'}}
+// expected-note@-1 {{Assuming 'C' is a 'const class clang::Circle *'}}
 // expected-note@-2 {{Taking false branch}}
 return;
   }
 
   if (dyn_cast_or_null(C)) {
-// expected-note@-1 {{Assuming 'C' is not a 'Triangle'}}
+// expected-note@-1 {{Assuming 'C' is not a 'const class clang::Triangle 
*'}}
 // expected-note@-2 {{Taking false branch}}
 return;
   }
 
   if (dyn_cast_or_null(C)) {
-// expected-note@-1 {{Assuming 'C' is not a 'Rectangle'}}
+// expected-note@-1 {{Assuming 'C' is not a 'const class clang::Rectangle 
*'}}
 // expected-note@-2 {{Taking false branch}}
 return;
   }
 
   if (dyn_cast_or_null(C)) {
-// expected-note@-1 {{Assuming 'C' is not a 'Hexagon'}}
+// expected-note@-1 {{Assuming 'C' is not a 'const class clang::Hexagon 
*'}}
 

[clang] b5b33fb - [clang-format] Skip parsing a block if it's nested too deep

2022-06-07 Thread via cfe-commits

Author: owenca
Date: 2022-06-07T15:28:03-07:00
New Revision: b5b33fbffb087f69f54b9a7bce70828ef6e82601

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

LOG: [clang-format] Skip parsing a block if it's nested too deep

Fixes #55912.

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 86b42c499b23b..aa1411d67799b 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -842,6 +842,10 @@ void UnwrappedLineParser::parseBlock(bool 
MustBeDeclaration, unsigned AddLevels,
   unsigned InitialLevel = Line->Level;
   nextToken(/*LevelDifference=*/AddLevels);
 
+  // Bail out if there are too many levels. Otherwise, the stack might 
overflow.
+  if (Line->Level > 300)
+return;
+
   if (MacroBlock && FormatTok->is(tok::l_paren))
 parseParens();
 



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


[clang] 5ead1f1 - [clang-format] Remove braces of else blocks that embody an if block

2022-06-08 Thread via cfe-commits

Author: owenca
Date: 2022-06-08T16:05:20-07:00
New Revision: 5ead1f13a2d8ca33e9e93c06acee941a857905c6

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

LOG: [clang-format] Remove braces of else blocks that embody an if block

Fixes #55663.

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index aa1411d67799..d2d69aabfd80 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -469,18 +469,21 @@ bool 
UnwrappedLineParser::precededByCommentOrPPDirective() const {
 /// \param CanContainBracedList If the content can contain (at any level) a
 /// braced list.
 /// \param NextLBracesType The type for left brace found in this level.
-/// \param IfKind The if statement kind in the level.
+/// \param IfKind The \p if statement kind in the level.
+/// \param IfLeftBrace The left brace of the \p if block in the level.
 /// \returns true if a simple block of if/else/for/while, or false otherwise.
 /// (A simple block has a single statement.)
 bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace,
  bool CanContainBracedList,
  TokenType NextLBracesType,
- IfStmtKind *IfKind) {
+ IfStmtKind *IfKind,
+ FormatToken **IfLeftBrace) {
   auto NextLevelLBracesType = NextLBracesType == TT_CompoundRequirementLBrace
   ? TT_BracedListLBrace
   : TT_Unknown;
   const bool IsPrecededByCommentOrPPDirective =
   !Style.RemoveBracesLLVM || precededByCommentOrPPDirective();
+  FormatToken *IfLBrace = nullptr;
   bool HasDoWhile = false;
   bool HasLabel = false;
   unsigned StatementCount = 0;
@@ -498,9 +501,9 @@ bool UnwrappedLineParser::parseLevel(const FormatToken 
*OpeningBrace,
   kind = tok::r_brace;
 
 auto ParseDefault = [this, OpeningBrace, NextLevelLBracesType, IfKind,
- &HasDoWhile, &HasLabel, &StatementCount] {
+ &IfLBrace, &HasDoWhile, &HasLabel, &StatementCount] {
   parseStructuralElement(!OpeningBrace, NextLevelLBracesType, IfKind,
- HasDoWhile ? nullptr : &HasDoWhile,
+ &IfLBrace, HasDoWhile ? nullptr : &HasDoWhile,
  HasLabel ? nullptr : &HasLabel);
   ++StatementCount;
   assert(StatementCount > 0 && "StatementCount overflow!");
@@ -545,7 +548,11 @@ bool UnwrappedLineParser::parseLevel(const FormatToken 
*OpeningBrace,
   return false;
 }
 const FormatToken *Next = Tokens->peekNextToken();
-return Next->isNot(tok::comment) || Next->NewlinesBefore > 0;
+if (Next->is(tok::comment) && Next->NewlinesBefore == 0)
+  return false;
+if (IfLeftBrace)
+  *IfLeftBrace = IfLBrace;
+return true;
   }
   nextToken();
   addUnwrappedLine();
@@ -818,12 +825,10 @@ bool UnwrappedLineParser::mightFitOnOneLine(
   return Line.Level * Style.IndentWidth + Length <= ColumnLimit;
 }
 
-void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, unsigned 
AddLevels,
- bool MunchSemi, bool KeepBraces,
- IfStmtKind *IfKind,
- bool UnindentWhitesmithsBraces,
- bool CanContainBracedList,
- TokenType NextLBracesType) {
+FormatToken *UnwrappedLineParser::parseBlock(
+bool MustBeDeclaration, unsigned AddLevels, bool MunchSemi, bool 
KeepBraces,
+IfStmtKind *IfKind, bool UnindentWhitesmithsBraces,
+bool CanContainBracedList, TokenType NextLBracesType) {
   assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
  "'{' or macro block token expected");
   FormatToken *Tok = FormatTok;
@@ -844,7 +849,7 @@ void UnwrappedLineParser::parseBlock(bool 
MustBeDeclaration, unsigned AddLevels,
 
   // Bail out if there are too many levels. Otherwise, the stack might 
overflow.
   if (Line->Level > 300)
-return;
+return nullptr;
 
   if (MacroBlock && FormatTok->is(tok::l_paren))
 parseParens();
@@ -868,31 +873,37 @@ void UnwrappedLineParser::parseBlock(bool 
MustBeDeclaration, unsigned AddLevels,
   if (AddLevels > 0u && Style.BreakBeforeBraces != FormatStyle::BS_Whitesmiths)
 Line->Level += AddLevels;
 
+  F

[clang] 40a5d79 - [clang-format][NFC] Format lib/Format and unittests/Format in clang

2022-06-09 Thread via cfe-commits

Author: owenca
Date: 2022-06-09T02:25:06-07:00
New Revision: 40a5d79a5cb4edc7343349f17e59377eb9362c4a

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

LOG: [clang-format][NFC] Format lib/Format and unittests/Format in clang

Reformat these directories with InsertBraces and RemoveBracesLLVM.

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

Added: 


Modified: 
clang/lib/Format/BreakableToken.cpp
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/BreakableToken.cpp 
b/clang/lib/Format/BreakableToken.cpp
index 6ae112b86ebb6..db82018a4c83c 100644
--- a/clang/lib/Format/BreakableToken.cpp
+++ b/clang/lib/Format/BreakableToken.cpp
@@ -705,11 +705,9 @@ void BreakableBlockComment::adaptStartOfLine(
   // contain a trailing whitespace.
   Prefix = Prefix.substr(0, 1);
 }
-  } else {
-if (ContentColumn[LineIndex] == 1) {
-  // This line starts immediately after the decorating *.
-  Prefix = Prefix.substr(0, 1);
-}
+  } else if (ContentColumn[LineIndex] == 1) {
+// This line starts immediately after the decorating *.
+Prefix = Prefix.substr(0, 1);
   }
   // This is the offset of the end of the last line relative to the start of 
the
   // token text in the token.

diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index fe43981e27d00..6ec788ad23c66 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -230,12 +230,10 @@ void WhitespaceManager::calculateLineBreakInformation() {
 if (Change.Tok->is(tok::comment)) {
   if (Change.Tok->is(TT_LineComment) || !Change.IsInsideToken) {
 LastBlockComment = &Change;
-  } else {
-if ((Change.StartOfBlockComment = LastBlockComment)) {
-  Change.IndentationOffset =
-  Change.StartOfTokenColumn -
-  Change.StartOfBlockComment->StartOfTokenColumn;
-}
+  } else if ((Change.StartOfBlockComment = LastBlockComment)) {
+Change.IndentationOffset =
+Change.StartOfTokenColumn -
+Change.StartOfBlockComment->StartOfTokenColumn;
   }
 } else {
   LastBlockComment = nullptr;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index ffc7e941398a1..14b169ebe5869 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -25439,8 +25439,7 @@ TEST_F(FormatTest, RemoveBraces) {
   verifyFormat("do {\n"
"  ++I;\n"
"} while (hasMore() && Filter(*I));",
-   "do { ++I; } while (hasMore() && Filter(*I));",
-   Style);
+   "do { ++I; } while (hasMore() && Filter(*I));", Style);
 
   verifyFormat("if (a)\n"
"  if (b)\n"



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


[clang] e9f2d47 - [clang-format][NFC] Remove unused FormatStyle members

2022-06-09 Thread via cfe-commits

Author: owenca
Date: 2022-06-09T22:34:31-07:00
New Revision: e9f2d47bfe29c31c7a1b43a2cc503ed9cdc0fbad

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

LOG: [clang-format][NFC] Remove unused FormatStyle members

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

Added: 


Modified: 
clang/include/clang/Format/Format.h

Removed: 




diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index d53e5d020c4a..bbd96af6154a 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -395,11 +395,6 @@ struct FormatStyle {
   /// \version 9
   bool AllowAllArgumentsOnNextLine;
 
-  /// This option is **deprecated**. See ``NextLine`` of
-  /// ``PackConstructorInitializers``.
-  /// \version 9
-  bool AllowAllConstructorInitializersOnNextLine;
-
   /// If the function declaration doesn't fit on a line,
   /// allow putting all parameters of a function declaration onto
   /// the next line even if ``BinPackParameters`` is ``false``.
@@ -1883,11 +1878,6 @@ struct FormatStyle {
   /// \version 5
   bool CompactNamespaces;
 
-  /// This option is **deprecated**. See ``CurrentLine`` of
-  /// ``PackConstructorInitializers``.
-  /// \version 3.7
-  bool ConstructorInitializerAllOnOneLineOrOnePerLine;
-
   /// The number of characters to use for indentation of constructor
   /// initializer lists as well as inheritance lists.
   /// \version 3.7



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


[clang] 1d3d5ec - [Documentation] Fixed typos in LibASTMatchers tutorial

2022-06-10 Thread via cfe-commits

Author: isuckatcs
Date: 2022-06-10T10:22:36+02:00
New Revision: 1d3d5ecea5f07546a9755a1d4546dbe4930af624

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

LOG: [Documentation] Fixed typos in LibASTMatchers tutorial

There was one missing parenthesis and a typo in the mentioned
part of the documentation.

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

Added: 


Modified: 
clang/docs/LibASTMatchersTutorial.rst

Removed: 




diff  --git a/clang/docs/LibASTMatchersTutorial.rst 
b/clang/docs/LibASTMatchersTutorial.rst
index 3f396dd39ded1..37c9f178fa8df 100644
--- a/clang/docs/LibASTMatchersTutorial.rst
+++ b/clang/docs/LibASTMatchersTutorial.rst
@@ -399,7 +399,7 @@ in the callback. So we start with:
 
 .. code-block:: c++
 
-  hasCondition(binaryOperator(hasOperatorName("<"))
+  hasCondition(binaryOperator(hasOperatorName("<")))
 
 It makes sense to ensure that the left-hand side is a reference to a
 variable, and that the right-hand side has integer type.
@@ -529,7 +529,7 @@ address, all we need to do is make sure neither 
``ValueDecl`` (base class of
   }
 
 If execution reaches the end of ``LoopPrinter::run()``, we know that the
-loop shell that looks like
+loop shell looks like
 
 .. code-block:: c++
 



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


[clang] 6cf8348 - [NFC][clang] Fix typo

2022-06-11 Thread via cfe-commits

Author: Sheng
Date: 2022-06-11T15:59:05+08:00
New Revision: 6cf83480ea631b05bdab8b32a5903728685a6c2a

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

LOG: [NFC][clang] Fix typo

Change 'otuer' to 'outer'.

Added: 


Modified: 
clang/include/clang/Sema/Template.h

Removed: 




diff  --git a/clang/include/clang/Sema/Template.h 
b/clang/include/clang/Sema/Template.h
index 540d2c9aa87e..5dcde77b5dd3 100644
--- a/clang/include/clang/Sema/Template.h
+++ b/clang/include/clang/Sema/Template.h
@@ -398,7 +398,7 @@ enum class TemplateSubstitutionKind : char {
   return newScope;
 }
 
-/// deletes the given scope, and all otuer scopes, down to the
+/// deletes the given scope, and all outer scopes, down to the
 /// given outermost scope.
 static void deleteScopes(LocalInstantiationScope *Scope,
  LocalInstantiationScope *Outermost) {



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


[clang] 05d7710 - [clang-format] Fix a bug in RemoveBracesLLVM

2022-06-11 Thread via cfe-commits

Author: owenca
Date: 2022-06-11T01:12:11-07:00
New Revision: 05d771021ad9de12f3e657d464d18731a13578ab

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

LOG: [clang-format] Fix a bug in RemoveBracesLLVM

Remove the braces of an else block only if the r_brace of the block
is followed by an if.

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

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 d2d69aabfd80a..2721949794195 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2610,6 +2610,7 @@ FormatToken 
*UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
 nextToken();
 handleAttributes();
 if (FormatTok->is(tok::l_brace)) {
+  const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
   FormatTok->setFinalizedType(TT_ElseLBrace);
   ElseLeftBrace = FormatTok;
   CompoundStatementIndenter Indenter(this, Style, Line->Level);
@@ -2621,7 +2622,7 @@ FormatToken 
*UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
 KeepElseBraces = KeepElseBraces ||
  ElseBlockKind == IfStmtKind::IfOnly ||
  ElseBlockKind == IfStmtKind::IfElseIf;
-  } else if (IfLBrace && !IfLBrace->Optional) {
+  } else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
 KeepElseBraces = true;
 assert(ElseLeftBrace->MatchingParen);
 markOptionalBraces(ElseLeftBrace);

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 14b169ebe5869..27984ecb0fa53 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -25576,6 +25576,17 @@ TEST_F(FormatTest, RemoveBraces) {
"  g;",
Style);
 
+  verifyFormat("if (a) {\n"
+   "  b;\n"
+   "  c;\n"
+   "} else { // comment\n"
+   "  if (d) {\n"
+   "e;\n"
+   "f;\n"
+   "  }\n"
+   "}",
+   Style);
+
   verifyFormat("if (a)\n"
"  b;\n"
"else if (c)\n"



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


[clang] 45b278f - [Clang][Doc][SafeStack] Fix deadlink (NFC)

2022-06-11 Thread via cfe-commits

Author: ksyx
Date: 2022-06-11T10:59:51-04:00
New Revision: 45b278f195b25e012fe441db13715cfecb377fce

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

LOG: [Clang][Doc][SafeStack] Fix deadlink (NFC)

Added: 


Modified: 
clang/docs/SafeStack.rst

Removed: 




diff  --git a/clang/docs/SafeStack.rst b/clang/docs/SafeStack.rst
index 8b5557bf59b0..c585315dff88 100644
--- a/clang/docs/SafeStack.rst
+++ b/clang/docs/SafeStack.rst
@@ -18,7 +18,7 @@ buffer overflows on the unsafe stack cannot be used to 
overwrite anything
 on the safe stack.
 
 SafeStack is a part of the `Code-Pointer Integrity (CPI) Project
-`_.
+`_.
 
 Performance
 ---
@@ -84,7 +84,7 @@ Known security limitations
 A complete protection against control-flow hijack attacks requires combining
 SafeStack with another mechanism that enforces the integrity of code pointers
 that are stored on the heap or the unsafe stack, such as `CPI
-`_, or a forward-edge control flow integrity
+`_, or a forward-edge control flow 
integrity
 mechanism that enforces correct calling conventions at indirect call sites,
 such as `IFCC `_ with arity
 checks. Clang has control-flow integrity protection scheme for :doc:`C++ 
virtual
@@ -186,7 +186,7 @@ Deprecated: This builtin function is an alias for
 Design
 ==
 
-Please refer to the `Code-Pointer Integrity 
`__
+Please refer to the `Code-Pointer Integrity 
`__
 project page for more information about the design of the SafeStack and its
 related technologies.
 



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


[clang] b1c300f - [clang-format] Handle deprecated options in dump_format_style.py

2022-06-12 Thread via cfe-commits

Author: owenca
Date: 2022-06-12T23:35:48-07:00
New Revision: b1c300fe6849a053482d117c7d3fa425da9a7430

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

LOG: [clang-format] Handle deprecated options in dump_format_style.py

Also add two deprecated options as comments back to Format.h.

Added: 


Modified: 
clang/docs/tools/dump_format_style.py
clang/include/clang/Format/Format.h

Removed: 




diff  --git a/clang/docs/tools/dump_format_style.py 
b/clang/docs/tools/dump_format_style.py
index fb074435e753e..e8bf29cfd2bee 100755
--- a/clang/docs/tools/dump_format_style.py
+++ b/clang/docs/tools/dump_format_style.py
@@ -267,6 +267,9 @@ class State:
   name = re.sub(r'struct\s+(\w+)\s*\{', '\\1', line)
   nested_struct = NestedStruct(name, comment)
 elif line.endswith(';'):
+  prefix = '// '
+  if line.startswith(prefix):
+line = line[len(prefix):]
   state = State.InStruct
   field_type, field_name = re.match(r'([<>:\w(,\s)]+)\s+(\w+);',
 line).groups()

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index bbd96af6154a4..8249060dc7c04 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -395,6 +395,11 @@ struct FormatStyle {
   /// \version 9
   bool AllowAllArgumentsOnNextLine;
 
+  /// This option is **deprecated**. See ``NextLine`` of
+  /// ``PackConstructorInitializers``.
+  /// \version 9
+  // bool AllowAllConstructorInitializersOnNextLine;
+
   /// If the function declaration doesn't fit on a line,
   /// allow putting all parameters of a function declaration onto
   /// the next line even if ``BinPackParameters`` is ``false``.
@@ -1878,6 +1883,11 @@ struct FormatStyle {
   /// \version 5
   bool CompactNamespaces;
 
+  /// This option is **deprecated**. See ``CurrentLine`` of
+  /// ``PackConstructorInitializers``.
+  /// \version 3.7
+  // bool ConstructorInitializerAllOnOneLineOrOnePerLine;
+
   /// The number of characters to use for indentation of constructor
   /// initializer lists as well as inheritance lists.
   /// \version 3.7



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


[clang] aebe24a - [RISCV] Add vread_csr and vwrite_csr to riscv_vector.h

2022-06-13 Thread via cfe-commits

Author: wangpc
Date: 2022-06-13T19:12:15+08:00
New Revision: aebe24a856d2f40284d940970d4e159319dbb90f

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

LOG: [RISCV] Add vread_csr and vwrite_csr to riscv_vector.h

These two functions are described in RVV intrinsics doc
to read/write RVV CSRs. This matches what GCC does.

Reviewed By: craig.topper

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

Added: 
clang/test/CodeGen/RISCV/rvv-intrinsics/vread-csr.c
clang/test/CodeGen/RISCV/rvv-intrinsics/vwrite-csr.c

Modified: 
clang/include/clang/Basic/riscv_vector.td

Removed: 




diff  --git a/clang/include/clang/Basic/riscv_vector.td 
b/clang/include/clang/Basic/riscv_vector.td
index 8a1e0eb742582..933a6c11f3359 100644
--- a/clang/include/clang/Basic/riscv_vector.td
+++ b/clang/include/clang/Basic/riscv_vector.td
@@ -1497,6 +1497,56 @@ multiclass RVVPseudoVNCVTBuiltin
+
+// CHECK-LABEL: @vread_csr_vstart(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i64 asm sideeffect "csrr\09$0, 
vstart", "=r,~{memory}"() #[[ATTR1:[0-9]+]], !srcloc !4
+// CHECK-NEXT:ret i64 [[TMP0]]
+//
+unsigned long vread_csr_vstart(void) {
+  return vread_csr(RVV_VSTART);
+}
+
+// CHECK-LABEL: @vread_csr_vxsat(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i64 asm sideeffect "csrr\09$0, 
vxsat", "=r,~{memory}"() #[[ATTR1]], !srcloc !5
+// CHECK-NEXT:ret i64 [[TMP0]]
+//
+unsigned long vread_csr_vxsat(void) {
+  return vread_csr(RVV_VXSAT);
+}
+
+// CHECK-LABEL: @vread_csr_vxrm(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i64 asm sideeffect "csrr\09$0, 
vxrm", "=r,~{memory}"() #[[ATTR1]], !srcloc !6
+// CHECK-NEXT:ret i64 [[TMP0]]
+//
+unsigned long vread_csr_vxrm(void) {
+  return vread_csr(RVV_VXRM);
+}
+
+// CHECK-LABEL: @vread_csr_vcsr(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i64 asm sideeffect "csrr\09$0, 
vcsr", "=r,~{memory}"() #[[ATTR1]], !srcloc !7
+// CHECK-NEXT:ret i64 [[TMP0]]
+//
+unsigned long vread_csr_vcsr(void) {
+  return vread_csr(RVV_VCSR);
+}

diff  --git a/clang/test/CodeGen/RISCV/rvv-intrinsics/vwrite-csr.c 
b/clang/test/CodeGen/RISCV/rvv-intrinsics/vwrite-csr.c
new file mode 100644
index 0..119fc018595e2
--- /dev/null
+++ b/clang/test/CodeGen/RISCV/rvv-intrinsics/vwrite-csr.c
@@ -0,0 +1,41 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -triple riscv64 -target-feature +v -disable-O0-optnone 
-emit-llvm %s -o - \
+// RUN: | opt -S -O2 | FileCheck  %s
+
+#include 
+
+// CHECK-LABEL: @vwrite_csr_vstart(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void asm sideeffect "csrw\09vstart, ${0:z}", 
"rJ,~{memory}"(i64 [[VALUE:%.*]]) #[[ATTR1:[0-9]+]], !srcloc !4
+// CHECK-NEXT:ret void
+//
+void vwrite_csr_vstart(unsigned long value) {
+  vwrite_csr(RVV_VSTART, value);
+}
+
+// CHECK-LABEL: @vwrite_csr_vxsat(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void asm sideeffect "csrw\09vxsat, ${0:z}", 
"rJ,~{memory}"(i64 [[VALUE:%.*]]) #[[ATTR1]], !srcloc !5
+// CHECK-NEXT:ret void
+//
+void vwrite_csr_vxsat(unsigned long value) {
+  vwrite_csr(RVV_VXSAT, value);
+}
+
+// CHECK-LABEL: @vwrite_csr_vxrm(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void asm sideeffect "csrw\09vxrm, ${0:z}", 
"rJ,~{memory}"(i64 [[VALUE:%.*]]) #[[ATTR1]], !srcloc !6
+// CHECK-NEXT:ret void
+//
+void vwrite_csr_vxrm(unsigned long value) {
+  vwrite_csr(RVV_VXRM, value);
+}
+
+// CHECK-LABEL: @vwrite_csr_vcsr(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void asm sideeffect "csrw\09vcsr, ${0:z}", 
"rJ,~{memory}"(i64 [[VALUE:%.*]]) #[[ATTR1]], !srcloc !7
+// CHECK-NEXT:ret void
+//
+void vwrite_csr_vcsr(unsigned long value) {
+  vwrite_csr(RVV_VCSR, value);
+}



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


[clang] 0f6f429 - Revert "[RISCV] Add vread_csr and vwrite_csr to riscv_vector.h"

2022-06-13 Thread via cfe-commits

Author: wangpc
Date: 2022-06-13T19:31:25+08:00
New Revision: 0f6f4295d10fe8cc9c3933b85dc9a66b840e3eca

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

LOG: Revert "[RISCV] Add vread_csr and vwrite_csr to riscv_vector.h"

This reverts commit aebe24a856d2f40284d940970d4e159319dbb90f.

`REQUIRES` for RISCV target is needed in tests.

Added: 


Modified: 
clang/include/clang/Basic/riscv_vector.td

Removed: 
clang/test/CodeGen/RISCV/rvv-intrinsics/vread-csr.c
clang/test/CodeGen/RISCV/rvv-intrinsics/vwrite-csr.c



diff  --git a/clang/include/clang/Basic/riscv_vector.td 
b/clang/include/clang/Basic/riscv_vector.td
index 933a6c11f3359..8a1e0eb742582 100644
--- a/clang/include/clang/Basic/riscv_vector.td
+++ b/clang/include/clang/Basic/riscv_vector.td
@@ -1497,56 +1497,6 @@ multiclass RVVPseudoVNCVTBuiltin
-
-// CHECK-LABEL: @vread_csr_vstart(
-// CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call i64 asm sideeffect "csrr\09$0, 
vstart", "=r,~{memory}"() #[[ATTR1:[0-9]+]], !srcloc !4
-// CHECK-NEXT:ret i64 [[TMP0]]
-//
-unsigned long vread_csr_vstart(void) {
-  return vread_csr(RVV_VSTART);
-}
-
-// CHECK-LABEL: @vread_csr_vxsat(
-// CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call i64 asm sideeffect "csrr\09$0, 
vxsat", "=r,~{memory}"() #[[ATTR1]], !srcloc !5
-// CHECK-NEXT:ret i64 [[TMP0]]
-//
-unsigned long vread_csr_vxsat(void) {
-  return vread_csr(RVV_VXSAT);
-}
-
-// CHECK-LABEL: @vread_csr_vxrm(
-// CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call i64 asm sideeffect "csrr\09$0, 
vxrm", "=r,~{memory}"() #[[ATTR1]], !srcloc !6
-// CHECK-NEXT:ret i64 [[TMP0]]
-//
-unsigned long vread_csr_vxrm(void) {
-  return vread_csr(RVV_VXRM);
-}
-
-// CHECK-LABEL: @vread_csr_vcsr(
-// CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call i64 asm sideeffect "csrr\09$0, 
vcsr", "=r,~{memory}"() #[[ATTR1]], !srcloc !7
-// CHECK-NEXT:ret i64 [[TMP0]]
-//
-unsigned long vread_csr_vcsr(void) {
-  return vread_csr(RVV_VCSR);
-}

diff  --git a/clang/test/CodeGen/RISCV/rvv-intrinsics/vwrite-csr.c 
b/clang/test/CodeGen/RISCV/rvv-intrinsics/vwrite-csr.c
deleted file mode 100644
index 119fc018595e2..0
--- a/clang/test/CodeGen/RISCV/rvv-intrinsics/vwrite-csr.c
+++ /dev/null
@@ -1,41 +0,0 @@
-// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
-// RUN: %clang_cc1 -triple riscv64 -target-feature +v -disable-O0-optnone 
-emit-llvm %s -o - \
-// RUN: | opt -S -O2 | FileCheck  %s
-
-#include 
-
-// CHECK-LABEL: @vwrite_csr_vstart(
-// CHECK-NEXT:  entry:
-// CHECK-NEXT:tail call void asm sideeffect "csrw\09vstart, ${0:z}", 
"rJ,~{memory}"(i64 [[VALUE:%.*]]) #[[ATTR1:[0-9]+]], !srcloc !4
-// CHECK-NEXT:ret void
-//
-void vwrite_csr_vstart(unsigned long value) {
-  vwrite_csr(RVV_VSTART, value);
-}
-
-// CHECK-LABEL: @vwrite_csr_vxsat(
-// CHECK-NEXT:  entry:
-// CHECK-NEXT:tail call void asm sideeffect "csrw\09vxsat, ${0:z}", 
"rJ,~{memory}"(i64 [[VALUE:%.*]]) #[[ATTR1]], !srcloc !5
-// CHECK-NEXT:ret void
-//
-void vwrite_csr_vxsat(unsigned long value) {
-  vwrite_csr(RVV_VXSAT, value);
-}
-
-// CHECK-LABEL: @vwrite_csr_vxrm(
-// CHECK-NEXT:  entry:
-// CHECK-NEXT:tail call void asm sideeffect "csrw\09vxrm, ${0:z}", 
"rJ,~{memory}"(i64 [[VALUE:%.*]]) #[[ATTR1]], !srcloc !6
-// CHECK-NEXT:ret void
-//
-void vwrite_csr_vxrm(unsigned long value) {
-  vwrite_csr(RVV_VXRM, value);
-}
-
-// CHECK-LABEL: @vwrite_csr_vcsr(
-// CHECK-NEXT:  entry:
-// CHECK-NEXT:tail call void asm sideeffect "csrw\09vcsr, ${0:z}", 
"rJ,~{memory}"(i64 [[VALUE:%.*]]) #[[ATTR1]], !srcloc !7
-// CHECK-NEXT:ret void
-//
-void vwrite_csr_vcsr(unsigned long value) {
-  vwrite_csr(RVV_VCSR, value);
-}



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


[clang] 93b4a41 - [RISCV] Add vread_csr and vwrite_csr to riscv_vector.h

2022-06-13 Thread via cfe-commits

Author: wangpc
Date: 2022-06-13T20:38:52+08:00
New Revision: 93b4a41b55102fb400ef6507068148761bb10be1

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

LOG: [RISCV] Add vread_csr and vwrite_csr to riscv_vector.h

These two functions are described in RVV intrinsics doc
to read/write RVV CSRs. This matches what GCC does.

This reapply aebe24a which was reverted in 0f6f429 due
to missing REQUIRES in tests.

Reviewed By: craig.topper

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

Added: 
clang/test/CodeGen/RISCV/rvv-intrinsics/vread-csr.c
clang/test/CodeGen/RISCV/rvv-intrinsics/vwrite-csr.c

Modified: 
clang/include/clang/Basic/riscv_vector.td

Removed: 




diff  --git a/clang/include/clang/Basic/riscv_vector.td 
b/clang/include/clang/Basic/riscv_vector.td
index 8a1e0eb742582..933a6c11f3359 100644
--- a/clang/include/clang/Basic/riscv_vector.td
+++ b/clang/include/clang/Basic/riscv_vector.td
@@ -1497,6 +1497,56 @@ multiclass RVVPseudoVNCVTBuiltin
+
+// CHECK-LABEL: @vread_csr_vstart(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i64 asm sideeffect "csrr\09$0, 
vstart", "=r,~{memory}"() #[[ATTR1:[0-9]+]], !srcloc !4
+// CHECK-NEXT:ret i64 [[TMP0]]
+//
+unsigned long vread_csr_vstart(void) {
+  return vread_csr(RVV_VSTART);
+}
+
+// CHECK-LABEL: @vread_csr_vxsat(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i64 asm sideeffect "csrr\09$0, 
vxsat", "=r,~{memory}"() #[[ATTR1]], !srcloc !5
+// CHECK-NEXT:ret i64 [[TMP0]]
+//
+unsigned long vread_csr_vxsat(void) {
+  return vread_csr(RVV_VXSAT);
+}
+
+// CHECK-LABEL: @vread_csr_vxrm(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i64 asm sideeffect "csrr\09$0, 
vxrm", "=r,~{memory}"() #[[ATTR1]], !srcloc !6
+// CHECK-NEXT:ret i64 [[TMP0]]
+//
+unsigned long vread_csr_vxrm(void) {
+  return vread_csr(RVV_VXRM);
+}
+
+// CHECK-LABEL: @vread_csr_vcsr(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i64 asm sideeffect "csrr\09$0, 
vcsr", "=r,~{memory}"() #[[ATTR1]], !srcloc !7
+// CHECK-NEXT:ret i64 [[TMP0]]
+//
+unsigned long vread_csr_vcsr(void) {
+  return vread_csr(RVV_VCSR);
+}

diff  --git a/clang/test/CodeGen/RISCV/rvv-intrinsics/vwrite-csr.c 
b/clang/test/CodeGen/RISCV/rvv-intrinsics/vwrite-csr.c
new file mode 100644
index 0..a94f599d7c7c3
--- /dev/null
+++ b/clang/test/CodeGen/RISCV/rvv-intrinsics/vwrite-csr.c
@@ -0,0 +1,42 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// REQUIRES: riscv-registered-target
+// RUN: %clang_cc1 -triple riscv64 -target-feature +v -disable-O0-optnone 
-emit-llvm %s -o - \
+// RUN: | opt -S -O2 | FileCheck  %s
+
+#include 
+
+// CHECK-LABEL: @vwrite_csr_vstart(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void asm sideeffect "csrw\09vstart, ${0:z}", 
"rJ,~{memory}"(i64 [[VALUE:%.*]]) #[[ATTR1:[0-9]+]], !srcloc !4
+// CHECK-NEXT:ret void
+//
+void vwrite_csr_vstart(unsigned long value) {
+  vwrite_csr(RVV_VSTART, value);
+}
+
+// CHECK-LABEL: @vwrite_csr_vxsat(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void asm sideeffect "csrw\09vxsat, ${0:z}", 
"rJ,~{memory}"(i64 [[VALUE:%.*]]) #[[ATTR1]], !srcloc !5
+// CHECK-NEXT:ret void
+//
+void vwrite_csr_vxsat(unsigned long value) {
+  vwrite_csr(RVV_VXSAT, value);
+}
+
+// CHECK-LABEL: @vwrite_csr_vxrm(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void asm sideeffect "csrw\09vxrm, ${0:z}", 
"rJ,~{memory}"(i64 [[VALUE:%.*]]) #[[ATTR1]], !srcloc !6
+// CHECK-NEXT:ret void
+//
+void vwrite_csr_vxrm(unsigned long value) {
+  vwrite_csr(RVV_VXRM, value);
+}
+
+// CHECK-LABEL: @vwrite_csr_vcsr(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void asm sideeffect "csrw\09vcsr, ${0:z}", 
"rJ,~{memory}"(i64 [[VALUE:%.*]]) #[[ATTR1]], !srcloc !7
+// CHECK-NEXT:ret void
+//
+void vwrite_csr_vcsr(unsigned long value) {
+  vwrite_csr(RVV_VCSR, value);
+}



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


<    2   3   4   5   6   7   8   9   10   11   >