[PATCH] D137960: [Lexer] Speedup LexTokenInternal

2022-11-15 Thread serge via Phabricator via cfe-commits
serge-sans-paille updated this revision to Diff 475699.
serge-sans-paille added a comment.

Add extra assert to ensure we start lexing in a clean state


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

https://reviews.llvm.org/D137960

Files:
  clang/include/clang/Lex/Token.h
  clang/lib/Lex/Lexer.cpp


Index: clang/lib/Lex/Lexer.cpp
===
--- clang/lib/Lex/Lexer.cpp
+++ clang/lib/Lex/Lexer.cpp
@@ -3516,10 +3516,9 @@
 /// token, not a normal token, as such, it is an internal interface.  It 
assumes
 /// that the Flags of result have been cleared before calling this.
 bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
-LexNextToken:
-  // New token, can't need cleaning yet.
-  Result.clearFlag(Token::NeedsCleaning);
-  Result.setIdentifierInfo(nullptr);
+LexStart:
+  assert(!Result.needsCleaning() && "Result doesn't need cleaning");
+  assert(!Result.hasPtrData() && "Result has been reset");
 
   // CurPtr - Cache BufferPtr in an automatic variable.
   const char *CurPtr = BufferPtr;
@@ -4141,7 +4140,7 @@
   CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
 } else if (Char == '|') {
   // If this is '|||' and we're in a conflict marker, ignore it.
-  if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
+  if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr - 1))
 goto LexNextToken;
   Kind = tok::pipepipe;
   CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
@@ -4170,7 +4169,7 @@
 Char = getCharAndSize(CurPtr, SizeTmp);
 if (Char == '=') {
   // If this is '' and we're in a conflict marker, ignore it.
-  if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
+  if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr - 1))
 goto LexNextToken;
 
   Kind = tok::equalequal;
@@ -4301,6 +4300,10 @@
 
   // We parsed the directive; lex a token with the new state.
   return false;
+
+LexNextToken:
+  Result.clearFlag(Token::NeedsCleaning);
+  goto LexStart;
 }
 
 const char *Lexer::convertDependencyDirectiveToken(
Index: clang/include/clang/Lex/Token.h
===
--- clang/include/clang/Lex/Token.h
+++ clang/include/clang/Lex/Token.h
@@ -175,6 +175,8 @@
 Loc = SourceLocation().getRawEncoding();
   }
 
+  bool hasPtrData() const { return PtrData != nullptr; }
+
   IdentifierInfo *getIdentifierInfo() const {
 assert(isNot(tok::raw_identifier) &&
"getIdentifierInfo() on a tok::raw_identifier token!");


Index: clang/lib/Lex/Lexer.cpp
===
--- clang/lib/Lex/Lexer.cpp
+++ clang/lib/Lex/Lexer.cpp
@@ -3516,10 +3516,9 @@
 /// token, not a normal token, as such, it is an internal interface.  It assumes
 /// that the Flags of result have been cleared before calling this.
 bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
-LexNextToken:
-  // New token, can't need cleaning yet.
-  Result.clearFlag(Token::NeedsCleaning);
-  Result.setIdentifierInfo(nullptr);
+LexStart:
+  assert(!Result.needsCleaning() && "Result doesn't need cleaning");
+  assert(!Result.hasPtrData() && "Result has been reset");
 
   // CurPtr - Cache BufferPtr in an automatic variable.
   const char *CurPtr = BufferPtr;
@@ -4141,7 +4140,7 @@
   CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
 } else if (Char == '|') {
   // If this is '|||' and we're in a conflict marker, ignore it.
-  if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
+  if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr - 1))
 goto LexNextToken;
   Kind = tok::pipepipe;
   CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
@@ -4170,7 +4169,7 @@
 Char = getCharAndSize(CurPtr, SizeTmp);
 if (Char == '=') {
   // If this is '' and we're in a conflict marker, ignore it.
-  if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
+  if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr - 1))
 goto LexNextToken;
 
   Kind = tok::equalequal;
@@ -4301,6 +4300,10 @@
 
   // We parsed the directive; lex a token with the new state.
   return false;
+
+LexNextToken:
+  Result.clearFlag(Token::NeedsCleaning);
+  goto LexStart;
 }
 
 const char *Lexer::convertDependencyDirectiveToken(
Index: clang/include/clang/Lex/Token.h
===
--- clang/include/clang/Lex/Token.h
+++ clang/include/clang/Lex/Token.h
@@ -175,6 +175,8 @@
 Loc = SourceLocation().getRawEncoding();
   }
 
+  bool hasPtrData() const { return PtrData != nullptr; }
+
   IdentifierInfo *getIdentifierInfo() const {
 assert(isNot(tok::raw_identifier) &&
"getIdentifierInfo() on a tok::raw_identifier token!");
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://li

[PATCH] D127284: [clang-repl] Support statements on global scope in incremental mode.

2022-11-15 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: clang/lib/AST/Decl.cpp:5264
+
+FunctionDecl *TopLevelStmtDecl::getOrConvertToFunction() {
+  if (FD)

I would hope that we can remove this. Instead, I think we can teach `CodeGen` 
to emit a sequence of `TopLevelStmtDecl`s directly as an LLVM IR function -- if 
it's not emitted anything else nor flushed its IR output since it last emitted 
a `TopLevelStmtDecl`, then reuse and extend the previous `Function`, otherwise 
create a new one. That would also allow us to make `TopLevelStmtDecl` model 
exactly one `Stmt`, which seems cleaner.



Comment at: clang/lib/Parse/ParseTentative.cpp:52-53
+  assert(getLangOpts().CPlusPlus && "Must be called for C++ only.");
+  if (DisambiguatingWithExpression) {
+if (Tok.is(tok::identifier)) {
+  RevertingTentativeParsingAction TPA(*this);

Can we sink this into the `switch` on the token kind below?



Comment at: clang/lib/Parse/Parser.cpp:1033
+!isDeclarationStatement(/*DisambiguatingWithExpression=*/true))
+  SingleDecl = ParseTopLevelStmtDecl();
+

v.g.vassilev wrote:
> There is a remaining challenge which probably could be addressed outside of 
> this patch.
> 
> Consider this statement block:
> ```
> int i =  12;
> ++i; 
> i--;
> 
> template struct A { };
> ```
> 
> Ideally we should model `++i; i--;` as a single `TopLevelStmtDecl` as the 
> statement block is contiguous. That would require the creation of 2 AST nodes 
> per block (one for the `TopLevelStmtDecl` and one for its conversion to 
> `FunctionDecl`). This will give us also a nice property on the REPL side 
> where the user could decide to squash multiple statements into a statement 
> block to save on memory.
> 
> To do so, we will need to use `isDeclarationStatement` as a stop rule in 
> `ParseTopLevelDecl`. In turn, this would mean that we should duplicate all of 
> the switch cases described in the `ParseExternalDeclaration` function here. 
> [We need teach  `isDeclarationStatement` everything we know about 
> declarations, eg. it must tell us to stop when we see definition `struct A`].
> 
> The last version of this patch goes in the opposite direction, trying to 
> minimize the code duplication (bloat?) by wrapping each global statement into 
> a `TopLevelStmtDecl`, reusing the logic in `ParseExternalDeclaration`. 
> However, we pay the price for 2 AST node allocations per global statement. 
> That is a serious hit for people that want to control the parsing granularity 
> of an interpreter.
> 
> I wonder if we can do something better hitting both requirements in some 
> smart way I cannot see...
It seems to me that the big cost here is creating a `FunctionDecl` and all of 
its ancillary components; a `TopLevelStmtDecl` is pretty cheap. I don't think 
it should be necessary to create that `FunctionDecl` at all -- we should be 
able to go straight from `TopLevelStmtDecl` to an IR function like we go 
straight from a `VarDecl` for a global function to its initializer IR function 
without creating a `FunctionDecl`.


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

https://reviews.llvm.org/D127284

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


[PATCH] D137488: [clang][Interp] Array initialization via string literal

2022-11-15 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 475697.
tbaeder marked 2 inline comments as done.

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

https://reviews.llvm.org/D137488

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/test/AST/Interp/literals.cpp


Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -350,6 +350,46 @@
 #endif
 
 #pragma clang diagnostic pop
+
+  constexpr char foo[12] = "abc";
+  static_assert(foo[0] == 'a', "");
+  static_assert(foo[1] == 'b', "");
+  static_assert(foo[2] == 'c', "");
+  static_assert(foo[3] == 0, "");
+  static_assert(foo[11] == 0, "");
+
+  constexpr char foo2[] = "abc\0def";
+  static_assert(foo2[0] == 'a', "");
+  static_assert(foo2[3] == '\0', "");
+  static_assert(foo2[6] == 'f', "");
+  static_assert(foo2[7] == '\0', "");
+  static_assert(foo2[8] == '\0', ""); // expected-error {{not an integral 
constant expression}} \
+  // expected-note {{read of dereferenced 
one-past-the-end pointer}} \
+  // ref-error {{not an integral constant 
expression}} \
+  // ref-note {{read of dereferenced 
one-past-the-end pointer}}
+
+  constexpr char foo3[4] = "abc";
+  static_assert(foo3[3] == '\0', "");
+  static_assert(foo3[4] == '\0', ""); // expected-error {{not an integral 
constant expression}} \
+  // expected-note {{read of dereferenced 
one-past-the-end pointer}} \
+  // ref-error {{not an integral constant 
expression}} \
+  // ref-note {{read of dereferenced 
one-past-the-end pointer}}
+
+  constexpr char foo4[2] = "abcd"; // expected-error {{initializer-string for 
char array is too long}} \
+   // ref-error {{initializer-string for char 
array is too long}}
+  static_assert(foo4[0] == 'a', "");
+  static_assert(foo4[1] == 'b', "");
+  static_assert(foo4[2] == '\0', ""); // expected-error {{not an integral 
constant expression}} \
+  // expected-note {{read of dereferenced 
one-past-the-end pointer}} \
+  // ref-error {{not an integral constant 
expression}} \
+  // ref-note {{read of dereferenced 
one-past-the-end pointer}}
+
+constexpr char foo5[12] = "abc\xff";
+#if defined(__CHAR_UNSIGNED__) || __CHAR_BIT__ > 8
+static_assert(foo5[3] == 255, "");
+#else
+static_assert(foo5[3] == -1, "");
+#endif
 };
 
 #if __cplusplus > 201402L
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1073,6 +1073,34 @@
 return false;
 }
 return true;
+  } else if (const auto *SL = dyn_cast(Initializer)) {
+const ConstantArrayType *CAT =
+Ctx.getASTContext().getAsConstantArrayType(SL->getType());
+assert(CAT && "a string literal that's not a constant array?");
+
+// If the initializer string is too long, a diagnostic has already been
+// emitted.
+unsigned N = std::min(SL->getLength(),
+  
static_cast(CAT->getSize().getZExtValue()));
+size_t CharWidth = SL->getCharByteWidth();
+
+for (unsigned I = 0; I != N; ++I) {
+  uint32_t CodeUnit = SL->getCodeUnit(I);
+
+  if (CharWidth == 1) {
+this->emitConstSint8(CodeUnit, SL);
+this->emitInitElemSint8(I, SL);
+  } else if (CharWidth == 2) {
+this->emitConstUint16(CodeUnit, SL);
+this->emitInitElemUint16(I, SL);
+  } else if (CharWidth == 4) {
+this->emitConstUint32(CodeUnit, SL);
+this->emitInitElemUint32(I, SL);
+  } else {
+llvm_unreachable("unsupported character width");
+  }
+}
+return true;
   }
 
   assert(false && "Unknown expression for array initialization");


Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -350,6 +350,46 @@
 #endif
 
 #pragma clang diagnostic pop
+
+  constexpr char foo[12] = "abc";
+  static_assert(foo[0] == 'a', "");
+  static_assert(foo[1] == 'b', "");
+  static_assert(foo[2] == 'c', "");
+  static_assert(foo[3] == 0, "");
+  static_assert(foo[11] == 0, "");
+
+  constexpr char foo2[] = "abc\0def";
+  static_assert(foo2[0] == 'a', "");
+  static_assert(foo2[3] == '\0', "");
+  static_assert(foo2[6] == 'f', "");
+  static_assert(foo2[7] == '\0', "");
+  static_assert(foo2[8] == '\0', ""); // expected-error {{not an integral constant expression}} \
+  // expected-note {{read of dereferenced one-past-the-end poi

[PATCH] D136809: [CMake] Ensure `CLANG_RESOURCE_DIR` is respected

2022-11-15 Thread LJC via Phabricator via cfe-commits
paperchalice updated this revision to Diff 475696.

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

https://reviews.llvm.org/D136809

Files:
  clang/lib/Headers/CMakeLists.txt
  clang/lib/Tooling/CMakeLists.txt
  clang/runtime/CMakeLists.txt
  cmake/Modules/GetClangResourceDir.cmake
  compiler-rt/cmake/base-config-ix.cmake
  lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp
  lldb/unittests/Expression/ClangParserTest.cpp
  llvm/cmake/modules/LLVMExternalProjectUtils.cmake
  openmp/CMakeLists.txt

Index: openmp/CMakeLists.txt
===
--- openmp/CMakeLists.txt
+++ openmp/CMakeLists.txt
@@ -79,8 +79,8 @@
 if(${OPENMP_STANDALONE_BUILD})
   set(LIBOMP_HEADERS_INSTALL_PATH "${CMAKE_INSTALL_INCLUDEDIR}")
 else()
-  string(REGEX MATCH "[0-9]+\\.[0-9]+(\\.[0-9]+)?" CLANG_VERSION ${PACKAGE_VERSION})
-  set(LIBOMP_HEADERS_INSTALL_PATH "${OPENMP_INSTALL_LIBDIR}/clang/${CLANG_VERSION}/include")
+  include(GetClangResourceDir)
+  get_clang_resource_dir(LIBOMP_HEADERS_INSTALL_PATH SUBDIR include)
 endif()
 
 # Build host runtime library, after LIBOMPTARGET variables are set since they are needed
Index: llvm/cmake/modules/LLVMExternalProjectUtils.cmake
===
--- llvm/cmake/modules/LLVMExternalProjectUtils.cmake
+++ llvm/cmake/modules/LLVMExternalProjectUtils.cmake
@@ -257,7 +257,11 @@
 if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
   string(REGEX MATCH "^[0-9]+" CLANG_VERSION_MAJOR
  ${PACKAGE_VERSION})
-  set(resource_dir "${LLVM_LIBRARY_DIR}/clang/${CLANG_VERSION_MAJOR}")
+  if(DEFINED CLANG_RESOURCE_DIR AND NOT CLANG_RESOURCE_DIR STREQUAL "")
+set(resource_dir ${LLVM_TOOLS_BINARY_DIR}/${CLANG_RESOURCE_DIR})
+  else()
+set(resource_dir "${LLVM_LIBRARY_DIR}/clang/${CLANG_VERSION_MAJOR}")
+  endif()
   set(flag_types ASM C CXX MODULE_LINKER SHARED_LINKER EXE_LINKER)
   foreach(type ${flag_types})
 set(${type}_flag -DCMAKE_${type}_FLAGS=-resource-dir=${resource_dir})
Index: lldb/unittests/Expression/ClangParserTest.cpp
===
--- lldb/unittests/Expression/ClangParserTest.cpp
+++ lldb/unittests/Expression/ClangParserTest.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "clang/Basic/Version.h"
+#include "clang/Config/config.h"
 
 #include "Plugins/ExpressionParser/Clang/ClangHost.h"
 #include "TestingSupport/SubsystemRAII.h"
@@ -37,12 +38,16 @@
 TEST_F(ClangHostTest, ComputeClangResourceDirectory) {
 #if !defined(_WIN32)
   std::string path_to_liblldb = "/foo/bar/lib/";
-  std::string path_to_clang_dir =
-  "/foo/bar/" LLDB_INSTALL_LIBDIR_BASENAME "/clang/" CLANG_VERSION_MAJOR_STRING;
+  std::string path_to_clang_dir = CLANG_RESOURCE_DIR[0]
+  ? "/foo/bar/bin/" CLANG_RESOURCE_DIR
+  : "/foo/bar/" LLDB_INSTALL_LIBDIR_BASENAME
+"/clang/" CLANG_VERSION_MAJOR_STRING;
 #else
   std::string path_to_liblldb = "C:\\foo\\bar\\lib";
   std::string path_to_clang_dir =
-  "C:\\foo\\bar\\lib\\clang\\" CLANG_VERSION_MAJOR_STRING;
+  CLANG_RESOURCE_DIR[0]
+  ? "C:\\foo\\bar\\bin\\" CLANG_RESOURCE_DIR
+  : "C:\\foo\\bar\\lib\\clang\\" CLANG_VERSION_MAJOR_STRING;
 #endif
   EXPECT_EQ(ComputeClangResourceDir(path_to_liblldb), path_to_clang_dir);
 
Index: lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp
===
--- lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp
+++ lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp
@@ -54,8 +54,11 @@
 
   static const llvm::StringRef kResourceDirSuffixes[] = {
   // LLVM.org's build of LLDB uses the clang resource directory placed
-  // in $install_dir/lib{,64}/clang/$clang_version.
-  CLANG_INSTALL_LIBDIR_BASENAME "/clang/" CLANG_VERSION_MAJOR_STRING,
+  // in $install_dir/lib{,64}/clang/$clang_version or
+  // $install_dir/bin/$CLANG_RESOURCE_DIR
+  CLANG_RESOURCE_DIR[0] ? "bin/" CLANG_RESOURCE_DIR
+: CLANG_INSTALL_LIBDIR_BASENAME
+  "/clang/" CLANG_VERSION_MAJOR_STRING,
   // swift-lldb uses the clang resource directory copied from swift, which
   // by default is placed in $install_dir/lib{,64}/lldb/clang. LLDB places
   // it there, so we use LLDB_INSTALL_LIBDIR_BASENAME.
Index: compiler-rt/cmake/base-config-ix.cmake
===
--- compiler-rt/cmake/base-config-ix.cmake
+++ compiler-rt/cmake/base-config-ix.cmake
@@ -7,6 +7,7 @@
 include(CheckIncludeFile)
 include(CheckCXXSourceCompiles)
 include(GNUInstallDirs)
+include(GetClangResourceDir)
 include(ExtendPath)
 
 check_include_file(unwind.h HAVE_UNWIND_H)
@@ -43,9 +44,9 @@
   

[PATCH] D138094: [LoongArch] Add intrinsics for ibar, break and syscall

2022-11-15 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: clang/include/clang/Basic/BuiltinsLoongArch.def:20-23
 TARGET_BUILTIN(__builtin_loongarch_dbar, "vIUi", "nc", "")
+TARGET_BUILTIN(__builtin_loongarch_ibar, "vIUi", "nc", "")
+TARGET_BUILTIN(__builtin_loongarch_break, "vIUi", "nc", "")
+TARGET_BUILTIN(__builtin_loongarch_syscall, "vIUi", "nc", "")

These all have I parameters but the underlying intrinsic wasn't marked with 
immarg 



Comment at: clang/test/CodeGen/LoongArch/intrinsic-error.c:21
+  __builtin_loongarch_ibar(-1); // expected-error {{argument value 4294967295 
is outside the valid range [0, 32767]}}
+}
+

Should also test non-constant cases 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138094

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


[PATCH] D138094: [LoongArch] Add intrinsics for ibar, break and syscall

2022-11-15 Thread Gong LingQin via Phabricator via cfe-commits
gonglingqin created this revision.
gonglingqin added reviewers: xen0n, xry111, SixWeining, wangleiat, MaskRay, 
XiaodongLoong.
Herald added subscribers: StephenFan, hiraditya.
Herald added a project: All.
gonglingqin requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

Diagnostics for intrinsic input parameters have also been added.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138094

Files:
  clang/include/clang/Basic/BuiltinsLoongArch.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Headers/larchintrin.h
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/LoongArch/intrinsic-error.c
  clang/test/CodeGen/LoongArch/intrinsic.c
  llvm/include/llvm/IR/IntrinsicsLoongArch.td
  llvm/lib/Target/LoongArch/LoongArchISelLowering.cpp
  llvm/lib/Target/LoongArch/LoongArchISelLowering.h
  llvm/lib/Target/LoongArch/LoongArchInstrInfo.td
  llvm/test/CodeGen/LoongArch/intrinsic-error.ll
  llvm/test/CodeGen/LoongArch/intrinsic.ll

Index: llvm/test/CodeGen/LoongArch/intrinsic.ll
===
--- llvm/test/CodeGen/LoongArch/intrinsic.ll
+++ llvm/test/CodeGen/LoongArch/intrinsic.ll
@@ -3,6 +3,9 @@
 ; RUN: llc --mtriple=loongarch64 < %s | FileCheck %s
 
 declare void @llvm.loongarch.dbar(i32)
+declare void @llvm.loongarch.ibar(i32)
+declare void @llvm.loongarch.break(i32)
+declare void @llvm.loongarch.syscall(i32)
 
 define void @foo() nounwind {
 ; CHECK-LABEL: foo:
@@ -13,3 +16,33 @@
   call void @llvm.loongarch.dbar(i32 0)
   ret void
 }
+
+define void @ibar() nounwind {
+; CHECK-LABEL: ibar:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:ibar 0
+; CHECK-NEXT:ret
+entry:
+  call void @llvm.loongarch.ibar(i32 0)
+  ret void
+}
+
+define void @break() nounwind {
+; CHECK-LABEL: break:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:break 1
+; CHECK-NEXT:ret
+entry:
+  call void @llvm.loongarch.break(i32 1)
+  ret void
+}
+
+define void @syscall() nounwind {
+; CHECK-LABEL: syscall:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:syscall 1
+; CHECK-NEXT:ret
+entry:
+  call void @llvm.loongarch.syscall(i32 1)
+  ret void
+}
Index: llvm/test/CodeGen/LoongArch/intrinsic-error.ll
===
--- llvm/test/CodeGen/LoongArch/intrinsic-error.ll
+++ llvm/test/CodeGen/LoongArch/intrinsic-error.ll
@@ -1,6 +1,11 @@
 ; RUN: not llc --mtriple=loongarch32 --disable-verify < %s 2>&1 | FileCheck %s
 ; RUN: not llc --mtriple=loongarch64 --disable-verify < %s 2>&1 | FileCheck %s
 
+declare void @llvm.loongarch.dbar(i32)
+declare void @llvm.loongarch.ibar(i32)
+declare void @llvm.loongarch.break(i32)
+declare void @llvm.loongarch.syscall(i32)
+
 define void @dbar_not_constant(i32 %x) nounwind {
 ; CHECK: argument to '__builtin_loongarch_dbar' must be a constant integer
 entry:
@@ -8,6 +13,27 @@
   ret void
 }
 
+define void @ibar(i32 %x) nounwind {
+; CHECK: argument to '__builtin_loongarch_ibar' must be a constant integer
+entry:
+  call void @llvm.loongarch.ibar(i32 %x)
+  ret void
+}
+
+define void @break(i32 %x) nounwind {
+; CHECK: argument to '__builtin_loongarch_break' must be a constant integer
+entry:
+  call void @llvm.loongarch.break(i32 %x)
+  ret void
+}
+
+define void @syscall(i32 %x) nounwind {
+; CHECK: argument to '__builtin_loongarch_syscall' must be a constant integer
+entry:
+  call void @llvm.loongarch.syscall(i32 %x)
+  ret void
+}
+
 define void @dbar_imm_out_of_hi_range() nounwind {
 ; CHECK: argument to '__builtin_loongarch_dbar' out of range
 entry:
@@ -22,4 +48,44 @@
   ret void
 }
 
-declare void @llvm.loongarch.dbar(i32)
+define void @ibar_imm_out_of_hi_range() nounwind {
+; CHECK: argument to '__builtin_loongarch_ibar' out of range
+entry:
+  call void @llvm.loongarch.ibar(i32 32769)
+  ret void
+}
+
+define void @ibar_imm_out_of_lo_range() nounwind {
+; CHECK: argument to '__builtin_loongarch_ibar' out of range
+entry:
+  call void @llvm.loongarch.ibar(i32 -1)
+  ret void
+}
+
+define void @break_imm_out_of_hi_range() nounwind {
+; CHECK: argument to '__builtin_loongarch_break' out of range
+entry:
+  call void @llvm.loongarch.break(i32 32769)
+  ret void
+}
+
+define void @break_imm_out_of_lo_range() nounwind {
+; CHECK: argument to '__builtin_loongarch_break' out of range
+entry:
+  call void @llvm.loongarch.break(i32 -1)
+  ret void
+}
+
+define void @syscall_imm_out_of_hi_range() nounwind {
+; CHECK: argument to '__builtin_loongarch_syscall' out of range
+entry:
+  call void @llvm.loongarch.syscall(i32 32769)
+  ret void
+}
+
+define void @syscall_imm_out_of_lo_range() nounwind {
+; CHECK: argument to '__builtin_loongarch_syscall' out of range
+entry:
+  call void @llvm.loongarch.syscall(i32 -1)
+  ret void
+}
Index: llvm/lib/Target/LoongArch/LoongArchInstrInfo.td
===
--- llvm/lib/Target/LoongArch/LoongArchInstrInfo.

[PATCH] D138062: [clang] Don't include C++ Standard Library headers when -nostdinc is used

2022-11-15 Thread Petr Hosek via Phabricator via cfe-commits
phosek accepted this revision.
phosek added a comment.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138062

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


[PATCH] D138062: [clang] Don't include C++ Standard Library headers when -nostdinc is used

2022-11-15 Thread Michał Górny via Phabricator via cfe-commits
mgorny accepted this revision as: mgorny.
mgorny added a comment.

I'd say this is fine to land as 16.x. I'll be doing another snapshot for Gentoo 
next weekend, so if it lands by then, we're going to do some crash testing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138062

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


[PATCH] D137809: [LoongArch] Add immediate operand validity check for __builtin_loongarch_dbar

2022-11-15 Thread Gong LingQin via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGddbb21bdb579: [LoongArch] Add immediate operand validity 
check for __builtin_loongarch_dbar (authored by gonglingqin).

Changed prior to commit:
  https://reviews.llvm.org/D137809?vs=475333&id=475690#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137809

Files:
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/LoongArch/intrinsic-error.c
  llvm/test/CodeGen/LoongArch/intrinsic-error.ll


Index: llvm/test/CodeGen/LoongArch/intrinsic-error.ll
===
--- llvm/test/CodeGen/LoongArch/intrinsic-error.ll
+++ llvm/test/CodeGen/LoongArch/intrinsic-error.ll
@@ -8,11 +8,18 @@
   ret void
 }
 
-define void @dbar_imm_out_of_range() nounwind {
+define void @dbar_imm_out_of_hi_range() nounwind {
 ; CHECK: argument to '__builtin_loongarch_dbar' out of range
 entry:
   call void @llvm.loongarch.dbar(i32 32769)
   ret void
 }
 
+define void @dbar_imm_out_of_lo_range() nounwind {
+; CHECK: argument to '__builtin_loongarch_dbar' out of range
+entry:
+  call void @llvm.loongarch.dbar(i32 -1)
+  ret void
+}
+
 declare void @llvm.loongarch.dbar(i32)
Index: clang/test/CodeGen/LoongArch/intrinsic-error.c
===
--- clang/test/CodeGen/LoongArch/intrinsic-error.c
+++ clang/test/CodeGen/LoongArch/intrinsic-error.c
@@ -6,3 +6,11 @@
 int crc_w_d_w(long int a, int b) {
   return __builtin_loongarch_crc_w_d_w(a, b); // expected-error {{this builtin 
requires target: loongarch64}}
 }
+
+void dbar_out_of_hi_range() {
+  return __builtin_loongarch_dbar(32768); // expected-error {{argument value 
32768 is outside the valid range [0, 32767]}}
+}
+
+void dbar_out_of_lo_range() {
+  return __builtin_loongarch_dbar(-1); // expected-error {{argument value 
4294967295 is outside the valid range [0, 32767]}}
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -3685,6 +3685,9 @@
   diag::err_loongarch_builtin_requires_la64)
  << TheCall->getSourceRange();
 break;
+  case LoongArch::BI__builtin_loongarch_dbar:
+// Check if immediate is in [0, 32767].
+return SemaBuiltinConstantArgRange(TheCall, 0, 0, 32767);
   }
 
   return false;


Index: llvm/test/CodeGen/LoongArch/intrinsic-error.ll
===
--- llvm/test/CodeGen/LoongArch/intrinsic-error.ll
+++ llvm/test/CodeGen/LoongArch/intrinsic-error.ll
@@ -8,11 +8,18 @@
   ret void
 }
 
-define void @dbar_imm_out_of_range() nounwind {
+define void @dbar_imm_out_of_hi_range() nounwind {
 ; CHECK: argument to '__builtin_loongarch_dbar' out of range
 entry:
   call void @llvm.loongarch.dbar(i32 32769)
   ret void
 }
 
+define void @dbar_imm_out_of_lo_range() nounwind {
+; CHECK: argument to '__builtin_loongarch_dbar' out of range
+entry:
+  call void @llvm.loongarch.dbar(i32 -1)
+  ret void
+}
+
 declare void @llvm.loongarch.dbar(i32)
Index: clang/test/CodeGen/LoongArch/intrinsic-error.c
===
--- clang/test/CodeGen/LoongArch/intrinsic-error.c
+++ clang/test/CodeGen/LoongArch/intrinsic-error.c
@@ -6,3 +6,11 @@
 int crc_w_d_w(long int a, int b) {
   return __builtin_loongarch_crc_w_d_w(a, b); // expected-error {{this builtin requires target: loongarch64}}
 }
+
+void dbar_out_of_hi_range() {
+  return __builtin_loongarch_dbar(32768); // expected-error {{argument value 32768 is outside the valid range [0, 32767]}}
+}
+
+void dbar_out_of_lo_range() {
+  return __builtin_loongarch_dbar(-1); // expected-error {{argument value 4294967295 is outside the valid range [0, 32767]}}
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -3685,6 +3685,9 @@
   diag::err_loongarch_builtin_requires_la64)
  << TheCall->getSourceRange();
 break;
+  case LoongArch::BI__builtin_loongarch_dbar:
+// Check if immediate is in [0, 32767].
+return SemaBuiltinConstantArgRange(TheCall, 0, 0, 32767);
   }
 
   return false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] ddbb21b - [LoongArch] Add immediate operand validity check for __builtin_loongarch_dbar

2022-11-15 Thread via cfe-commits

Author: gonglingqin
Date: 2022-11-16T14:47:45+08:00
New Revision: ddbb21bdb579cc5b6092369b39aef376a8df4da1

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

LOG: [LoongArch] Add immediate operand validity check for 
__builtin_loongarch_dbar

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

Added: 


Modified: 
clang/lib/Sema/SemaChecking.cpp
clang/test/CodeGen/LoongArch/intrinsic-error.c
llvm/test/CodeGen/LoongArch/intrinsic-error.ll

Removed: 




diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 5a9c1750d8b32..75fb822f392dd 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -3685,6 +3685,9 @@ bool Sema::CheckLoongArchBuiltinFunctionCall(const 
TargetInfo &TI,
   diag::err_loongarch_builtin_requires_la64)
  << TheCall->getSourceRange();
 break;
+  case LoongArch::BI__builtin_loongarch_dbar:
+// Check if immediate is in [0, 32767].
+return SemaBuiltinConstantArgRange(TheCall, 0, 0, 32767);
   }
 
   return false;

diff  --git a/clang/test/CodeGen/LoongArch/intrinsic-error.c 
b/clang/test/CodeGen/LoongArch/intrinsic-error.c
index 5dc0cadd686ef..6f2b2ea3409e3 100644
--- a/clang/test/CodeGen/LoongArch/intrinsic-error.c
+++ b/clang/test/CodeGen/LoongArch/intrinsic-error.c
@@ -6,3 +6,11 @@
 int crc_w_d_w(long int a, int b) {
   return __builtin_loongarch_crc_w_d_w(a, b); // expected-error {{this builtin 
requires target: loongarch64}}
 }
+
+void dbar_out_of_hi_range() {
+  return __builtin_loongarch_dbar(32768); // expected-error {{argument value 
32768 is outside the valid range [0, 32767]}}
+}
+
+void dbar_out_of_lo_range() {
+  return __builtin_loongarch_dbar(-1); // expected-error {{argument value 
4294967295 is outside the valid range [0, 32767]}}
+}

diff  --git a/llvm/test/CodeGen/LoongArch/intrinsic-error.ll 
b/llvm/test/CodeGen/LoongArch/intrinsic-error.ll
index cdf69e9520508..a00cd8c5e6ac7 100644
--- a/llvm/test/CodeGen/LoongArch/intrinsic-error.ll
+++ b/llvm/test/CodeGen/LoongArch/intrinsic-error.ll
@@ -8,11 +8,18 @@ entry:
   ret void
 }
 
-define void @dbar_imm_out_of_range() nounwind {
+define void @dbar_imm_out_of_hi_range() nounwind {
 ; CHECK: argument to '__builtin_loongarch_dbar' out of range
 entry:
   call void @llvm.loongarch.dbar(i32 32769)
   ret void
 }
 
+define void @dbar_imm_out_of_lo_range() nounwind {
+; CHECK: argument to '__builtin_loongarch_dbar' out of range
+entry:
+  call void @llvm.loongarch.dbar(i32 -1)
+  ret void
+}
+
 declare void @llvm.loongarch.dbar(i32)



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


[PATCH] D136354: [Driver] Enable nested configuration files

2022-11-15 Thread Serge Pavlov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1f67dc8b7c22: [Driver] Enable nested configuration files 
(authored by sepavloff).

Changed prior to commit:
  https://reviews.llvm.org/D136354?vs=475400&id=475685#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136354

Files:
  clang/docs/UsersManual.rst
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/Inputs/config-6.cfg
  clang/test/Driver/config-file-errs.c
  clang/test/Driver/config-file.c
  clang/unittests/Driver/ToolChainTest.cpp
  llvm/lib/Support/CommandLine.cpp

Index: llvm/lib/Support/CommandLine.cpp
===
--- llvm/lib/Support/CommandLine.cpp
+++ llvm/lib/Support/CommandLine.cpp
@@ -1191,27 +1191,44 @@
 return Error::success();
 
   StringRef BasePath = llvm::sys::path::parent_path(FName);
-  for (auto I = NewArgv.begin(), E = NewArgv.end(); I != E; ++I) {
-const char *&Arg = *I;
-if (Arg == nullptr)
+  for (const char *&Arg : NewArgv) {
+if (!Arg)
   continue;
 
 // Substitute  with the file's base path.
 if (InConfigFile)
   ExpandBasePaths(BasePath, Saver, Arg);
 
-// Get expanded file name.
-StringRef FileName(Arg);
-if (!FileName.consume_front("@"))
-  continue;
-if (!llvm::sys::path::is_relative(FileName))
+// Discover the case, when argument should be transformed into '@file' and
+// evaluate 'file' for it.
+StringRef ArgStr(Arg);
+StringRef FileName;
+bool ConfigInclusion = false;
+if (ArgStr.consume_front("@")) {
+  FileName = ArgStr;
+  if (!llvm::sys::path::is_relative(FileName))
+continue;
+} else if (ArgStr.consume_front("--config=")) {
+  FileName = ArgStr;
+  ConfigInclusion = true;
+} else {
   continue;
+}
 
 // Update expansion construct.
 SmallString<128> ResponseFile;
 ResponseFile.push_back('@');
-ResponseFile.append(BasePath);
-llvm::sys::path::append(ResponseFile, FileName);
+if (ConfigInclusion && !llvm::sys::path::has_parent_path(FileName)) {
+  SmallString<128> FilePath;
+  if (!findConfigFile(FileName, FilePath))
+return createStringError(
+std::make_error_code(std::errc::no_such_file_or_directory),
+"cannot not find configuration file: " + FileName);
+  ResponseFile.append(FilePath);
+} else {
+  ResponseFile.append(BasePath);
+  llvm::sys::path::append(ResponseFile, FileName);
+}
 Arg = Saver.save(ResponseFile.str()).data();
   }
   return Error::success();
Index: clang/unittests/Driver/ToolChainTest.cpp
===
--- clang/unittests/Driver/ToolChainTest.cpp
+++ clang/unittests/Driver/ToolChainTest.cpp
@@ -652,4 +652,56 @@
 #undef INCLUDED1
 }
 
+TEST(ToolChainTest, NestedConfigFile) {
+  IntrusiveRefCntPtr DiagOpts = new DiagnosticOptions();
+  IntrusiveRefCntPtr DiagID(new DiagnosticIDs());
+  struct TestDiagnosticConsumer : public DiagnosticConsumer {};
+  DiagnosticsEngine Diags(DiagID, &*DiagOpts, new TestDiagnosticConsumer);
+  IntrusiveRefCntPtr FS(
+  new llvm::vfs::InMemoryFileSystem);
+
+#ifdef _WIN32
+  const char *TestRoot = "C:\\";
+#else
+  const char *TestRoot = "/";
+#endif
+  FS->setCurrentWorkingDirectory(TestRoot);
+
+  FS->addFile("/opt/sdk/root.cfg", 0,
+  llvm::MemoryBuffer::getMemBuffer("--config=platform.cfg\n"));
+  FS->addFile("/opt/sdk/platform.cfg", 0,
+  llvm::MemoryBuffer::getMemBuffer("--sysroot=/platform-sys\n"));
+  FS->addFile("/home/test/bin/platform.cfg", 0,
+  llvm::MemoryBuffer::getMemBuffer("--sysroot=/platform-bin\n"));
+
+  SmallString<128> ClangExecutable("/home/test/bin/clang");
+  FS->makeAbsolute(ClangExecutable);
+
+  // User file is absent - use system definitions.
+  {
+Driver TheDriver(ClangExecutable, "arm-linux-gnueabi", Diags,
+ "clang LLVM compiler", FS);
+std::unique_ptr C(TheDriver.BuildCompilation(
+{"/home/test/bin/clang", "--config", "root.cfg",
+ "--config-system-dir=/opt/sdk", "--config-user-dir=/home/test/sdk"}));
+ASSERT_TRUE(C);
+ASSERT_FALSE(C->containsError());
+EXPECT_EQ("/platform-sys", TheDriver.SysRoot);
+  }
+
+  // User file overrides system definitions.
+  FS->addFile("/home/test/sdk/platform.cfg", 0,
+  llvm::MemoryBuffer::getMemBuffer("--sysroot=/platform-user\n"));
+  {
+Driver TheDriver(ClangExecutable, "arm-linux-gnueabi", Diags,
+ "clang LLVM compiler", FS);
+std::unique_ptr C(TheDriver.BuildCompilation(
+{"/home/test/bin/clang", "--config", "root.cfg",
+ "--config-system-dir=/opt/sdk", "--config-user-dir=/home/test/sdk"}));
+ASSERT_TRUE(C);
+ASSERT_FALSE(C->containsError());
+EXP

[clang] 1f67dc8 - [Driver] Enable nested configuration files

2022-11-15 Thread Serge Pavlov via cfe-commits

Author: Serge Pavlov
Date: 2022-11-16T13:32:27+07:00
New Revision: 1f67dc8b7c225290d1b3eb93d90e2c9861aeefc0

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

LOG: [Driver] Enable nested configuration files

Users may partition parameters specified by configuration file and put
different groups into separate files. These files are inserted into the
main file using constructs `@file`. Relative file names in it are
resolved relative to the including configuration file and this is not
convenient in some cases. A configuration file, which resides in system
directory, may need to include a file with user-defined parameters and
still provide default definitions if such file is absent.

To solve such problems, the option `--config=` is allowed inside
configuration files. Like `@file` it results in insertion of
command-line arguments but the algorithm of file search is different and
allows overriding system definitions with user ones.

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

Added: 


Modified: 
clang/docs/UsersManual.rst
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/lib/Driver/Driver.cpp
clang/test/Driver/Inputs/config-6.cfg
clang/test/Driver/config-file-errs.c
clang/test/Driver/config-file.c
clang/unittests/Driver/ToolChainTest.cpp
llvm/lib/Support/CommandLine.cpp

Removed: 




diff  --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index 9b03db9e0f742..69dcd495d689c 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -985,7 +985,10 @@ configuration file:
 Files included by ``@file`` directives in configuration files are resolved
 relative to the including file. For example, if a configuration file
 ``~/.llvm/target.cfg`` contains the directive ``@os/linux.opts``, the file
-``linux.opts`` is searched for in the directory ``~/.llvm/os``.
+``linux.opts`` is searched for in the directory ``~/.llvm/os``. Another way to
+include a file content is using the command line option ``--config=``. It works
+similarly but the included file is searched for using the rules for 
configuration
+files.
 
 To generate paths relative to the configuration file, the  token 
may
 be used. This will expand to the absolute path of the directory containing the

diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 551ebf1c9bc2e..119ad57466b65 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -225,8 +225,6 @@ def note_drv_config_file_searched_in : Note<
   "was searched for in the directory: %0">;
 def err_drv_cannot_read_config_file : Error<
   "cannot read configuration file '%0': %1">;
-def err_drv_nested_config_file: Error<
-  "option '--config' is not allowed inside configuration file">;
 def err_drv_arg_requires_bitcode_input: Error<
   "option '%0' requires input to be LLVM bitcode">;
 

diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index fd9d5c21e67c9..c63160e55ea30 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -970,11 +970,6 @@ bool Driver::readConfigFile(StringRef FileName,
   if (ContainErrors)
 return true;
 
-  if (NewOptions->hasArg(options::OPT_config)) {
-Diag(diag::err_drv_nested_config_file);
-return true;
-  }
-
   // Claim all arguments that come from a configuration file so that the driver
   // does not warn on any that is unused.
   for (Arg *A : *NewOptions)

diff  --git a/clang/test/Driver/Inputs/config-6.cfg 
b/clang/test/Driver/Inputs/config-6.cfg
index 24d93cf8eca61..e54ec0c629709 100644
--- a/clang/test/Driver/Inputs/config-6.cfg
+++ b/clang/test/Driver/Inputs/config-6.cfg
@@ -1 +1 @@
---config config-5
+--config=config-4.cfg

diff  --git a/clang/test/Driver/config-file-errs.c 
b/clang/test/Driver/config-file-errs.c
index 85b3443a7e530..96b49b2acf8ab 100644
--- a/clang/test/Driver/config-file-errs.c
+++ b/clang/test/Driver/config-file-errs.c
@@ -4,12 +4,6 @@
 // CHECK-MISSING-FILE: argument to '--config' is missing (expected 1 value)
 
 
-//--- '--config' must not be found in config files.
-//
-// RUN: not %clang --config %S/Inputs/config-6.cfg 2>&1 | FileCheck %s 
-check-prefix CHECK-NESTED
-// CHECK-NESTED: option '--config' is not allowed inside configuration file
-
-
 //--- Argument of '--config' must be existing file, if it is specified by path.
 //
 // RUN: not %clang --config somewhere/nonexistent-config-file 2>&1 | FileCheck 
%s -check-prefix CHECK-NONEXISTENT

diff  --git a/clang/test/Driver/config-file.c b/clang/test/Driver/config-file.c
index 9c8d5be575f3c..9df830ca4c753 100644
--- a/clang/test/Driver/config-file.c
+++ b/clang/test/Driver/config-file.c
@@ -44,9 +4

[PATCH] D137751: Produce a more informative diagnostics when Clang runs out of source locations

2022-11-15 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

In D137751#3919162 , @alexfh wrote:

> I wonder whether we can include SLoc usage information into `-print-stats` 
> output?

Yeah, we could extend the source manager information there with something like 
this. It's a bit awkward to reuse this implementation because it's geared 
around producing notes, but it should be fairly straightforward to factor out 
some common code and extend `-print-stats` with it in a follow-up change.




Comment at: clang/include/clang/Basic/SourceManager.h:1695-1696
+  // Produce notes describing the current source location address space usage.
+  void noteSLocAddressSpaceUsage(DiagnosticsEngine &Diag,
+ unsigned MaxNotes = 50) const;
+

aaron.ballman wrote:
> Not that I'm opposed, but how did you arrive at 50?
I was aiming for a number that's small enough that the diagnostic won't run for 
pages (will fit into a relatively small scroll buffer) but large enough that it 
should capture problematic usage.

But, you know what, we should be consistent. A default of 32 would match our 
default limit for notes in constexpr and template backtraces; let's use that. 
Plus powers of 2 are the best arbitrary numbers.



Comment at: clang/lib/Basic/SourceManager.cpp:675
   LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
+  // TODO: Produce a proper diagnostic for this case.
   assert(NextLocalOffset + Length + 1 > NextLocalOffset &&

aaron.ballman wrote:
> Are you planning to do this as part of this patch, or is this more of an 
> aspirational FIXME for the future?
This is aspirational. I think it'll be a lot of work to make all the transitive 
callers of this be able to handle it failing.



Comment at: clang/lib/Basic/SourceManager.cpp:2251
+  uint64_t CountedSize = 0;
+  for (int IDIndex = -(int)LoadedSLocEntryTable.size() - 1;
+   IDIndex < (int)LocalSLocEntryTable.size(); ++IDIndex) {

shafik wrote:
> alexfh wrote:
> > Could you add a comment about the meaning of negative IDIndex values?
> Maybe make `-(int)LoadedSLocEntryTable.size()` a named variable may help 
> readability as well.  Perhaps also for `(int)LocalSLocEntryTable.size()` as 
> well.
Refactored to make it clearer what's going on, added comments.



Comment at: clang/lib/Basic/SourceManager.cpp:2281-2282
+  SortedUsage.reserve(Usage.size());
+  for (auto It = Usage.begin(); It != Usage.end(); ++It)
+SortedUsage.push_back(It);
+  auto Cmp = [](UsageMap::iterator A, UsageMap::iterator B) {

aaron.ballman wrote:
> llvm::copy?
This is forming a vector of iterators, not a vector of values. Hm, but... I 
think I can express this better with `MapVector` and avoid this copy in the 
process.



Comment at: clang/lib/Lex/Pragma.cpp:1187
+  // specifically report information about.
+  uint64_t MaxNotes = (uint64_t)-1;
+  Token ArgToken;

aaron.ballman wrote:
> `~0ULL`?
That would be `(unsigned long long)-1`, which isn't necessarily the same value.

But I think we can do better than forming a large unsigned number here; changed 
to use `Optional`.



Comment at: clang/test/Misc/sloc-usage.cpp:1
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+

aaron.ballman wrote:
> Should we do anything special about source locations from the command line, 
> or do those not contribute source locations? (e.g., `-D` or `-U`, force 
> include file, etc flags)
> 
> (Testing a forced include would be interesting regardless, just to ensure we 
> catch those the same as we do an `#include`.)
For `-D` etc, we get output that looks like this:

```
:1:1: note: file entered 2 times using 14778B of space
# 1 "" 3
^
```

... where the `:1:1` is the location of the first time we enter a 
`FileID` with a null corresponding `const FileEntry*`. I think these will all 
correspond to predefines and similar things, so the `:1:1` source 
location seems pretty reasonable.

I've added a test for `-include`.


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

https://reviews.llvm.org/D137751

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


[PATCH] D138091: [Clang] Fix Sema::ClassifyName so that it classifies EnumConstantDecl as NonType when they are brought into scope via using enum

2022-11-15 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik created this revision.
shafik added reviewers: erichkeane, aaron.ballman, urnathan.
Herald added a project: All.
shafik requested review of this revision.

Currently `Sema::ClassifyName(...)` in some cases when an `enumerator` is 
brought into scope via `using enum` during lookup it can end up being 
classified as an `OverloadSet`. It looks like this was never accounted for when 
`using enum` support was implemented and we need to add a check to allow an 
`EnumConstantDecl` to be classified as `NonType` even when it is a class member.

This fixes: 
https://github.com/llvm/llvm-project/issues/58057
https://github.com/llvm/llvm-project/issues/59014
https://github.com/llvm/llvm-project/issues/54746


https://reviews.llvm.org/D138091

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/test/SemaCXX/cxx20-using-enum.cpp


Index: clang/test/SemaCXX/cxx20-using-enum.cpp
===
--- clang/test/SemaCXX/cxx20-using-enum.cpp
+++ clang/test/SemaCXX/cxx20-using-enum.cpp
@@ -240,4 +240,33 @@
 
 } // namespace Thirteen
 
+namespace GH58057 {
+struct Wrap {
+enum Things {
+  Value1,
+  Value2
+};
+};
+
+using enum Wrap::Things;
+
+int f() {
+  return (Value1 | Value2);
+}
+}
+
+namespace GH59014 {
+struct X {
+  enum Masks {Mask = 1,Shift = 0};
+};
+
+void f(int a) {
+  using enum X::Masks;
+
+  auto u = (Mask);
+  auto v = (Mask << Shift);
+  void (~(Mask));
+}
+}
+
 #endif
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -1247,7 +1247,8 @@
   // member accesses, as we need to defer certain access checks until we know
   // the context.
   bool ADL = UseArgumentDependentLookup(SS, Result, 
NextToken.is(tok::l_paren));
-  if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
+  if (Result.isSingleResult() && !ADL &&
+  (!FirstDecl->isCXXClassMember() || isa(FirstDecl)))
 return NameClassification::NonType(Result.getRepresentativeDecl());
 
   // Otherwise, this is an overload set that we will need to resolve later.


Index: clang/test/SemaCXX/cxx20-using-enum.cpp
===
--- clang/test/SemaCXX/cxx20-using-enum.cpp
+++ clang/test/SemaCXX/cxx20-using-enum.cpp
@@ -240,4 +240,33 @@
 
 } // namespace Thirteen
 
+namespace GH58057 {
+struct Wrap {
+enum Things {
+  Value1,
+  Value2
+};
+};
+
+using enum Wrap::Things;
+
+int f() {
+  return (Value1 | Value2);
+}
+}
+
+namespace GH59014 {
+struct X {
+  enum Masks {Mask = 1,Shift = 0};
+};
+
+void f(int a) {
+  using enum X::Masks;
+
+  auto u = (Mask);
+  auto v = (Mask << Shift);
+  void (~(Mask));
+}
+}
+
 #endif
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -1247,7 +1247,8 @@
   // member accesses, as we need to defer certain access checks until we know
   // the context.
   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
-  if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
+  if (Result.isSingleResult() && !ADL &&
+  (!FirstDecl->isCXXClassMember() || isa(FirstDecl)))
 return NameClassification::NonType(Result.getRepresentativeDecl());
 
   // Otherwise, this is an overload set that we will need to resolve later.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137865: [clang-format][NFC] Improve documentation on ReflowComments

2022-11-15 Thread Björn Schäpers via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG40c1476e3ae2: [clang-format][NFC] Improve documentation on 
ReflowComments (authored by HazardyKnusperkeks).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137865

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


Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -3070,7 +3070,9 @@
   ReferenceAlignmentStyle ReferenceAlignment;
 
   // clang-format off
-  /// If ``true``, clang-format will attempt to re-flow comments.
+  /// If ``true``, clang-format will attempt to re-flow comments. That is it
+  /// will touch a comment and *reflow* long comments into new lines, trying to
+  /// obey the ``ColumnLimit``.
   /// \code
   ///false:
   ///// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with 
plenty of information
@@ -3821,7 +3823,7 @@
   /// \version 3.7
   bool SpacesInCStyleCastParentheses;
 
-  /// Control of spaces within a single line comment
+  /// Control of spaces within a single line comment.
   struct SpacesInLineComment {
 /// The minimum number of spaces at the start of the comment.
 unsigned Minimum;
@@ -3858,6 +3860,8 @@
   ///   ///  - Foo/// - Foo
   ///   ///- Bar  ///   - Bar
   /// \endcode
+  ///
+  /// This option has only effect if ``ReflowComments`` is set to ``true``.
   /// \version 13
   SpacesInLineComment SpacesInLineCommentPrefix;
 
Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -3795,7 +3795,9 @@
 
 
 **ReflowComments** (``Boolean``) :versionbadge:`clang-format 3.8`
-  If ``true``, clang-format will attempt to re-flow comments.
+  If ``true``, clang-format will attempt to re-flow comments. That is it
+  will touch a comment and *reflow* long comments into new lines, trying to
+  obey the ``ColumnLimit``.
 
   .. code-block:: c++
 
@@ -4610,9 +4612,11 @@
 ///  - Foo/// - Foo
 ///- Bar  ///   - Bar
 
+  This option has only effect if ``ReflowComments`` is set to ``true``.
+
   Nested configuration flags:
 
-  Control of spaces within a single line comment
+  Control of spaces within a single line comment.
 
   * ``unsigned Minimum`` The minimum number of spaces at the start of the 
comment.
 


Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -3070,7 +3070,9 @@
   ReferenceAlignmentStyle ReferenceAlignment;
 
   // clang-format off
-  /// If ``true``, clang-format will attempt to re-flow comments.
+  /// If ``true``, clang-format will attempt to re-flow comments. That is it
+  /// will touch a comment and *reflow* long comments into new lines, trying to
+  /// obey the ``ColumnLimit``.
   /// \code
   ///false:
   ///// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
@@ -3821,7 +3823,7 @@
   /// \version 3.7
   bool SpacesInCStyleCastParentheses;
 
-  /// Control of spaces within a single line comment
+  /// Control of spaces within a single line comment.
   struct SpacesInLineComment {
 /// The minimum number of spaces at the start of the comment.
 unsigned Minimum;
@@ -3858,6 +3860,8 @@
   ///   ///  - Foo/// - Foo
   ///   ///- Bar  ///   - Bar
   /// \endcode
+  ///
+  /// This option has only effect if ``ReflowComments`` is set to ``true``.
   /// \version 13
   SpacesInLineComment SpacesInLineCommentPrefix;
 
Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -3795,7 +3795,9 @@
 
 
 **ReflowComments** (``Boolean``) :versionbadge:`clang-format 3.8`
-  If ``true``, clang-format will attempt to re-flow comments.
+  If ``true``, clang-format will attempt to re-flow comments. That is it
+  will touch a comment and *reflow* long comments into new lines, trying to
+  obey the ``ColumnLimit``.
 
   .. code-block:: c++
 
@@ -4610,9 +4612,11 @@
 ///  - Foo/// - Foo
 ///- Bar  ///   - Bar
 
+  This option has only effect if ``ReflowComments`` is set to ``true``.
+
   Nested configuration flags:
 
-  Control of spaces within a single line comment
+  Control of spaces within a single line c

[clang] cb01bef - [clang-format][NFC] Improve documentation of FixNamespaceComments

2022-11-15 Thread Björn Schäpers via cfe-commits

Author: Björn Schäpers
Date: 2022-11-16T07:02:10+01:00
New Revision: cb01befda5479b0368d40582f046eec44fda3cec

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

LOG: [clang-format][NFC] Improve documentation of FixNamespaceComments

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

Added: 


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

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 4d4f08690ecbf..76ae54b6ef6da 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -2696,16 +2696,19 @@ the configuration (without a prefix: ``Auto``).
 
 **FixNamespaceComments** (``Boolean``) :versionbadge:`clang-format 5`
   If ``true``, clang-format adds missing namespace end comments for
-  short namespaces and fixes invalid existing ones. Short ones are
-  controlled by "ShortNamespaceLines".
+  namespaces and fixes invalid existing ones. This doesn't affect short
+  namespaces, which are controlled by ``ShortNamespaceLines``.
 
   .. code-block:: c++
 
  true:  false:
- namespace a {  vs. namespace a {
- foo(); foo();
- bar(); bar();
+ namespace longNamespace {  vs. namespace longNamespace {
+ void foo();void foo();
+ void bar();void bar();
  } // namespace a   }
+ namespace shortNamespace { namespace shortNamespace {
+ void baz();void baz();
+ }  }
 
 **ForEachMacros** (``List of Strings``) :versionbadge:`clang-format 3.7`
   A vector of macros that should be interpreted as foreach loops

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index ba56ef732dab0..93b84e1bfddfb 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -2121,14 +2121,17 @@ struct FormatStyle {
   bool ExperimentalAutoDetectBinPacking;
 
   /// If ``true``, clang-format adds missing namespace end comments for
-  /// short namespaces and fixes invalid existing ones. Short ones are
-  /// controlled by "ShortNamespaceLines".
+  /// namespaces and fixes invalid existing ones. This doesn't affect short
+  /// namespaces, which are controlled by ``ShortNamespaceLines``.
   /// \code
   ///true:  false:
-  ///namespace a {  vs. namespace a {
-  ///foo(); foo();
-  ///bar(); bar();
+  ///namespace longNamespace {  vs. namespace longNamespace {
+  ///void foo();void foo();
+  ///void bar();void bar();
   ///} // namespace a   }
+  ///namespace shortNamespace { namespace shortNamespace {
+  ///void baz();void baz();
+  ///}  }
   /// \endcode
   /// \version 5
   bool FixNamespaceComments;



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


[clang] 40c1476 - [clang-format][NFC] Improve documentation on ReflowComments

2022-11-15 Thread Björn Schäpers via cfe-commits

Author: Björn Schäpers
Date: 2022-11-16T07:02:10+01:00
New Revision: 40c1476e3ae24766426802a61b15f374285c443b

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

LOG: [clang-format][NFC] Improve documentation on ReflowComments

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

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

Added: 


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

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index a905117341776..4d4f08690ecbf 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -3795,7 +3795,9 @@ the configuration (without a prefix: ``Auto``).
 
 
 **ReflowComments** (``Boolean``) :versionbadge:`clang-format 3.8`
-  If ``true``, clang-format will attempt to re-flow comments.
+  If ``true``, clang-format will attempt to re-flow comments. That is it
+  will touch a comment and *reflow* long comments into new lines, trying to
+  obey the ``ColumnLimit``.
 
   .. code-block:: c++
 
@@ -4610,9 +4612,11 @@ the configuration (without a prefix: ``Auto``).
 ///  - Foo/// - Foo
 ///- Bar  ///   - Bar
 
+  This option has only effect if ``ReflowComments`` is set to ``true``.
+
   Nested configuration flags:
 
-  Control of spaces within a single line comment
+  Control of spaces within a single line comment.
 
   * ``unsigned Minimum`` The minimum number of spaces at the start of the 
comment.
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 276725406f295..ba56ef732dab0 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -3070,7 +3070,9 @@ struct FormatStyle {
   ReferenceAlignmentStyle ReferenceAlignment;
 
   // clang-format off
-  /// If ``true``, clang-format will attempt to re-flow comments.
+  /// If ``true``, clang-format will attempt to re-flow comments. That is it
+  /// will touch a comment and *reflow* long comments into new lines, trying to
+  /// obey the ``ColumnLimit``.
   /// \code
   ///false:
   ///// veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with 
plenty of information
@@ -3821,7 +3823,7 @@ struct FormatStyle {
   /// \version 3.7
   bool SpacesInCStyleCastParentheses;
 
-  /// Control of spaces within a single line comment
+  /// Control of spaces within a single line comment.
   struct SpacesInLineComment {
 /// The minimum number of spaces at the start of the comment.
 unsigned Minimum;
@@ -3858,6 +3860,8 @@ struct FormatStyle {
   ///   ///  - Foo/// - Foo
   ///   ///- Bar  ///   - Bar
   /// \endcode
+  ///
+  /// This option has only effect if ``ReflowComments`` is set to ``true``.
   /// \version 13
   SpacesInLineComment SpacesInLineCommentPrefix;
 



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


[PATCH] D138078: [CodeGenPrepare] split critical indirect edges from callbr w/ outputs

2022-11-15 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

You can't put transforms that are necessary for correctness in CodeGenPrepare; 
it isn't enabled at -O0.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138078

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


[PATCH] D138088: [clang][docs] Use `option` directive in User's Manual

2022-11-15 Thread KAWASHIMA Takahiro via Phabricator via cfe-commits
kawashima-fj created this revision.
kawashima-fj added a project: clang.
Herald added a project: All.
kawashima-fj requested review of this revision.
Herald added a subscriber: cfe-commits.

Sphinx has the `option` directive. Most option descriptions in 
`clang/docs/UsersManual.rst` used it but some didn't. This commit changes the 
remaining option descriptions to use the `option` directive. This makes a 
consistent view in HTML.

The `option` directive automatically creates a cross-reference target. So 
labeling by `.. _opt_XXX:` is almost unnecessary. However, options with and 
without `no-` (e.g. `-fno-show-column`/`-fshow-column`) cannot be distinguish 
for the cross-reference. So some required `.. _opt_XXX:` directives are kept 
unremoved.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138088

Files:
  clang/docs/OpenCLSupport.rst
  clang/docs/UsersManual.rst

Index: clang/docs/UsersManual.rst
===
--- clang/docs/UsersManual.rst
+++ clang/docs/UsersManual.rst
@@ -165,7 +165,8 @@
 
 .. _opt_fshow-column:
 
-**-f[no-]show-column**
+.. option:: -f[no-]show-column
+
Print column number in diagnostic.
 
This option, which defaults to on, controls whether or not Clang
@@ -187,7 +188,8 @@
 
 .. _opt_fshow-source-location:
 
-**-f[no-]show-source-location**
+.. option:: -f[no-]show-source-location
+
Print source file/line/column information in diagnostic.
 
This option, which defaults to on, controls whether or not Clang
@@ -206,7 +208,8 @@
 
 .. _opt_fcaret-diagnostics:
 
-**-f[no-]caret-diagnostics**
+.. option:: -f[no-]caret-diagnostics
+
Print source line and ranges from source code in diagnostic.
This option, which defaults to on, controls whether or not Clang
prints the source line, source ranges, and caret when emitting a
@@ -220,7 +223,8 @@
 ^
 //
 
-**-f[no-]color-diagnostics**
+.. option:: -f[no-]color-diagnostics
+
This option, which defaults to on when a color-capable terminal is
detected, controls whether or not Clang prints diagnostics in color.
 
@@ -247,7 +251,8 @@
 ^
 //
 
-**-fansi-escape-codes**
+.. option:: -fansi-escape-codes
+
Controls whether ANSI escape codes are used instead of the Windows Console
API to output colored diagnostics. This option is only used on Windows and
defaults to off.
@@ -277,7 +282,8 @@
 
 .. _opt_fdiagnostics-show-option:
 
-**-f[no-]diagnostics-show-option**
+.. option:: -f[no-]diagnostics-show-option
+
Enable ``[-Woption]`` information in diagnostic line.
 
This option, which defaults to on, controls whether or not Clang
@@ -293,13 +299,11 @@
 //
 
Passing **-fno-diagnostics-show-option** will prevent Clang from
-   printing the [:ref:`-Wextra-tokens `] information in
+   printing the [:option:`-Wextra-tokens`] information in
the diagnostic. This information tells you the flag needed to enable
or disable the diagnostic, either from the command line or through
:ref:`#pragma GCC diagnostic `.
 
-.. _opt_fdiagnostics-show-category:
-
 .. option:: -fdiagnostics-show-category=none/id/name
 
Enable printing category information in diagnostic line.
@@ -347,7 +351,7 @@
   ``-fsave-optimization-record=bitstream``: A binary format based on LLVM
   Bitstream.
 
-   The output file is controlled by :ref:`-foptimization-record-file `.
+   The output file is controlled by :option:`-foptimization-record-file`.
 
In the absence of an explicit output file, the file is chosen using the
following scheme:
@@ -395,20 +399,18 @@
``-.opt.``
 
Note that this is incompatible with passing the
-   :ref:`-foptimization-record-file ` option.
+   :option:`-foptimization-record-file` option.
 
-.. _opt_foptimization-record-file:
+.. option:: -foptimization-record-file
 
-**-foptimization-record-file**
Control the file to which optimization reports are written. This implies
:ref:`-fsave-optimization-record `.
 
 On Darwin platforms, this is incompatible with passing multiple
 ``-arch `` options.
 
-.. _opt_foptimization-record-passes:
+.. option:: -foptimization-record-passes
 
-**-foptimization-record-passes**
Only include passes which match a specified regular expression.
 
When optimization reports are being output (see
@@ -420,7 +422,8 @@
 
 .. _opt_fdiagnostics-show-hotness:
 
-**-f[no-]diagnostics-show-hotness**
+.. option:: -f[no-]diagnostics-show-hotness
+
Enable profile hotness information in diagnostic line.
 
This option controls whether Clang prints the profile hotness associated
@@ -443,9 +446,8 @@
:ref:`-fsave-optimization-record ` is used.
Otherwise, it defaults to off.
 
-.. _opt_fdiagnostics-hotness-threshold:
+.. option:: -fdiagnostics-hotness-threshold
 
-**-fdiagnostics-hotness-threshold**
Prevent optimization remarks from being output if they do not have at least
thi

[PATCH] D136354: [Driver] Enable nested configuration files

2022-11-15 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff added a comment.

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136354

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


[PATCH] D137217: [LTO][COFF] Use bitcode file names in lto native object file names.

2022-11-15 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: lld/COFF/LTO.cpp:229
+StringRef ltoObjName;
+if (bitcodeFilePath == "ld-temp.o") {
+  ltoObjName =

MaskRay wrote:
> tejohnson wrote:
> > zequanwu wrote:
> > > tejohnson wrote:
> > > > This case should always be i==0 I think?
> > > IIUC, "ld-temp.o" is the name of combined module. Do you mean there will 
> > > be only 1 combined module and it will always be the first task?
> > Yes. So you don't need the handling for i==0 in the name in this case (you 
> > could probably assert that i==0).
> This looks like a hack. `assert(i == 0)` will fail with 
> `-opt:lldltopartitions=2`: `buf[1]` will be called `ld-temp.o` as well.
> 
> In addition, if an input bitcode file is called `ld-temp.o` (for some reason 
> they don't use `.obj`, just `ld-temp.o`), `assert(i == 0)` will fail as well.
I guess `if (i < config->ltoPartitions)` may fix the issue.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137217

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


[PATCH] D137217: [LTO][COFF] Use bitcode file names in lto native object file names.

2022-11-15 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In D137217#3926601 , @tejohnson wrote:

> @MaskRay wondering if this is a good change to make for ELF as well, wdyt?

Yes, I think this is a good idea and improves debuggability. The change is 
non-trivial so so this patch focusing on the COFF part is good.




Comment at: lld/COFF/LTO.cpp:238
+  sys::path::append(path, directory,
+outputFileBaseName + ".lto." + baseName);
+  sys::path::remove_dots(path, true);

What if two input bitcode files have the same basename, e.g. `dir1/a.obj` and 
`dir2/a.obj`?



Comment at: lld/COFF/LTO.cpp:229
+StringRef ltoObjName;
+if (bitcodeFilePath == "ld-temp.o") {
+  ltoObjName =

tejohnson wrote:
> zequanwu wrote:
> > tejohnson wrote:
> > > This case should always be i==0 I think?
> > IIUC, "ld-temp.o" is the name of combined module. Do you mean there will be 
> > only 1 combined module and it will always be the first task?
> Yes. So you don't need the handling for i==0 in the name in this case (you 
> could probably assert that i==0).
This looks like a hack. `assert(i == 0)` will fail with 
`-opt:lldltopartitions=2`: `buf[1]` will be called `ld-temp.o` as well.

In addition, if an input bitcode file is called `ld-temp.o` (for some reason 
they don't use `.obj`, just `ld-temp.o`), `assert(i == 0)` will fail as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137217

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


[PATCH] D135488: [codegen] Display stack layouts in console

2022-11-15 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added a comment.

The kernel resource remarks added in 67357739c6d36a61972c1fc0e829e35cb5375279 
 are 
probably the current heaviest remarks. I believe there were some changes to 
newline handling for it


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135488

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


[PATCH] D137059: [Driver] [Modules] Introduce -fsave-std-c++-module-file= to specify the path of the module file (2/2)

2022-11-15 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu updated this revision to Diff 475664.
ChuanqiXu added a comment.

Use tests with `-###`


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

https://reviews.llvm.org/D137059

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/save-std-c++-module-file.cpp


Index: clang/test/Driver/save-std-c++-module-file.cpp
===
--- clang/test/Driver/save-std-c++-module-file.cpp
+++ clang/test/Driver/save-std-c++-module-file.cpp
@@ -7,9 +7,16 @@
 //
 // RUN: %clang -std=c++20 %t/Hello.cppm -fsave-std-c++-module-file -o 
%t/output/Hello.o \
 // RUN:   -### 2>&1 | FileCheck %t/Hello.cppm -DPREFIX=%t 
--check-prefix=CHECK-WITH-OUTPUT
+//
+// RUN: %clang -std=c++20 %t/Hello.cppm 
-fsave-std-c++-module-file=%t/tmp/H.pcm \
+// RUN:   -### 2>&1 | FileCheck %t/Hello.cppm -DPREFIX=%t 
--check-prefix=CHECK-SPECIFIED
+//
+// RUN: %clang -std=c++20 %t/Hello.cppm 
-fsave-std-c++-module-file=%t/tmp/H.pcm -o %t/Hello.o \
+// RUN:   -### 2>&1 | FileCheck %t/Hello.cppm -DPREFIX=%t 
--check-prefix=CHECK-SPECIFIED
 
 //--- Hello.cppm
 export module Hello;
 
 // CHECK: "-o" "[[PREFIX]]/Hello.pcm"
 // CHECK-WITH-OUTPUT: "-o" "[[PREFIX]]/output/Hello.pcm"
+// CHECK-SPECIFIED: "-o" "[[PREFIX]]/tmp/H.pcm"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -5553,15 +5553,21 @@
   }
 
   // If `-fsave-std-c++-module-file` is specfied, then:
-  // - If `-o` is specified, the module file is writing to the same path
+  // - If `-fsave-std-c++-module-file` has a value, the module file is
+  //   writing to the value.
+  // - Else if `-o` is specified, the module file is writing to the same path
   //   with the output file in module file's suffix. 
-  // - If `-o` is not specified, the module file is writing to the same path
+  // - Else, the module file is writing to the same path
   //   with the input file in module file's suffix.
   if (!AtTopLevel && isa(JA) &&
   JA.getType() == types::TY_ModuleFile &&
-  C.getArgs().hasArg(options::OPT_fsave_std_cxx_module_file)) {
+  (C.getArgs().hasArg(options::OPT_fsave_std_cxx_module_file) ||
+   C.getArgs().hasArg(options::OPT_fsave_std_cxx_module_file_EQ))) {
 SmallString<128> TempPath;
-if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
+
+if (Arg *ModuleFilePath = 
C.getArgs().getLastArg(options::OPT_fsave_std_cxx_module_file_EQ))
+  TempPath = ModuleFilePath->getValue();
+else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
   TempPath = FinalOutput->getValue();
 else
   TempPath = BaseInput;
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2285,6 +2285,8 @@
   PosFlag,
   NegFlag, BothFlags<[NoXarchOption, CC1Option]>>;
 
+def fsave_std_cxx_module_file_EQ : Joined<["-"], 
"fsave-std-c++-module-file=">, Flags<[NoXarchOption, CC1Option]>,
+  HelpText<"Save intermediate module file results when compiling a standard 
C++ module unit.">;
 def fsave_std_cxx_module_file : Flag<["-"], "fsave-std-c++-module-file">, 
Flags<[NoXarchOption, CC1Option]>,
   HelpText<"Save intermediate module file results when compiling a standard 
C++ module unit.">;
 


Index: clang/test/Driver/save-std-c++-module-file.cpp
===
--- clang/test/Driver/save-std-c++-module-file.cpp
+++ clang/test/Driver/save-std-c++-module-file.cpp
@@ -7,9 +7,16 @@
 //
 // RUN: %clang -std=c++20 %t/Hello.cppm -fsave-std-c++-module-file -o %t/output/Hello.o \
 // RUN:   -### 2>&1 | FileCheck %t/Hello.cppm -DPREFIX=%t --check-prefix=CHECK-WITH-OUTPUT
+//
+// RUN: %clang -std=c++20 %t/Hello.cppm -fsave-std-c++-module-file=%t/tmp/H.pcm \
+// RUN:   -### 2>&1 | FileCheck %t/Hello.cppm -DPREFIX=%t --check-prefix=CHECK-SPECIFIED
+//
+// RUN: %clang -std=c++20 %t/Hello.cppm -fsave-std-c++-module-file=%t/tmp/H.pcm -o %t/Hello.o \
+// RUN:   -### 2>&1 | FileCheck %t/Hello.cppm -DPREFIX=%t --check-prefix=CHECK-SPECIFIED
 
 //--- Hello.cppm
 export module Hello;
 
 // CHECK: "-o" "[[PREFIX]]/Hello.pcm"
 // CHECK-WITH-OUTPUT: "-o" "[[PREFIX]]/output/Hello.pcm"
+// CHECK-SPECIFIED: "-o" "[[PREFIX]]/tmp/H.pcm"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -5553,15 +5553,21 @@
   }
 
   // If `-fsave-std-c++-module-file` is specfied, then:
-  // - If `-o` is specified, the module file is writing to the same path
+  // - If `-fsave-std-c++-module-file` has a value, the module file is
+  //   writing to the value.
+  // - Else if `-o` is specified, the module file is writing to the same path
   //   with the out

[PATCH] D137058: [Driver] [Modules] Support -fsave-std-c++-module-file (1/2)

2022-11-15 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu marked 2 inline comments as done.
ChuanqiXu added inline comments.



Comment at: clang/lib/Driver/Driver.cpp:5541-5542
+  //
+  // FIXME: Do we need to handle the case that the calculated output is
+  // conflicting with the specified output file or the input file?
+  if (!AtTopLevel && isa(JA) &&

dblaikie wrote:
> Do we do that for `-o` today? (eg: if you try to `-o` and specify the input 
> file name, such that the output would overwrite the input, what happens? I'm 
> not sure - but I guess it's OK to do whatever that is for this case too)
> Do we do that for -o today? (eg: if you try to -o and specify the input file 
> name, such that the output would overwrite the input, what happens? I'm not 
> sure - but I guess it's OK to do whatever that is for this case too)

In this case, the input file will be overwrite and no warning shows. So it 
looks like we didn't take special treatment here. So I remove the FIXME.



Comment at: clang/test/Driver/save-std-c++-module-file.cpp:1-11
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: split-file %s %t
+//
+// RUN: %clang -std=c++20 %t/Hello.cppm -fsave-std-c++-module-file -c
+// RUN: ls %t | FileCheck %t/Hello.cppm --check-prefix=CHECK-DEFAULT
+//

dblaikie wrote:
> Usually driver tests only invoke the driver and observe the output using 
> `-###` to see what subcommands the driver would run. Could this test be 
> phrased in that way? (testing whatever command line is expected to be 
> invoked, rather than the actual behavior of the frontend)
Good point! Done.


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

https://reviews.llvm.org/D137058

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


[PATCH] D137058: [Driver] [Modules] Support -fsave-std-c++-module-file (1/2)

2022-11-15 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu updated this revision to Diff 475663.
ChuanqiXu added a comment.

Address comments.


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

https://reviews.llvm.org/D137058

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/save-std-c++-module-file.cpp


Index: clang/test/Driver/save-std-c++-module-file.cpp
===
--- /dev/null
+++ clang/test/Driver/save-std-c++-module-file.cpp
@@ -0,0 +1,15 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: split-file %s %t
+//
+// RUN: %clang -std=c++20 %t/Hello.cppm -fsave-std-c++-module-file -### 2>&1 | 
\
+// RUN:   FileCheck %t/Hello.cppm -DPREFIX=%t
+//
+// RUN: %clang -std=c++20 %t/Hello.cppm -fsave-std-c++-module-file -o 
%t/output/Hello.o \
+// RUN:   -### 2>&1 | FileCheck %t/Hello.cppm -DPREFIX=%t 
--check-prefix=CHECK-WITH-OUTPUT
+
+//--- Hello.cppm
+export module Hello;
+
+// CHECK: "-o" "[[PREFIX]]/Hello.pcm"
+// CHECK-WITH-OUTPUT: "-o" "[[PREFIX]]/output/Hello.pcm"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -5552,6 +5552,25 @@
 return "-";
   }
 
+  // If `-fsave-std-c++-module-file` is specfied, then:
+  // - If `-o` is specified, the module file is writing to the same path
+  //   with the output file in module file's suffix. 
+  // - If `-o` is not specified, the module file is writing to the same path
+  //   with the input file in module file's suffix.
+  if (!AtTopLevel && isa(JA) &&
+  JA.getType() == types::TY_ModuleFile &&
+  C.getArgs().hasArg(options::OPT_fsave_std_cxx_module_file)) {
+SmallString<128> TempPath;
+if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
+  TempPath = FinalOutput->getValue();
+else
+  TempPath = BaseInput;
+
+const char *Extension = types::getTypeTempSuffix(JA.getType());
+llvm::sys::path::replace_extension(TempPath, Extension);
+return C.addResultFile(C.getArgs().MakeArgString(TempPath.c_str()), &JA);
+  }
+
   if (IsDXCMode() && !C.getArgs().hasArg(options::OPT_o))
 return "-";
 
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2285,6 +2285,9 @@
   PosFlag,
   NegFlag, BothFlags<[NoXarchOption, CC1Option]>>;
 
+def fsave_std_cxx_module_file : Flag<["-"], "fsave-std-c++-module-file">, 
Flags<[NoXarchOption, CC1Option]>,
+  HelpText<"Save intermediate module file results when compiling a standard 
C++ module unit.">;
+
 def fmodules_prune_interval : Joined<["-"], "fmodules-prune-interval=">, 
Group,
   Flags<[CC1Option]>, MetaVarName<"">,
   HelpText<"Specify the interval (in seconds) between attempts to prune the 
module cache">,


Index: clang/test/Driver/save-std-c++-module-file.cpp
===
--- /dev/null
+++ clang/test/Driver/save-std-c++-module-file.cpp
@@ -0,0 +1,15 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: split-file %s %t
+//
+// RUN: %clang -std=c++20 %t/Hello.cppm -fsave-std-c++-module-file -### 2>&1 | \
+// RUN:   FileCheck %t/Hello.cppm -DPREFIX=%t
+//
+// RUN: %clang -std=c++20 %t/Hello.cppm -fsave-std-c++-module-file -o %t/output/Hello.o \
+// RUN:   -### 2>&1 | FileCheck %t/Hello.cppm -DPREFIX=%t --check-prefix=CHECK-WITH-OUTPUT
+
+//--- Hello.cppm
+export module Hello;
+
+// CHECK: "-o" "[[PREFIX]]/Hello.pcm"
+// CHECK-WITH-OUTPUT: "-o" "[[PREFIX]]/output/Hello.pcm"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -5552,6 +5552,25 @@
 return "-";
   }
 
+  // If `-fsave-std-c++-module-file` is specfied, then:
+  // - If `-o` is specified, the module file is writing to the same path
+  //   with the output file in module file's suffix. 
+  // - If `-o` is not specified, the module file is writing to the same path
+  //   with the input file in module file's suffix.
+  if (!AtTopLevel && isa(JA) &&
+  JA.getType() == types::TY_ModuleFile &&
+  C.getArgs().hasArg(options::OPT_fsave_std_cxx_module_file)) {
+SmallString<128> TempPath;
+if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
+  TempPath = FinalOutput->getValue();
+else
+  TempPath = BaseInput;
+
+const char *Extension = types::getTypeTempSuffix(JA.getType());
+llvm::sys::path::replace_extension(TempPath, Extension);
+return C.addResultFile(C.getArgs().MakeArgString(TempPath.c_str()), &JA);
+  }
+
   if (IsDXCMode() && !C.getArgs().hasArg(options::OPT_o))
 return "-";
 
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driv

[PATCH] D135488: [codegen] Display stack layouts in console

2022-11-15 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth added a comment.

As a quick test, I hacked the printer pass to generate an output string, and 
passed that into the remarks emitter. From opt or llc things look as expected. 
There's some additional output, but its limited.

I see a more serious issue when using it from Clang, as the output is truncated 
, as in it only printed up to the first stack slot in my test. Its also all 
bold, which isn't great. I have a feeling that my shortcut is the root cause of 
the truncation, but I haven't tracked down the issue exactly.

Do any other remarks output complex data like this? From what I can see they 
tend to be fairly short…

I also thought about printing each line as a remark, but that seems to get 
noisy pretty fast, since each line would have the `remark ` tag 
plus an `[-Rpass-analysis=stackframe-printer]` at the end.

Example truncated output (each function should have several lines w/ offset 
from SP, alignment, and size):

  $ clang -O1 -Rpass-analysis=stackframe-printer 
llvm/test/CodeGen/X86/stack-frame-printer.ll -c -o /dev/null -mllvm 
-print-stack-frame
  
  remark: :0:0: 
  # Stack Layout: stackSizeWarning
   [-Rpass-analysis=stackframe-printer]
  remark: :0:0: 
  # Stack Layout: cleanup_array
  OffsetAlign Size  
  [SP-8]  Spill 168 
  
   [-Rpass-analysis=stackframe-printer]
  remark: :0:0: 
  # Stack Layout: cleanup_result
  OffsetAlign Size  
  [SP-8]  Spill 168 
  
   [-Rpass-analysis=stackframe-printer]
  remark: :0:0: 
  # Stack Layout: do_work
  OffsetAlign Size  
  [SP-8]  Spill 168 
  
   [-Rpass-analysis=stackframe-printer]
  remark: :0:0: 
  # Stack Layout: gen_array
  OffsetAlign Size  
  [SP-8]  Spill 168 
  
   [-Rpass-analysis=stackframe-printer]
  remark: :0:0: 
  # Stack Layout: caller
  OffsetAlign Size  
  [SP-8]  Spill 168 
  
   [-Rpass-analysis=stackframe-printer]

Output from llc (which looks more or less as expected):

  $ llc -mcpu=corei7 -O1 -print-stack-frame 
-pass-remarks-analysis=stackframe-printer < 
llvm/test/CodeGen/X86/stack-frame-printer.ll 2>&1 >/dev/null
  
  remark: :0:0: 
  # Stack Layout: stackSizeWarning
  OffsetAlign Size  
  [SP-88]   1680
  buffer @ frame-diags.c:30
  [SP-168]  1680
  buffer2 @ frame-diags.c:33
  
  
  remark: :0:0: 
  # Stack Layout: cleanup_array
  OffsetAlign Size  
  [SP-8]  Spill 168 
  [SP-16]   8 8 
  a @ dot.c:13
  
  
  remark: :0:0: 
  # Stack Layout: cleanup_result
  OffsetAlign Size  
  [SP-8]  Spill 168 
  [SP-16]   8 8 
  res @ dot.c:21
  
  
  remark: :0:0: 
  # Stack Layout: do_work
  OffsetAlign Size  
  [SP-8]  Spill 168 
  [SP-12]   4 4 
  i @ dot.c:55
  [SP-24]   8 8 
  AB @ dot.c:38
  [SP-28]   4 4 
  len @ dot.c:37
  [SP-32]   4 4 
  [SP-40]   8 8 
  out @ dot.c:32
  [SP-48]   8 8 
  B @ dot.c:32
  [SP-56]   8 8 
  A @ dot.c:32
  [SP-60]   4 4 
  sum @ dot.c:54
  
  
  remark: :0:0: 
  # Stack Layout: gen_array
  OffsetAlign Size  
  [SP-8]  Spill 168 
  [SP-12]   4 4 
  i @ dot.c:69
  [SP-16]   4 4 
  size @ dot.c:62
  [SP-24]   8 8 
  res @ dot.c:65
  [SP-32]   8 8 
  
  
  remark: :0:0: 
  # Stack Layout: caller
  OffsetAlign Size  
  [SP-8]  Spill 168 
  [SP-12]   4 4 
  ret @ dot.c:81
  [SP-16]   4 4 
  [SP-24]   8 8 
  res @ dot.c:80
  [SP-32]   8 8 
  B @ dot.c:79
  [SP-40]   8 8 
  A @ dot.c:78
  [SP-44]   4 4 
  err @ dot.c:83
  [SP-48]   4 4 
  size @ dot.c:77

Are there any thoughts about how to make this work more nicely w/ optimization 
remarks from Clang?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135488

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


[PATCH] D137381: [clang][compiler-rt] Exception escape out of an non-unwinding function is an undefined behaviour

2022-11-15 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri marked an inline comment as done.
lebedev.ri added inline comments.



Comment at: clang/lib/CodeGen/CodeGenFunction.h:2028
+// FIXME: what about FuncletPads?
+if (llvm::BasicBlock *InvokeBB = Builder.GetInsertBlock();
+SanOpts.has(SanitizerKind::ExceptionEscape) &&

rjmccall wrote:
> The purpose of `getInvokeDestImpl` is to outline the slow path, and this 
> definitely belongs in the slow path.
The problem is that we aggressively cache all the EH stuff.
I will take a second look, maybe this can be done less intrusively.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137381

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


[PATCH] D137381: [clang][compiler-rt] Exception escape out of an non-unwinding function is an undefined behaviour

2022-11-15 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri updated this revision to Diff 475649.
lebedev.ri marked an inline comment as done.
lebedev.ri added a comment.

@rjmccall thank you for taking a look!
I do believe this now does the right thing.

I would like to keep this patch minimal.
I have not looked into `-fno-exceptions`,
and i'm not sure about funclets.
I will need to double-check tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137381

Files:
  clang/docs/ReleaseNotes.rst
  clang/docs/UndefinedBehaviorSanitizer.rst
  clang/include/clang/Basic/Sanitizers.def
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGCleanup.cpp
  clang/lib/CodeGen/CGCleanup.h
  clang/lib/CodeGen/CGException.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/CodeGen/EHScopeStack.h
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/CodeGenCXX/catch-exception-escape.cpp
  clang/test/Driver/fsanitize.c
  compiler-rt/lib/ubsan/ubsan_checks.inc
  compiler-rt/lib/ubsan/ubsan_handlers.cpp
  compiler-rt/lib/ubsan/ubsan_handlers.h
  compiler-rt/lib/ubsan_minimal/ubsan_minimal_handlers.cpp
  compiler-rt/test/ubsan/TestCases/Misc/exception-escape.cpp
  compiler-rt/test/ubsan_minimal/TestCases/exception-escape.cpp

Index: compiler-rt/test/ubsan_minimal/TestCases/exception-escape.cpp
===
--- /dev/null
+++ compiler-rt/test/ubsan_minimal/TestCases/exception-escape.cpp
@@ -0,0 +1,47 @@
+// RUN: %clangxx -fsanitize=exception-escape %s -O3 -o %t
+// RUN: %run %t 2>&1 | FileCheck %s --implicit-check-not="exception-escape" --check-prefixes=CHECK-ALL,CHECK-ONE
+// RUN: not --crash %run %t a 2>&1 | FileCheck %s --implicit-check-not="exception-escape" --check-prefixes=CHECK-ALL,CHECK-TWO
+// RUN: not --crash %run %t a b 2>&1 | FileCheck %s --implicit-check-not="exception-escape" --check-prefixes=CHECK-ALL,CHECK-THREE
+
+#include 
+#include 
+
+void thrower() { throw 0; }
+
+void nonthrower() noexcept {}
+
+// pure functions are generally side-effect free,
+// so we need to be smart to defeat optimizer
+// from completely dropping the call to the function...
+
+void *__attribute__((pure)) footgun(int x) {
+  if (x == 2)
+thrower();
+  if (x == 3)
+thrower();
+  nonthrower();
+  fprintf(stderr, "SUCCESS\n"); // Should be here, not in `main()`.
+  return malloc(1);
+}
+
+// CHECK-ALL: TEST
+
+// CHECK-ONE: SUCCESS
+// CHECK-TWO: exception-escape
+// CHECK-THREE: exception-escape
+
+int main(int argc, char **argv) {
+  bool status = 0;
+  void *mem = nullptr;
+
+  fprintf(stderr, "TEST\n");
+
+  try {
+mem = footgun(argc);
+status = mem != 0;
+  } catch (...) {
+  }
+
+  free(mem);
+  return status;
+}
Index: compiler-rt/test/ubsan/TestCases/Misc/exception-escape.cpp
===
--- /dev/null
+++ compiler-rt/test/ubsan/TestCases/Misc/exception-escape.cpp
@@ -0,0 +1,96 @@
+// RUN: %clangxx -fsanitize=exception-escape %s -O3 -o %t
+// RUN: %run %t 2>&1 | FileCheck %s --implicit-check-not="error:" --check-prefixes=CHECK-ALL,CHECK-ONE
+// RUN: not %run %t 1 2>&1 | FileCheck %s --implicit-check-not="error:" --check-prefixes=CHECK-ALL,CHECK-TWO
+// RUN: not %run %t 1 2 2>&1 | FileCheck %s --implicit-check-not="error:" --check-prefixes=CHECK-ALL,CHECK-THREE
+// RUN: not %run %t 1 2 3 2>&1 | FileCheck %s --implicit-check-not="error:" --check-prefixes=CHECK-ALL,CHECK-FOUR
+// RUN: not %run %t 1 2 3 4 2>&1 | FileCheck %s --implicit-check-not="error:" --check-prefixes=CHECK-ALL,CHECK-FIVE
+// RUN: not %run %t 1 2 3 4 5 2>&1 | FileCheck %s --implicit-check-not="error:" --check-prefixes=CHECK-ALL,CHECK-SIX
+
+#include 
+#include 
+
+void thrower() { throw 0; }
+
+void maybe_throws() {}
+
+void nonthrower() noexcept {}
+
+// pure functions are generally side-effect free,
+// so we need to be smart to defeat optimizer
+// from completely dropping the call to the function...
+
+void *__attribute__((pure)) footgun(int x) {
+  if (x == 2)
+#line 100
+thrower();
+
+  if (x == 3)
+#line 200
+thrower();
+
+  nonthrower();
+
+  if (x == 4) {
+try {
+#line 300
+  thrower();
+} catch (...) {
+#line 400
+  throw;
+}
+  }
+
+  if (x == 5) {
+try {
+#line 500
+  thrower();
+} catch (...) {
+#line 600
+  maybe_throws();
+#line 700
+  throw;
+}
+  }
+
+  if (x == 6) {
+try {
+#line 800
+  thrower();
+} catch (...) {
+#line 900
+  thrower();
+#line 1000
+  throw;
+}
+  }
+
+  fprintf(stderr, "SUCCESS\n"); // Should be here, not in `main()`.
+  return malloc(1);
+}
+
+// CHECK-ALL: TEST
+
+// CHECK-ONE: SUCCESS
+// CHECK-TWO: exception-escape.cpp:100:5: runtime error: exception escapes out of function that should not throw exception
+// CHECK-THREE: exception-escape.cpp:200:5: runtime error: exception escapes out of function that should not throw ex

[PATCH] D138058: [Sema] Use the value category of the base expression when creating an ExtVectorElementExpr

2022-11-15 Thread Akira Hatanaka via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG81e33602f78d: [Sema] Use the value category of the base 
expression when creating an (authored by ahatanak).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138058

Files:
  clang/lib/Sema/SemaExprMember.cpp
  clang/test/SemaObjC/property-not-lvalue.m


Index: clang/test/SemaObjC/property-not-lvalue.m
===
--- clang/test/SemaObjC/property-not-lvalue.m
+++ clang/test/SemaObjC/property-not-lvalue.m
@@ -7,10 +7,13 @@
} inner;
 } NSSize;
 
+typedef __attribute__((__ext_vector_type__(2))) float simd_float2;
+
 @interface Foo  {
 NSSize _size;
 }
 @property NSSize size;
+@property simd_float2 f2;
 @end
 
 void foo(void) { 
@@ -32,3 +35,8 @@
 }
 - (NSSize)size {}
 @end
+
+// clang used to crash compiling this code.
+void test(Foo *f) {
+  simd_float2 *v = &f.f2.xy; // expected-error {{cannot take the address of an 
rvalue}}
+}
Index: clang/lib/Sema/SemaExprMember.cpp
===
--- clang/lib/Sema/SemaExprMember.cpp
+++ clang/lib/Sema/SemaExprMember.cpp
@@ -1621,16 +1621,7 @@
   if (BaseType->isExtVectorType()) {
 // FIXME: this expr should store IsArrow.
 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
-ExprValueKind VK;
-if (IsArrow)
-  VK = VK_LValue;
-else {
-  if (PseudoObjectExpr *POE = dyn_cast(BaseExpr.get()))
-VK = POE->getSyntacticForm()->getValueKind();
-  else
-VK = BaseExpr.get()->getValueKind();
-}
-
+ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
Member, MemberLoc);
 if (ret.isNull())


Index: clang/test/SemaObjC/property-not-lvalue.m
===
--- clang/test/SemaObjC/property-not-lvalue.m
+++ clang/test/SemaObjC/property-not-lvalue.m
@@ -7,10 +7,13 @@
 		} inner;
 } NSSize;
 
+typedef __attribute__((__ext_vector_type__(2))) float simd_float2;
+
 @interface Foo  {
 NSSize _size;
 }
 @property NSSize size;
+@property simd_float2 f2;
 @end
 
 void foo(void) { 
@@ -32,3 +35,8 @@
 }
 - (NSSize)size {}
 @end
+
+// clang used to crash compiling this code.
+void test(Foo *f) {
+  simd_float2 *v = &f.f2.xy; // expected-error {{cannot take the address of an rvalue}}
+}
Index: clang/lib/Sema/SemaExprMember.cpp
===
--- clang/lib/Sema/SemaExprMember.cpp
+++ clang/lib/Sema/SemaExprMember.cpp
@@ -1621,16 +1621,7 @@
   if (BaseType->isExtVectorType()) {
 // FIXME: this expr should store IsArrow.
 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
-ExprValueKind VK;
-if (IsArrow)
-  VK = VK_LValue;
-else {
-  if (PseudoObjectExpr *POE = dyn_cast(BaseExpr.get()))
-VK = POE->getSyntacticForm()->getValueKind();
-  else
-VK = BaseExpr.get()->getValueKind();
-}
-
+ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
Member, MemberLoc);
 if (ret.isNull())
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D138081: [IR] Split out IR printing passes into IRPrinter

2022-11-15 Thread Alexander Shaposhnikov via Phabricator via cfe-commits
alexander-shaposhnikov created this revision.
alexander-shaposhnikov added reviewers: nikic, aeubanks, tejohnson.
alexander-shaposhnikov created this object with visibility "All Users".
Herald added subscribers: Moerafaat, zero9178, bzcheeseman, sdasgup3, 
wenzhicui, wrengr, ormris, cota, teijeong, rdzhabarov, tatianashp, msifontes, 
jurahul, Kayjukh, grosul1, Joonsoo, liufengdb, aartbik, mgester, arpith-jacob, 
antiagainst, shauheen, rriddle, mehdi_amini, hiraditya.
Herald added a project: All.
alexander-shaposhnikov requested review of this revision.
Herald added subscribers: cfe-commits, stephenneuendorffer, nicolasvasilache.
Herald added projects: clang, LLVM.

This diff splits out (from LLVMCore) IR printing passes into IRPrinter.
This structure is similar to what we already have for IRReader and enables us 
to avoid circular dependencies between LLVMCore and Analysis.
The legacy interface is left unchanged, once the legacy pass manager is removed 
(in the future) we will be able to clean it up further.
The bazel build configuration has been updated as well.

Test plan:
1/ Tested the following cmake configurations: static/dynamic linking * lld/gold 
* clang/gcc
2/ bazel build --config=generic_clang @llvm-project//...


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138081

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/CodeGen/CMakeLists.txt
  llvm/include/llvm/CodeGen/CodeGenPassBuilder.h
  llvm/include/llvm/IR/IRPrintingPasses.h
  llvm/include/llvm/IRPrinter/IRPrintingPasses.h
  llvm/lib/CMakeLists.txt
  llvm/lib/IR/IRPrintingPasses.cpp
  llvm/lib/IRPrinter/CMakeLists.txt
  llvm/lib/IRPrinter/IRPrintingPasses.cpp
  llvm/lib/Passes/CMakeLists.txt
  llvm/lib/Passes/PassBuilder.cpp
  llvm/lib/Target/DirectX/DirectXTargetMachine.cpp
  llvm/tools/llc/llc.cpp
  llvm/tools/opt/CMakeLists.txt
  llvm/tools/opt/NewPMDriver.cpp
  utils/bazel/llvm-project-overlay/clang/BUILD.bazel
  utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
  utils/bazel/llvm-project-overlay/mlir/BUILD.bazel

Index: utils/bazel/llvm-project-overlay/mlir/BUILD.bazel
===
--- utils/bazel/llvm-project-overlay/mlir/BUILD.bazel
+++ utils/bazel/llvm-project-overlay/mlir/BUILD.bazel
@@ -6521,6 +6521,7 @@
 ":Support",
 ":TranslateLib",
 "//llvm:Core",
+"//llvm:IRPrinter",
 "//llvm:IRReader",
 "//llvm:Support",
 ],
Index: utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
===
--- utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
+++ utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
@@ -915,6 +915,7 @@
 ":BinaryFormat",
 ":BitReader",
 ":Core",
+":IRPrinter",
 ":IRReader",
 ":MC",
 ":MCParser",
@@ -1375,6 +1376,22 @@
 ],
 )
 
+cc_library(
+name = "IRPrinter",
+srcs = glob([
+"lib/IRPrinter/*.cpp",
+"lib/IRPrinter/*.h",
+]),
+hdrs = glob([
+"include/llvm/IRPrinter/*.h",
+]),
+copts = llvm_copts,
+deps = [
+":Core",
+":Support",
+],
+)
+
 cc_library(
 name = "IRReader",
 srcs = glob([
@@ -1438,6 +1455,7 @@
 ":BitWriter",
 ":Core",
 ":FrontendOpenMP",
+":IRPrinter",
 ":IRReader",
 ":InstCombine",
 ":Instrumentation",
@@ -2260,6 +2278,7 @@
 ":BitWriter",
 ":CodeGen",
 ":Core",
+":IRPrinter",
 ":IRReader",
 ":Linker",
 ":MC",
@@ -2746,6 +2765,7 @@
 ":BitReader",
 ":CodeGen",
 ":Core",
+":IRPrinter",
 ":IRReader",
 ":MC",
 ":Support",
@@ -2788,6 +2808,7 @@
 ":CodeGen",
 ":Core",
 ":ExecutionEngine",
+":IRPrinter",
 ":IRReader",
 ":Instrumentation",
 ":Interpreter",
@@ -2886,6 +2907,7 @@
 ":BitReader",
 ":BitWriter",
 ":Core",
+":IRPrinter",
 ":IRReader",
 ":Support",
 ],
@@ -3178,6 +3200,7 @@
 ":BitWriter",
 ":Core",
 ":IPO",
+":IRPrinter",
 ":IRReader",
 ":Support",
 ],
@@ -3311,6 +3334,7 @@
 ":BitWriter",
 ":Core",
 ":IPO",
+":IRPrinter",
 ":IRReader",
 ":Linker",
 ":Object",
@@ -3371,6 +3395,7 @@
 ":BitWriter",
 ":CodeGen",
 ":Core",
+":IRPrinter",
 ":IRReader",
 ":LTO",
 ":Support",
@@ -3482,6 +3507,7 @@
 deps = [
 ":BitReader",
 ":BitWriter",
+":IRPrinter",
 ":IRReader",
 ":Support",
 ],
@@ -4037,6 +4063,7 @@
 deps = [
 ":BitWriter",
 ":Core",
+":IRPrinter",
 ":IRReader",
 ":Support",
 ":TransformUtils",
@@ -4162,6 +4189,7 @@
 ":BitWriter",
 ":CodeGen",
 ":

[clang] 81e3360 - [Sema] Use the value category of the base expression when creating an

2022-11-15 Thread Akira Hatanaka via cfe-commits

Author: Akira Hatanaka
Date: 2022-11-15T17:14:48-08:00
New Revision: 81e33602f78d135c11b0d74d738263fc6cfaae12

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

LOG: [Sema] Use the value category of the base expression when creating an
ExtVectorElementExpr

This fixes a bug where an lvalue ExtVectorElementExpr was created when
the base expression was an ObjC property dot operator.

This reverts 220d08d942ab0df3211388e602ed34fa6139ca61.

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

Added: 


Modified: 
clang/lib/Sema/SemaExprMember.cpp
clang/test/SemaObjC/property-not-lvalue.m

Removed: 




diff  --git a/clang/lib/Sema/SemaExprMember.cpp 
b/clang/lib/Sema/SemaExprMember.cpp
index 8eeed1a29dfc7..a3420ac6fdd2d 100644
--- a/clang/lib/Sema/SemaExprMember.cpp
+++ b/clang/lib/Sema/SemaExprMember.cpp
@@ -1621,16 +1621,7 @@ static ExprResult LookupMemberExpr(Sema &S, LookupResult 
&R,
   if (BaseType->isExtVectorType()) {
 // FIXME: this expr should store IsArrow.
 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
-ExprValueKind VK;
-if (IsArrow)
-  VK = VK_LValue;
-else {
-  if (PseudoObjectExpr *POE = dyn_cast(BaseExpr.get()))
-VK = POE->getSyntacticForm()->getValueKind();
-  else
-VK = BaseExpr.get()->getValueKind();
-}
-
+ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
Member, MemberLoc);
 if (ret.isNull())

diff  --git a/clang/test/SemaObjC/property-not-lvalue.m 
b/clang/test/SemaObjC/property-not-lvalue.m
index 4f8301b40ef31..029a0723ad2cb 100644
--- a/clang/test/SemaObjC/property-not-lvalue.m
+++ b/clang/test/SemaObjC/property-not-lvalue.m
@@ -7,10 +7,13 @@
} inner;
 } NSSize;
 
+typedef __attribute__((__ext_vector_type__(2))) float simd_float2;
+
 @interface Foo  {
 NSSize _size;
 }
 @property NSSize size;
+@property simd_float2 f2;
 @end
 
 void foo(void) { 
@@ -32,3 +35,8 @@ - (void)MyView_sharedInit {
 }
 - (NSSize)size {}
 @end
+
+// clang used to crash compiling this code.
+void test(Foo *f) {
+  simd_float2 *v = &f.f2.xy; // expected-error {{cannot take the address of an 
rvalue}}
+}



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


[PATCH] D138028: [clangd] Fix action `RemoveUsingNamespace` for inline namespace

2022-11-15 Thread v1nh1shungry via Phabricator via cfe-commits
v1nh1shungry added inline comments.



Comment at: 
clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp:212
   // Produce replacements to add the qualifiers.
   std::string Qualifier = printUsingNamespaceName(Ctx, *TargetDirective) + 
"::";
   for (auto Loc : IdentsToQualify) {

tom-anders wrote:
> v1nh1shungry wrote:
> > We can replace `printUsingNamespaceName` with `printNamespaceScope` here so 
> > that we can get `a::foobar()` in the test. 
> > 
> > However, it can sometimes cause redundancy such as in the 10th test. 
> > 
> > And I don't know whether it is worth it. WDYT?
> Just making sure I understood this correctly:
> 
> If you replace `printUsingNamespaceName` with `printNamespaceScope`, then...
> 
> - ...in the test you added it would result in `a::foobar()` instead of 
> `a::b::foobar()` (which is better)
> - ... but in this test (which is the 10th test if I counted correctly):
>  
> ```
>  namespace a::b { struct Foo {}; }
>   using namespace a;
>   using namespace a::[[b]];
>   using namespace b;
>   int main() { Foo F;}
> ```
> what would be the result..? would you get `a::Foo` instead of `a::b::Foo`?
> 
Sorry, I mean the next test. I read `10` from the inlay hint but I forgot the 
index starts from `0` :(

The test I want to mention:
```
namespace a::b { struct Foo {}; }
using namespace a;
using namespace a::b;
using namespace [[b]];
int main() { Foo F;}
```

We will get `a::b::Foo` in both the 10th and 11th tests. So in the 10th test, 
we don't get any benefits and don't sacrifice anything. In the 11th test, we 
get more redundancy than the existing version.

Apologize again for my mistake.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138028

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


[PATCH] D137583: [lldb] Fix simple template names and template params with scope qualifiers

2022-11-15 Thread Arthur Eubanks via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGcb0ffa529a0f: [lldb] Fix simple template names and template 
params with scope qualifiers (authored by aeubanks).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137583

Files:
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
  lldb/test/API/lang/cpp/unique-types2/TestUniqueTypes2.py
  lldb/test/API/lang/cpp/unique-types2/main.cpp

Index: lldb/test/API/lang/cpp/unique-types2/main.cpp
===
--- lldb/test/API/lang/cpp/unique-types2/main.cpp
+++ lldb/test/API/lang/cpp/unique-types2/main.cpp
@@ -1,3 +1,7 @@
+namespace ns {
+struct Bar {};
+} // namespace ns
+
 template  struct Foo {
   T t;
   template  class Nested {
@@ -23,5 +27,6 @@
   FooPack p7;
 
   Foo::Nested n1;
+  Foo::Nested n2;
   // Set breakpoint here
 }
Index: lldb/test/API/lang/cpp/unique-types2/TestUniqueTypes2.py
===
--- lldb/test/API/lang/cpp/unique-types2/TestUniqueTypes2.py
+++ lldb/test/API/lang/cpp/unique-types2/TestUniqueTypes2.py
@@ -36,6 +36,7 @@
 self.expect("image lookup -A -t 'Foo::Nested'", DATA_TYPES_DISPLAYED_CORRECTLY, error=True)
 self.expect("image lookup -A -t 'Nested'", DATA_TYPES_DISPLAYED_CORRECTLY, substrs=["1 match found"])
 self.expect("image lookup -A -t '::Nested'", DATA_TYPES_DISPLAYED_CORRECTLY, error=True)
+self.expect("image lookup -A -t 'Foo::Nested'", DATA_TYPES_DISPLAYED_CORRECTLY, substrs=["1 match found"])
 
 self.expect_expr("t1", result_type="Foo")
 self.expect_expr("t1", result_type="Foo")
@@ -49,6 +50,7 @@
 self.expect_expr("p6", result_type="FooPack")
 self.expect_expr("p7", result_type="FooPack")
 self.expect_expr("n1", result_type="Foo::Nested")
+self.expect_expr("n2", result_type="Foo::Nested")
 
 @skipIf(compiler=no_match("clang"))
 @skipIf(compiler_version=["<", "15.0"])
Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
@@ -644,7 +644,7 @@
   // Accessors
 
   ConstString GetTypeName(lldb::opaque_compiler_type_t type,
-  bool BaseOnly) override;
+  bool base_only) override;
 
   ConstString GetDisplayTypeName(lldb::opaque_compiler_type_t type) override;
 
@@ -1051,7 +1051,8 @@
   clang::PrintingPolicy GetTypePrintingPolicy();
   /// Returns the internal type name for the given NamedDecl using the
   /// type printing policy.
-  std::string GetTypeNameForDecl(const clang::NamedDecl *named_decl);
+  std::string GetTypeNameForDecl(const clang::NamedDecl *named_decl,
+ bool qualified = true);
 
   const clang::ClassTemplateSpecializationDecl *
   GetAsTemplateSpecialization(lldb::opaque_compiler_type_t type);
Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -2131,11 +2131,12 @@
   return printing_policy;
 }
 
-std::string TypeSystemClang::GetTypeNameForDecl(const NamedDecl *named_decl) {
+std::string TypeSystemClang::GetTypeNameForDecl(const NamedDecl *named_decl,
+bool qualified) {
   clang::PrintingPolicy printing_policy = GetTypePrintingPolicy();
   std::string result;
   llvm::raw_string_ostream os(result);
-  named_decl->printQualifiedName(os, printing_policy);
+  named_decl->getNameForDiagnostic(os, printing_policy, qualified);
   return result;
 }
 
@@ -3768,7 +3769,7 @@
 }
 
 ConstString TypeSystemClang::GetTypeName(lldb::opaque_compiler_type_t type,
- bool BaseOnly) {
+ bool base_only) {
   if (!type)
 return ConstString();
 
@@ -3790,9 +3791,13 @@
 return ConstString(GetTypeNameForDecl(typedef_decl));
   }
 
-  clang::PrintingPolicy printing_policy(GetTypePrintingPolicy());
-  printing_policy.SuppressScope = BaseOnly;
-  return ConstString(qual_type.getAsString(printing_policy));
+  // For consistency, this follows the same code path that clang uses to emit
+  // debug info. This also handles when we don't want any scopes preceding the
+  // name.
+  if (auto *named_decl = qual_type->getAsTagDecl())
+return ConstString(GetTypeNameForDecl(named_decl, !base_only));
+
+  return ConstString(qual_type.getAsString(GetTypePrintingPolicy()));
 }
 
 ConstString
___
cfe-commits mailing list
cfe-

[PATCH] D138078: [CodeGenPrepare] split critical indirect edges from callbr w/ outputs

2022-11-15 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers updated this revision to Diff 475635.
nickdesaulniers added a comment.

- another typo in release notes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138078

Files:
  clang/docs/ReleaseNotes.rst
  llvm/docs/LangRef.rst
  llvm/include/llvm/Transforms/Utils/BasicBlockUtils.h
  llvm/lib/CodeGen/CodeGenPrepare.cpp
  llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp
  llvm/test/CodeGen/X86/callbr-asm-outputs.ll
  llvm/test/Transforms/CodeGenPrepare/AArch64/callbr.ll

Index: llvm/test/Transforms/CodeGenPrepare/AArch64/callbr.ll
===
--- /dev/null
+++ llvm/test/Transforms/CodeGenPrepare/AArch64/callbr.ll
@@ -0,0 +1,165 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
+; RUN: opt -S -codegenprepare %s -o - | FileCheck %s
+
+target triple = "aarch64-linux-gnu"
+
+; Don't split edges unless they are critical and callbr produces output.
+; Here we have neither.
+define i32 @dont_split0() {
+; CHECK-LABEL: @dont_split0(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:callbr void asm "", "!i"()
+; CHECK-NEXT:to label [[X:%.*]] [label %y]
+; CHECK:   x:
+; CHECK-NEXT:ret i32 42
+; CHECK:   y:
+; CHECK-NEXT:ret i32 0
+;
+entry:
+  callbr void asm "", "!i"()
+  to label %x [label %y]
+
+x:
+  ret i32 42
+
+y:
+  ret i32 0
+}
+
+; Don't split edges unless they are critical and callbr produces output.
+; Here we have output, but no critical edge.
+define i32 @dont_split1() {
+; CHECK-LABEL: @dont_split1(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[TMP0:%.*]] = callbr i32 asm "", "=r,!i"()
+; CHECK-NEXT:to label [[X:%.*]] [label %y]
+; CHECK:   x:
+; CHECK-NEXT:ret i32 42
+; CHECK:   y:
+; CHECK-NEXT:ret i32 [[TMP0]]
+;
+entry:
+  %0 = callbr i32 asm "", "=r,!i"()
+  to label %x [label %y]
+
+x:
+  ret i32 42
+
+y:
+  ret i32 %0
+}
+
+; Don't split edges unless they are critical and callbr produces output.
+; Here we have a critical edge along an indirect branch, but no output.
+define i32 @dont_split2() {
+; CHECK-LABEL: @dont_split2(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:callbr void asm "", "!i"()
+; CHECK-NEXT:to label [[X:%.*]] [label %y]
+; CHECK:   x:
+; CHECK-NEXT:br label [[Y:%.*]]
+; CHECK:   y:
+; CHECK-NEXT:[[TMP0:%.*]] = phi i32 [ 0, [[X]] ], [ 42, [[ENTRY:%.*]] ]
+; CHECK-NEXT:ret i32 [[TMP0]]
+;
+entry:
+  callbr void asm "", "!i"()
+  to label %x [label %y]
+
+x:
+  br label %y
+
+y:
+  %0 = phi i32 [ 0, %x ], [ 42, %entry ]
+  ret i32 %0
+}
+
+; Don't split edges unless they are critical and callbr produces output.
+; Here we have output and a critical edge along an indirect branch.
+define i32 @split_me0() {
+; CHECK-LABEL: @split_me0(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[TMP0:%.*]] = callbr i32 asm "", "=r,!i"()
+; CHECK-NEXT:to label [[X:%.*]] [label %entry.y_crit_edge]
+; CHECK:   entry.y_crit_edge:
+; CHECK-NEXT:br label [[Y:%.*]]
+; CHECK:   x:
+; CHECK-NEXT:br label [[Y]]
+; CHECK:   y:
+; CHECK-NEXT:[[TMP1:%.*]] = phi i32 [ [[TMP0]], [[ENTRY_Y_CRIT_EDGE:%.*]] ], [ 42, [[X]] ]
+; CHECK-NEXT:ret i32 [[TMP1]]
+;
+entry:
+  %0 = callbr i32 asm "", "=r,!i"()
+  to label %x [label %y]
+
+x:
+  br label %y
+
+y:
+  %1 = phi i32 [ %0, %entry ], [ 42, %x ]
+  ret i32 %1
+}
+
+; Here we have output and a critical edge along an indirect branch.
+; Ensure that if we repeat the indirect destination, that we only split it
+; once.
+define i32 @split_me1(i1 %z) {
+; CHECK-LABEL: @split_me1(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:br i1 [[Z:%.*]], label [[W:%.*]], label [[V:%.*]]
+; CHECK:   w:
+; CHECK-NEXT:[[TMP0:%.*]] = callbr i32 asm "", "=r,!i,!i"()
+; CHECK-NEXT:to label [[X:%.*]] [label [[W_V_CRIT_EDGE:%.*]], label %w.v_crit_edge]
+; CHECK:   w.v_crit_edge:
+; CHECK-NEXT:br label [[V]]
+; CHECK:   x:
+; CHECK-NEXT:ret i32 42
+; CHECK:   v:
+; CHECK-NEXT:ret i32 0
+;
+entry:
+  br i1 %z, label %w, label %v
+
+w:
+  %0 = callbr i32 asm "", "=r,!i,!i"()
+  to label %x [label %v, label %v]
+
+x:
+  ret i32 42
+
+v:
+  ret i32 0
+}
+
+; A more interessting case of @split_me1. Check that we still only split the
+; critical edge from w to v once.
+define i32 @split_me2(i1 %z) {
+; CHECK-LABEL: @split_me2(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:br i1 [[Z:%.*]], label [[W:%.*]], label [[V:%.*]]
+; CHECK:   w:
+; CHECK-NEXT:[[TMP0:%.*]] = callbr i32 asm "", "=r,!i,!i"()
+; CHECK-NEXT:to label [[X:%.*]] [label [[W_V_CRIT_EDGE:%.*]], label %w.v_crit_edge]
+; CHECK:   w.v_crit_edge:
+; CHECK-NEXT:br label [[V]]
+; CHECK:   x:
+; CHECK-NEXT:ret i32 42
+; CHECK:   v:
+; CHECK-NEXT:[[TMP1:%.*]] = phi i32 [ [[TMP0]], [[W_V_CRIT_EDGE]] ], [ 42, [[ENTRY:%.*]] ]
+; CHECK-NEXT:ret i32 [[TMP1]]
+;
+entry:
+  br i1 %z, label %w, label %v
+
+w:
+  %0 = callbr i32 asm ""

[PATCH] D138078: [CodeGenPrepare] split critical indirect edges from callbr w/ outputs

2022-11-15 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers updated this revision to Diff 475634.
nickdesaulniers added a comment.

- typo, iwyu


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138078

Files:
  clang/docs/ReleaseNotes.rst
  llvm/docs/LangRef.rst
  llvm/include/llvm/Transforms/Utils/BasicBlockUtils.h
  llvm/lib/CodeGen/CodeGenPrepare.cpp
  llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp
  llvm/test/CodeGen/X86/callbr-asm-outputs.ll
  llvm/test/Transforms/CodeGenPrepare/AArch64/callbr.ll

Index: llvm/test/Transforms/CodeGenPrepare/AArch64/callbr.ll
===
--- /dev/null
+++ llvm/test/Transforms/CodeGenPrepare/AArch64/callbr.ll
@@ -0,0 +1,165 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
+; RUN: opt -S -codegenprepare %s -o - | FileCheck %s
+
+target triple = "aarch64-linux-gnu"
+
+; Don't split edges unless they are critical and callbr produces output.
+; Here we have neither.
+define i32 @dont_split0() {
+; CHECK-LABEL: @dont_split0(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:callbr void asm "", "!i"()
+; CHECK-NEXT:to label [[X:%.*]] [label %y]
+; CHECK:   x:
+; CHECK-NEXT:ret i32 42
+; CHECK:   y:
+; CHECK-NEXT:ret i32 0
+;
+entry:
+  callbr void asm "", "!i"()
+  to label %x [label %y]
+
+x:
+  ret i32 42
+
+y:
+  ret i32 0
+}
+
+; Don't split edges unless they are critical and callbr produces output.
+; Here we have output, but no critical edge.
+define i32 @dont_split1() {
+; CHECK-LABEL: @dont_split1(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[TMP0:%.*]] = callbr i32 asm "", "=r,!i"()
+; CHECK-NEXT:to label [[X:%.*]] [label %y]
+; CHECK:   x:
+; CHECK-NEXT:ret i32 42
+; CHECK:   y:
+; CHECK-NEXT:ret i32 [[TMP0]]
+;
+entry:
+  %0 = callbr i32 asm "", "=r,!i"()
+  to label %x [label %y]
+
+x:
+  ret i32 42
+
+y:
+  ret i32 %0
+}
+
+; Don't split edges unless they are critical and callbr produces output.
+; Here we have a critical edge along an indirect branch, but no output.
+define i32 @dont_split2() {
+; CHECK-LABEL: @dont_split2(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:callbr void asm "", "!i"()
+; CHECK-NEXT:to label [[X:%.*]] [label %y]
+; CHECK:   x:
+; CHECK-NEXT:br label [[Y:%.*]]
+; CHECK:   y:
+; CHECK-NEXT:[[TMP0:%.*]] = phi i32 [ 0, [[X]] ], [ 42, [[ENTRY:%.*]] ]
+; CHECK-NEXT:ret i32 [[TMP0]]
+;
+entry:
+  callbr void asm "", "!i"()
+  to label %x [label %y]
+
+x:
+  br label %y
+
+y:
+  %0 = phi i32 [ 0, %x ], [ 42, %entry ]
+  ret i32 %0
+}
+
+; Don't split edges unless they are critical and callbr produces output.
+; Here we have output and a critical edge along an indirect branch.
+define i32 @split_me0() {
+; CHECK-LABEL: @split_me0(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[TMP0:%.*]] = callbr i32 asm "", "=r,!i"()
+; CHECK-NEXT:to label [[X:%.*]] [label %entry.y_crit_edge]
+; CHECK:   entry.y_crit_edge:
+; CHECK-NEXT:br label [[Y:%.*]]
+; CHECK:   x:
+; CHECK-NEXT:br label [[Y]]
+; CHECK:   y:
+; CHECK-NEXT:[[TMP1:%.*]] = phi i32 [ [[TMP0]], [[ENTRY_Y_CRIT_EDGE:%.*]] ], [ 42, [[X]] ]
+; CHECK-NEXT:ret i32 [[TMP1]]
+;
+entry:
+  %0 = callbr i32 asm "", "=r,!i"()
+  to label %x [label %y]
+
+x:
+  br label %y
+
+y:
+  %1 = phi i32 [ %0, %entry ], [ 42, %x ]
+  ret i32 %1
+}
+
+; Here we have output and a critical edge along an indirect branch.
+; Ensure that if we repeat the indirect destination, that we only split it
+; once.
+define i32 @split_me1(i1 %z) {
+; CHECK-LABEL: @split_me1(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:br i1 [[Z:%.*]], label [[W:%.*]], label [[V:%.*]]
+; CHECK:   w:
+; CHECK-NEXT:[[TMP0:%.*]] = callbr i32 asm "", "=r,!i,!i"()
+; CHECK-NEXT:to label [[X:%.*]] [label [[W_V_CRIT_EDGE:%.*]], label %w.v_crit_edge]
+; CHECK:   w.v_crit_edge:
+; CHECK-NEXT:br label [[V]]
+; CHECK:   x:
+; CHECK-NEXT:ret i32 42
+; CHECK:   v:
+; CHECK-NEXT:ret i32 0
+;
+entry:
+  br i1 %z, label %w, label %v
+
+w:
+  %0 = callbr i32 asm "", "=r,!i,!i"()
+  to label %x [label %v, label %v]
+
+x:
+  ret i32 42
+
+v:
+  ret i32 0
+}
+
+; A more interessting case of @split_me1. Check that we still only split the
+; critical edge from w to v once.
+define i32 @split_me2(i1 %z) {
+; CHECK-LABEL: @split_me2(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:br i1 [[Z:%.*]], label [[W:%.*]], label [[V:%.*]]
+; CHECK:   w:
+; CHECK-NEXT:[[TMP0:%.*]] = callbr i32 asm "", "=r,!i,!i"()
+; CHECK-NEXT:to label [[X:%.*]] [label [[W_V_CRIT_EDGE:%.*]], label %w.v_crit_edge]
+; CHECK:   w.v_crit_edge:
+; CHECK-NEXT:br label [[V]]
+; CHECK:   x:
+; CHECK-NEXT:ret i32 42
+; CHECK:   v:
+; CHECK-NEXT:[[TMP1:%.*]] = phi i32 [ [[TMP0]], [[W_V_CRIT_EDGE]] ], [ 42, [[ENTRY:%.*]] ]
+; CHECK-NEXT:ret i32 [[TMP1]]
+;
+entry:
+  br i1 %z, label %w, label %v
+
+w:
+  %0 = callbr i32 asm "", "=r,!i,!i"()
+  t

[PATCH] D138078: [CodeGenPrepare] split critical indirect edges from callbr w/ outputs

2022-11-15 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:187
+  two inputs may have compared equal in the inline assembly.  This is no longer
+  garunteed (and necessary to support outputs along indirect edges, which is
+  still not yet supported).

Typo garunteed


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138078

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


[PATCH] D134921: [HLSL] add cos library function

2022-11-15 Thread Joshua Batista via Phabricator via cfe-commits
bob80905 updated this revision to Diff 475633.
bob80905 added a comment.

- remove int overloads
- remove double
- update tests after new builtin landed


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134921

Files:
  clang/lib/Headers/hlsl/hlsl_intrinsics.h
  clang/test/CodeGenHLSL/builtins/cos.hlsl

Index: clang/test/CodeGenHLSL/builtins/cos.hlsl
===
--- /dev/null
+++ clang/test/CodeGenHLSL/builtins/cos.hlsl
@@ -0,0 +1,56 @@
+// RUN: %clang_cc1 -std=hlsl2021 -finclude-default-header -x hlsl -triple \
+// RUN:   dxil-pc-shadermodel6.3-library %s -fnative-half-type \
+// RUN:   -emit-llvm -disable-llvm-passes -O3 -o - | FileCheck %s
+// RUN: %clang_cc1 -std=hlsl2021 -finclude-default-header -x hlsl -triple \
+// RUN:   dxil-pc-shadermodel6.3-library %s -emit-llvm -disable-llvm-passes \
+// RUN:   -D__HLSL_ENABLE_16_BIT -o - | FileCheck %s --check-prefix=NO_HALF
+
+// CHECK: define noundef half @
+// CHECK: call half @llvm.cos.f16(
+// NO_HALF: define noundef float @"?test_cos_half@@YA$halff@$halff@@Z"(
+// NO_HALF: call float @llvm.cos.f32(
+half test_cos_half ( half p0 ) {
+  return cos ( p0 );
+}
+// CHECK: define noundef <2 x half> @
+// CHECK: call <2 x half> @llvm.cos.v2f16
+// NO_HALF: define noundef <2 x float> @"?test_cos_float2@@YAT?$__vector@M$01@__clang@@T12@@Z"(
+// NO_HALF: call <2 x float> @llvm.cos.v2f32(
+half2 test_cos_half2 ( half2 p0 ) {
+  return cos ( p0 );
+}
+// CHECK: define noundef <3 x half> @
+// CHECK: call <3 x half> @llvm.cos.v3f16
+// NO_HALF: define noundef <3 x float> @"?test_cos_float3@@YAT?$__vector@M$02@__clang@@T12@@Z"(
+// NO_HALF: call <3 x float> @llvm.cos.v3f32(
+half3 test_cos_half3 ( half3 p0 ) {
+  return cos ( p0 );
+}
+// CHECK: define noundef <4 x half> @
+// CHECK: call <4 x half> @llvm.cos.v4f16
+// NO_HALF: define noundef <4 x float> @"?test_cos_float4@@YAT?$__vector@M$03@__clang@@T12@@Z"(
+// NO_HALF: call <4 x float> @llvm.cos.v4f32(
+half4 test_cos_half4 ( half4 p0 ) {
+  return cos ( p0 );
+}
+
+// CHECK: define noundef float @
+// CHECK: call float @llvm.cos.f32(
+float test_cos_float ( float p0 ) {
+  return cos ( p0 );
+}
+// CHECK: define noundef <2 x float> @
+// CHECK: call <2 x float> @llvm.cos.v2f32
+float2 test_cos_float2 ( float2 p0 ) {
+  return cos ( p0 );
+}
+// CHECK: define noundef <3 x float> @
+// CHECK: call <3 x float> @llvm.cos.v3f32
+float3 test_cos_float3 ( float3 p0 ) {
+  return cos ( p0 );
+}
+// CHECK: define noundef <4 x float> @
+// CHECK: call <4 x float> @llvm.cos.v4f32
+float4 test_cos_float4 ( float4 p0 ) {
+  return cos ( p0 );
+}
Index: clang/lib/Headers/hlsl/hlsl_intrinsics.h
===
--- clang/lib/Headers/hlsl/hlsl_intrinsics.h
+++ clang/lib/Headers/hlsl/hlsl_intrinsics.h
@@ -101,6 +101,35 @@
 __attribute__((clang_builtin_alias(__builtin_elementwise_ceil)))
 double4 ceil(double4);
 
-} // namespace hlsl
 
+// cos builtins
+#ifdef __HLSL_ENABLE_16_BIT
+__attribute__((clang_builtin_alias(__builtin_elementwise_cos))) half cos(half);
+__attribute__((clang_builtin_alias(__builtin_elementwise_cos)))
+half2 cos(half2);
+__attribute__((clang_builtin_alias(__builtin_elementwise_cos)))
+half3 cos(half3);
+__attribute__((clang_builtin_alias(__builtin_elementwise_cos)))
+half4 cos(half4);
+#endif
+
+__attribute__((clang_builtin_alias(__builtin_elementwise_cos))) float
+cos(float);
+__attribute__((clang_builtin_alias(__builtin_elementwise_cos)))
+float2 cos(float2);
+__attribute__((clang_builtin_alias(__builtin_elementwise_cos)))
+float3 cos(float3);
+__attribute__((clang_builtin_alias(__builtin_elementwise_cos)))
+float4 cos(float4);
+
+__attribute__((clang_builtin_alias(__builtin_elementwise_cos))) double
+cos(double);
+__attribute__((clang_builtin_alias(__builtin_elementwise_cos)))
+double2 cos(double2);
+__attribute__((clang_builtin_alias(__builtin_elementwise_cos)))
+double3 cos(double3);
+__attribute__((clang_builtin_alias(__builtin_elementwise_cos)))
+double4 cos(double4);
+
+} // namespace hlsl
 #endif //_HLSL_HLSL_INTRINSICS_H_
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D138078: [CodeGenPrepare] split critical indirect edges from callbr w/ outputs

2022-11-15 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers created this revision.
nickdesaulniers added reviewers: void, jyknight, efriedma, craig.topper.
Herald added subscribers: StephenFan, jdoerfert, pengfei, hiraditya.
Herald added a project: All.
nickdesaulniers requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

Towards the goal of supporting outputs from callbr in its indirect
successors, split indirect edges that are critical when there are
outputs.

There are 2 invariants of LLVM that make this change necessary. Consider
a callbr with outputs that have physical register constraints, where the
indirect destination tries to use the result in a PHI.

The first constraint is that PHIs in MachineIR (MIR) do not support a
mix of physreg and virtreg operands. Physregs MUST be COPY'd to a
virtreg BEFORE they can be used in a PHI.

The second constraint is that PHIs MUST occur before non-PHIs in
MachineBasicBlocks. So where do we place the COPY, in the predecessor or
the successor? A: Neither. We split the "critical edge" that occurs when
the predecessor has multiple successors and the successor has multiple
predecessors.  In a follow up patch, we could then place the COPY in
that newly synthesized block, but this patch is just the critical edge
splitting.

This change was done prior to support for outputs along indirect edges,
because the changes to existing tests for outputs along the direct edge
are quite noisy and tricky to review itself.

Labels can be passed to asm goto in BOTH the input operands AND goto
labels lists, example:

  foo: asm goto ("# %0 %1"::"i"(&&foo)::foo);

This change has the implications that in the inline asm, the above
parameters need not compare equal; the goto label might refer to the
block synthesized when we split the critical edge while the input
operand will refer to the final destination. IMO, you're asking for
trouble if you have code doing this, but this patch will very much
change the codegen of LLVM in such an observable way. We initially
decided not to do this during the initial implementation of support for
outputs along "fallthrough" (aka "direct") edges from callbr, but
support for outputs along indirect edges is more valuable (subjective)
than labels passed simultaneously as input operands and goto labels
comparing equal. Also, this is how GCC chose to implement support for
outputs along indirect edges. Document this behavior change.

While CodeGenPrepare seems like a curious place to split critical edges,
the question "when is the best time to split critical edges" is perhaps
important to consider. SelectionDAG operates per BasicBlock and it's not
easy to visit other BasicBlocks during instruction selection.
MachineBasicBlock::canSplitCritical edge also avoids permitting critical
edge splitting for INLINEASM_BR indirect edges. The point of
CodeGenPrepare is to nudge LLVM IR to help SelectionDAG along. Also,
CodeGenPrepare has custom critical edge splitting for indirectbr, which
is a common theme for callbr.

Also, it might seem like we could also avoid splitting the
critical+indirect edge when there's no physreg defines, but it helps the
later patch for outputs along indirect edges not have to special case
virtreg COPYs vs physreg COPYs.

Link: https://github.com/llvm/llvm-project/issues/53562


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138078

Files:
  clang/docs/ReleaseNotes.rst
  llvm/docs/LangRef.rst
  llvm/include/llvm/Transforms/Utils/BasicBlockUtils.h
  llvm/lib/CodeGen/CodeGenPrepare.cpp
  llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp
  llvm/test/CodeGen/X86/callbr-asm-outputs.ll
  llvm/test/Transforms/CodeGenPrepare/AArch64/callbr.ll

Index: llvm/test/Transforms/CodeGenPrepare/AArch64/callbr.ll
===
--- /dev/null
+++ llvm/test/Transforms/CodeGenPrepare/AArch64/callbr.ll
@@ -0,0 +1,165 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
+; RUN: opt -S -codegenprepare %s -o - | FileCheck %s
+
+target triple = "aarch64-linux-gnu"
+
+; Don't split edges unless they are critical and callbr produces output.
+; Here we have neither.
+define i32 @dont_split0() {
+; CHECK-LABEL: @dont_split0(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:callbr void asm "", "!i"()
+; CHECK-NEXT:to label [[X:%.*]] [label %y]
+; CHECK:   x:
+; CHECK-NEXT:ret i32 42
+; CHECK:   y:
+; CHECK-NEXT:ret i32 0
+;
+entry:
+  callbr void asm "", "!i"()
+  to label %x [label %y]
+
+x:
+  ret i32 42
+
+y:
+  ret i32 0
+}
+
+; Don't split edges unless they are critical and callbr produces output.
+; Here we have output, but no critical edge.
+define i32 @dont_split1() {
+; CHECK-LABEL: @dont_split1(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[TMP0:%.*]] = callbr i32 asm "", "=r,!i"()
+; CHECK-NEXT:to label [[X:%.*]] [label %y]
+; CHECK:   x:
+; CHECK-NEXT:ret i32 42
+; CHECK:   y:
+; CHECK-NEXT:ret i32 [[TMP0]]
+;
+

[PATCH] D137986: [Clang][CodeGen][AIX] Map __builtin_frexpl, __builtin_ldexpl, and __builtin_modfl to 'double' version lib calls in 64-bit 'long double' mode

2022-11-15 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added inline comments.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:112
+  // double' mode.
+  static SmallDenseMap AIXLongDoubleBuiltins{
+  {Builtin::BI__builtin_frexpl, "frexp"},

Please rename to "AIXLongDouble64Builtins".



Comment at: clang/test/CodeGen/aix-builtin-mapping.c:3
+// 'long double'. Check that the compiler generates calls to the 'double'
+// versions for correspoding builtin functions in 64-bit 'long double' mode.
+

Fix typo.



Comment at: clang/test/CodeGen/aix-builtin-mapping.c:5-6
+
+// RUN: %clang_cc1 -triple powerpc-ibm-aix -mlong-double-64 -S -o - %s | 
FileCheck %s -check-prefix=CHECK
+// RUN: %clang_cc1 -triple powerpc64-ibm-aix -mlong-double-64 -S -o - %s | 
FileCheck %s -check-prefix=CHECK
+

This should be an IR test. Checking assembly means actually needing the PowerPC 
target enabled in the LLVM configuration.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137986

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


[PATCH] D138058: [Sema] Use the value category of the base expression when creating an ExtVectorElementExpr

2022-11-15 Thread John McCall via Phabricator via cfe-commits
rjmccall accepted this revision.
rjmccall added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138058

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


[PATCH] D135488: [codegen] Display stack layouts in console

2022-11-15 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

In D135488#3928831 , @dblaikie wrote:

> Any chance we could ... emit it as part of the 
> frame-larger-than/warn-stack-size diagnostic?

This pass prints a TON of (helpful) information...we have a lot of 
`-Wframe-larger-than=` instances triggered in our codebase...I think having 
this on by default would blow our logs significantly.  That's why it might be 
nice to have a Note suggest a flag (default off) for more info on a case by 
case basis.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135488

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


[PATCH] D138073: [clang-doc] Move file layout to the generators.

2022-11-15 Thread Brett Wilson via Phabricator via cfe-commits
brettw added a comment.

If you're curious, you can see the simplification the YAML output format change 
makes in the consuming code:
https://fuchsia-review.git.corp.google.com/c/fuchsia/+/760570/2/tools/cppdocgen/clangdoc/clangdoc.go
Since it allows us to remove some special-casing code for loading things in the 
global namespace and for anonymous records.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138073

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


[PATCH] D138073: [clang-doc] Move file layout to the generators.

2022-11-15 Thread Brett Wilson via Phabricator via cfe-commits
brettw created this revision.
brettw added a reviewer: paulkirth.
brettw added a project: clang-tools-extra.
Herald added subscribers: kadircet, arphaman.
Herald added a project: All.
brettw requested review of this revision.
Herald added subscribers: cfe-commits, ilya-biryukov.

Previously file naming and directory layout was handled on a per Info object 
basis by ClangDocMain and the generators blindly wrote to the files given. This 
means all generators must use the same file layout and caused problems where 
multiple objects mapped to the same file. The object collision problem happens 
most easily with template specializations because the template parameters are 
not part of the "name".

  

This patch moves the responsibility for output file organization to the 
generators. Currently HTML and MD use the same structure as before. But they 
now collect all objects that map to a given file and combine them, avoiding the 
corruption problems.

  

Converts the YAML generator to naming files based on USR in one directory. This 
is easier for downstream tools to manage and avoids the naming problems with 
template specializations. Since this change requires backward-incompatible 
output changes to referenced files anyway (since each one is now an array), 
this is a good time to introduce this change.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138073

Files:
  clang-tools-extra/clang-doc/Generators.h
  clang-tools-extra/clang-doc/HTMLGenerator.cpp
  clang-tools-extra/clang-doc/MDGenerator.cpp
  clang-tools-extra/clang-doc/YAMLGenerator.cpp
  clang-tools-extra/clang-doc/tool/ClangDocMain.cpp

Index: clang-tools-extra/clang-doc/tool/ClangDocMain.cpp
===
--- clang-tools-extra/clang-doc/tool/ClangDocMain.cpp
+++ clang-tools-extra/clang-doc/tool/ClangDocMain.cpp
@@ -43,6 +43,7 @@
 #include "llvm/Support/ThreadPool.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
+#include 
 #include 
 
 using namespace clang::ast_matchers;
@@ -130,54 +131,6 @@
   return llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
 }
 
-bool CreateDirectory(const Twine &DirName, bool ClearDirectory = false) {
-  std::error_code OK;
-  llvm::SmallString<128> DocsRootPath;
-  if (ClearDirectory) {
-std::error_code RemoveStatus = llvm::sys::fs::remove_directories(DirName);
-if (RemoveStatus != OK) {
-  llvm::errs() << "Unable to remove existing documentation directory for "
-   << DirName << ".\n";
-  return true;
-}
-  }
-  std::error_code DirectoryStatus = llvm::sys::fs::create_directories(DirName);
-  if (DirectoryStatus != OK) {
-llvm::errs() << "Unable to create documentation directories.\n";
-return true;
-  }
-  return false;
-}
-
-// A function to extract the appropriate file name for a given info's
-// documentation. The path returned is a composite of the output directory, the
-// info's relative path and name and the extension. The relative path should
-// have been constructed in the serialization phase.
-//
-// Example: Given the below, the  path for class C will be
-// /A/B/C.
-//
-// namespace A {
-// namespace B {
-//
-// class C {};
-//
-// }
-// }
-llvm::Expected> getInfoOutputFile(StringRef Root,
- StringRef RelativePath,
- StringRef Name,
- StringRef Ext) {
-  llvm::SmallString<128> Path;
-  llvm::sys::path::native(Root, Path);
-  llvm::sys::path::append(Path, RelativePath);
-  if (CreateDirectory(Path))
-return llvm::createStringError(llvm::inconvertibleErrorCode(),
-   "failed to create directory");
-  llvm::sys::path::append(Path, Name + Ext);
-  return Path;
-}
-
 int main(int argc, const char **argv) {
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
   std::error_code OK;
@@ -274,6 +227,11 @@
 R.first->second.emplace_back(Value);
   });
 
+  // Collects all Infos according to their unique USR value. This map is added
+  // to from the thread pool below and is protected by the USRToInfoMutex.
+  llvm::sys::Mutex USRToInfoMutex;
+  llvm::StringMap> USRToInfo;
+
   // First reducing phase (reduce all decls into one info per decl).
   llvm::outs() << "Reducing " << USRToBitcode.size() << " infos...\n";
   std::atomic Error;
@@ -304,31 +262,17 @@
 return;
   }
 
-  doc::Info *I = Reduced.get().get();
-  auto InfoPath =
-  getInfoOutputFile(OutDirectory, I->getRelativeFilePath(""),
-I->getFileBaseName(), "." + Format);
-  if (!InfoPath) {
-llvm::errs() << toString(InfoPath.takeError()) << "\n";
-Error = true;
-return;
-  }
-  std::error_code FileErr;
-  llvm::raw_fd_ostream InfoOS(InfoPath.get(), FileErr,
-  llvm::sys::fs::OF_None);
-  

[PATCH] D137346: -Wunsafe-buffer-usage: Initial commit - Transition away from raw buffer accesses.

2022-11-15 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h:29
+  /// Invoked when an unsafe operation over raw pointers is found.
+  virtual void handleUnsafeOperation(const Stmt *Operation) = 0;
+};

xazax.hun wrote:
>  What is the purpose of the handler, would this add the fixit hints? In that 
> case, is this the right abstraction level? E.g., do we want to group these by 
> the declarations so the handler can rewrite the declaration and its uses at 
> once? 
You're absolutely right, we want to group fixits by declarations when fixits 
are actually available.

But we still need to cover the case when fixits *aren't* available, and in this 
case it doesn't make sense to group anything, so this interface isn't going 
away.

And on top of that, there's layers to grouping. For instance, in this code
```
void foo(int *p, size_t size) {
  int *q = p;
  for (size_t i = 0; i < size; ++i)
q[i] = 0;
}
```
we'll need to attach the fix to the declaration `p` rather than `q`, as we aim 
to provide a single fixit for these two variables, because otherwise we end up 
with a low-quality fix that suppresses the warning but doesn't carry the span 
all the way from the caller to the use site.

Then if we have two parameters that we want to fix simultaneously this way, the 
fix will have to be inevitably grouped by *function* declaration.



Comment at: clang/lib/Analysis/UnsafeBufferUsage.cpp:22
+// Scan the function and return a list of gadgets found with provided kits.
+static GadgetList findGadgets(const Decl *D) {
+

xazax.hun wrote:
> Is this not a FunctionDecl because of ObjCMethod? At some point I wonder if 
> we should have an abstraction that works for both. Would NamedDecl work?
Yupp.

Well, we do have https://clang.llvm.org/doxygen/classclang_1_1AnyCall.html But 
it's not like the code actually cares at this point. And once it does (eg. for 
the purposes of fixits), it'll have to consider them separately anyway.



Comment at: clang/lib/Analysis/UnsafeBufferUsage.cpp:35-36
+
+  GadgetList G;
+  MatchFinder M;
+

xazax.hun wrote:
> Move these close to their uses?
The code in between is actually instantly deleted by the follow-up patch :)

(D137348)


Repository:
  rC Clang

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

https://reviews.llvm.org/D137346

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


[PATCH] D137259: [clang][modules][deps] WIP: In-memory module transfer

2022-11-15 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 475613.
jansvoboda11 added a comment.

Fixed two tests:

- modules-pch.c by always marking identifier info as not out-of-date when 
getting leaf module macros,
- modules-module-map-order.m by updating the sorting logic for gathering 
`SortedFiles`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137259

Files:
  clang/include/clang/Frontend/CompilerInstance.h
  clang/include/clang/Lex/PreprocessorOptions.h
  clang/include/clang/Lex/Token.h
  clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Frontend/FrontendActions.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/lib/Serialization/GeneratePCH.cpp
  clang/lib/Tooling/DependencyScanning/DependencyScanningService.cpp
  clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
  clang/test/ClangScanDeps/modules-basic.c

Index: clang/test/ClangScanDeps/modules-basic.c
===
--- /dev/null
+++ clang/test/ClangScanDeps/modules-basic.c
@@ -0,0 +1,135 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+//--- include/module.modulemap
+module top { header "top.h" }
+module left { header "left.h" }
+module right { header "right.h" }
+module right_extra { header "right-extra.h" }
+module bottom { header "bottom.h" }
+//--- include/top.h
+//
+#define D1
+//--- include/left.h
+///
+#include "top.h"
+#define D2
+//--- include/right.h
+
+#include "right-extra.h"
+#include "top.h"
+#define D3
+//--- include/right-extra.h
+/
+#define D4
+//--- include/bottom.h
+//
+#include "left.h"
+#include "right.h"
+#define D5
+//--- include/t.h
+
+//--- tu.c
+#include "bottom.h"
+#ifdef D1
+#endif
+#ifdef D2
+#endif
+#ifdef D3
+#endif
+#ifdef D4
+#endif
+#ifdef D5
+#endif
+
+#define D1
+#define D2
+#define D3
+#define D4
+#define D5
+
+//--- cdb.json.template
+[{
+  "file": "DIR/tu.c",
+  "directory": "DIR",
+  "command": "clang -fsyntax-only DIR/tu.c -fmodules -fmodules-cache-path=DIR/cache -fimplicit-module-maps -I DIR/include"
+}]
+
+// RUN: sed "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full > %t/result.json
+// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
+
+// CHECK: {
+// CHECK-NEXT:   "modules": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   clang-module-deps": [
+// CHECK-NEXT:{
+// CHECK-NEXT:  "context-hash": "[[X_HASH:.*]]",
+// CHECK-NEXT:  "module-name": "x"
+// CHECK-NEXT:}
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "clang-modulemap-file": "[[PREFIX]]/include/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK-NEXT: "-cc1",
+// CHECK:  "-o",
+// CHECK-NEXT: "[[PREFIX]]/cache/{{.*}}/m-{{.*}}.pcm",
+// CHECK:  "-emit-module",
+// CHECK:  "[[PREFIX]]/include/module.modulemap",
+// CHECK:  "-fmodules",
+// CHECK:  "-fmodule-name=m",
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "[[M_HASH:.*]]",
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: "[[PREFIX]]/include/m.h",
+// CHECK-NEXT: "[[PREFIX]]/include/module.modulemap"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "m"
+// CHECK-NEXT: },
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file": "[[PREFIX]]/include/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK-NEXT: "-cc1",
+// CHECK:  "-o",
+// CHECK-NEXT: "[[PREFIX]]/cache/{{.*}}/x-{{.*}}.pcm",
+// CHECK:  "-emit-module",
+// CHECK:  "[[PREFIX]]/include/module.modulemap",
+// CHECK:  "-fmodules",
+// CHECK:  "-fmodule-name=x",
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "[[X_HASH]]",
+// CHECK-NEXT:"file-deps": [
+// CHECK-NEXT:  "[[PREFIX]]/include/module.modulemap",
+// CHECK-NEXT:  "[[PREFIX]]/include/x.h"
+// CHECK-NEXT:],
+// CHECK-NEXT:   "name": "x"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "translation-units": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "commands": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-context-hash": "{{.*}}",
+// CHECK-NEXT:   "clang-module-deps": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "context-hash": "[[M_HASH]]",
+// CHECK-NEXT:   "module-name": "m"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "command-line": [
+// CHECK-NEXT: "-cc1",
+// CHECK:  "-fmodule-map-file=[[PREFIX]]/include/module.modulemap",
+// CHECK:  "-fmodule-file=m=[[PREFIX]]/ca

[PATCH] D135488: [codegen] Display stack layouts in console

2022-11-15 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth added a comment.

In D135488#3928975 , @dblaikie wrote:

> Fair enough - could the warn-stack-size warning be moved to there, then, and 
> then the information included in the warning? It could have both a warning 
> and remark form, so folks could use the remark form when they just want all 
> the reports or don't want the reports phrased as a problem, but as an 
> informational message? (though this may or may not be worth it - I guess 
> people can turn on the warning, lower the threshold, and specifically make 
> this warning a non-error, which amounts to roughly the same thing as a remark)

I guess it could be moved, but I'm not sure it makes the most sense. 
`PrologEpilogueInserter` is also already emitting the optimization remarks for 
stack size, so IMO it makes sense to keep them together, since that's the place 
where that information is determined. But there is no technical reason why we 
couldn't move it later, since all the information to do the check is readily 
available.

Another point to consider is that we already have several ways to expose stack 
sizes to users. `-Wframe-larger-than` gives warnings when a threshold is 
exceeded, but we also provide `-fstack-size-section`, and `-fstack-usage` which 
output information about every function in the module.  And, as mentioned 
earlier, there is an optimization remark for stack sizes too.

Regardless, I'll take a look and see how easy it will be to expose this through 
the remarks infrastructure, since that seems to be a generally good idea here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135488

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


[PATCH] D32199: [TySan] A Type Sanitizer (Clang)

2022-11-15 Thread Florian Hahn via Phabricator via cfe-commits
fhahn commandeered this revision.
fhahn added a reviewer: CJ-Johnson.
fhahn added a comment.

Commandeering after the recent updates to make review + follow-ups easier.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D32199

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


[PATCH] D135919: [Clang] Correct when Itanium ABI guard variables are set for non-block variables with static or thread storage duration.

2022-11-15 Thread John McCall via Phabricator via cfe-commits
rjmccall accepted this revision.
rjmccall added a comment.
This revision is now accepted and ready to land.

Thanks, this looks great.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135919

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


[PATCH] D135488: [codegen] Display stack layouts in console

2022-11-15 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth updated this revision to Diff 475602.
paulkirth added a comment.

Rebase and address comments

- Replace magic comparison with `MFI.isDeadIbjectIndex()`
- Small code improvement by using a constructor w/ `emplace_back`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135488

Files:
  llvm/include/llvm/CodeGen/Passes.h
  llvm/include/llvm/InitializePasses.h
  llvm/lib/CodeGen/CMakeLists.txt
  llvm/lib/CodeGen/CodeGen.cpp
  llvm/lib/CodeGen/StackFramePrinterPass.cpp
  llvm/lib/CodeGen/TargetPassConfig.cpp
  llvm/test/CodeGen/ARM/stack-frame-printer.ll
  llvm/test/CodeGen/X86/stack-frame-printer.ll

Index: llvm/test/CodeGen/X86/stack-frame-printer.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/stack-frame-printer.ll
@@ -0,0 +1,303 @@
+; Test basic output of the -print-stack-frame pass
+
+; ensure basic output works
+; RUN: llc -mcpu=corei7 -O1 -print-stack-frame < %s 2>&1 >/dev/null | FileCheck %s
+
+; check additional slots are displayed when stack is not optimized
+; RUN: llc -mcpu=corei7 -O0 -print-stack-frame < %s 2>&1 >/dev/null | FileCheck %s --check-prefix=NO_COLORING
+
+; check more complex cases
+; RUN: llc %s -print-stack-frame -o /dev/null --march=x86 -mcpu=i386 2>&1 | FileCheck %s --check-prefix=BOTH --check-prefix=DEBUG
+
+; check output without debug info
+; RUN: opt %s -strip -S | llc  -print-stack-frame -o /dev/null --march=x86 -mcpu=i386 2>&1 | FileCheck %s --check-prefix=BOTH --check-prefix=STRIPPED
+
+target triple = "x86_64-unknown-linux-gnu"
+
+; CHECK: # Stack Layout: stackSizeWarning
+; CHECK: Offset{{.*}}Align{{.*}}Size
+; CHECK: [SP-88]{{.*}}16{{.*}}80
+; CHECK:buffer @ frame-diags.c:30
+; NO_COLORING: [SP-168]{{.*}}16{{.*}}80
+; CHECK:buffer2 @ frame-diags.c:33
+define void @stackSizeWarning() {
+entry:
+  %buffer = alloca [80 x i8], align 16
+  %buffer2 = alloca [80 x i8], align 16
+  call void @llvm.dbg.declare(metadata ptr %buffer, metadata !25, metadata !DIExpression()), !dbg !39
+  call void @llvm.dbg.declare(metadata ptr %buffer2, metadata !31, metadata !DIExpression()), !dbg !40
+  ret void
+}
+
+; Function Attrs: nocallback nofree nosync nounwind readnone speculatable willreturn
+declare void @llvm.dbg.declare(metadata, metadata, metadata) #0
+
+; BOTH: # Stack Layout: cleanup_array
+; BOTH:  Offset{{.*}}Align{{.*}}Size
+; BOTH:  [SP+4]{{.+}}16{{.+}}4
+; DEBUG: a @ dot.c:13
+; STRIPPED-NOT: a @ dot.c:13
+; BOTH:  [SP-4]{{.+}}Spill 8{{.+}}4
+define void @cleanup_array(ptr %0) #1 {
+  %2 = alloca ptr, align 8
+  store ptr %0, ptr %2, align 8
+  call void @llvm.dbg.declare(metadata ptr %2, metadata !41, metadata !DIExpression()), !dbg !46
+  ret void
+}
+
+; BOTH: # Stack Layout: cleanup_result
+; BOTH:  Offset{{.+}}Align{{.+}}Size
+; BOTH:  [SP+4]{{.+}}16{{.+}}4
+; DEBUG: res @ dot.c:21
+; STRIPPED-NOT: res @ dot.c:21
+; BOTH:  [SP-4]{{.+}}Spill 8{{.+}}4
+define void @cleanup_result(ptr %0) #1 {
+  %2 = alloca ptr, align 8
+  store ptr %0, ptr %2, align 8
+  call void @llvm.dbg.declare(metadata ptr %2, metadata !47, metadata !DIExpression()), !dbg !51
+  ret void
+}
+
+; BOTH: # Stack Layout: do_work
+; BOTH:  Offset{{.+}}Align{{.+}}Size
+; BOTH:  [SP+12]{{.+}}8{{.+}}4
+; DEBUG: out @ dot.c:32
+; STRIPPED-NOT: out @ dot.c:32
+; BOTH:  [SP+8]{{.+}}4{{.+}}4
+; BOTH:  [SP+4]{{.+}}16{{.+}}4
+; DEBUG: A @ dot.c:32
+; STRIPPED-NOT: A @ dot.c:32
+; BOTH:  [SP-4]{{.+}}Spill 8{{.+}}4
+; BOTH:  [SP-12]{{.+}}8{{.+}}4
+; DEBUG: AB @ dot.c:38
+; STRIPPED-NOT: AB @ dot.c:38
+; BOTH:  [SP-16]{{.+}}4{{.+}}4
+; DEBUG: i @ dot.c:55
+; STRIPPED-NOT: i @ dot.c:55
+; BOTH:  [SP-20]{{.+}}8{{.+}}4
+; DEBUG: B @ dot.c:32
+; STRIPPED-NOT: B @ dot.c:32
+; BOTH:  [SP-24]{{.+}}4{{.+}}4
+; DEBUG: len @ dot.c:37
+; STRIPPED-NOT: len @ dot.c:37
+; BOTH:  [SP-28]{{.+}}4{{.+}}4
+; BOTH:  [SP-32]{{.+}}4{{.+}}4
+; DEBUG: sum @ dot.c:54
+; STRIPPED-NOT: sum @ dot.c:54
+define i32 @do_work(ptr %0, ptr %1, ptr %2) #1 {
+  %4 = alloca i32, align 4
+  %5 = alloca ptr, align 8
+  %6 = alloca ptr, align 8
+  %7 = alloca ptr, align 8
+  %8 = alloca i32, align 4
+  %9 = alloca ptr, align 8
+  %10 = alloca i32, align 4
+  %11 = alloca i32, align 4
+  store ptr %0, ptr %5, align 8
+  call void @llvm.dbg.declare(metadata ptr %5, metadata !52, metadata !DIExpression()), !dbg !56
+  call void @llvm.dbg.declare(metadata ptr %6, metadata !57, metadata !DIExpression()), !dbg !58
+  store ptr %2, ptr %7, align 8
+  call void @llvm.dbg.declare(metadata ptr %7, metadata !59, metadata !DIExpression()), !dbg !60
+  call void @llvm.dbg.declare(metadata ptr %8, metadata !61, metadata !DIExpression()), !dbg !63
+  call void @llvm.dbg.declare(metadata ptr %9, metadata !64, metadata !DIExpression()), !dbg !65
+  store ptr null, ptr %9, align 8
+  store ptr null, ptr null, align 8
+  store i32 0, ptr %9, align 8
+  %12 = load i32, ptr %8, align 4
+  store i32 %12, ptr null, a

[PATCH] D135488: [codegen] Display stack layouts in console

2022-11-15 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

In D135488#3928963 , @paulkirth wrote:

> In D135488#3928831 , @dblaikie 
> wrote:
>
>> Any chance we could squirrel the info away (I assume there's a reason we 
>> can't compute the info where the warn-stack-size LLVM feature is implemented 
>> in PrologEpilogInserter.cpp) somewhere, and emit it as part of the 
>> frame-larger-than/warn-stack-size diagnostic?
>>
>> (also, we do already have an opt remark for stack frame size in general (in 
>> PrologEpilogInserter, very close to where warn-stack-size is implemented), 
>> so it seems OK to use the remark infrastructure for a more detailed stack 
>> report - but ideally if the point is to make frame-larger-than better, it'd 
>> be good to include the info in that diagnostic)
>
> Originally, I had prototyped this to run when emitting `-Wframe-larger-than` 
> diagnostics, however being able to dump the stack layout easily seems 
> valuable on its own. The biggest advantage to delaying the pass is that we 
> can print better diagnostics after the `LiveDebugValues` pass has a chance to 
> run. The layout isn't affected, but we can print out more variable mappings 
> by delaying the printing pass.

Fair enough - could the warn-stack-size warning be moved to there, then, and 
then the information included in the warning? It could have both a warning and 
remark form, so folks could use the remark form when they just want all the 
reports or don't want the reports phrased as a problem, but as an informational 
message? (though this may or may not be worth it - I guess people can turn on 
the warning, lower the threshold, and specifically make this warning a 
non-error, which amounts to roughly the same thing as a remark)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135488

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


[PATCH] D135488: [codegen] Display stack layouts in console

2022-11-15 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth added a comment.

In D135488#3928831 , @dblaikie wrote:

> Any chance we could squirrel the info away (I assume there's a reason we 
> can't compute the info where the warn-stack-size LLVM feature is implemented 
> in PrologEpilogInserter.cpp) somewhere, and emit it as part of the 
> frame-larger-than/warn-stack-size diagnostic?
>
> (also, we do already have an opt remark for stack frame size in general (in 
> PrologEpilogInserter, very close to where warn-stack-size is implemented), so 
> it seems OK to use the remark infrastructure for a more detailed stack report 
> - but ideally if the point is to make frame-larger-than better, it'd be good 
> to include the info in that diagnostic)

Originally, I had prototyped this to run when emitting `-Wframe-larger-than` 
diagnostics, however being able to dump the stack layout easily seems valuable 
on its own. The biggest advantage to delaying the pass is that we can print 
better diagnostics after the `LiveDebugValues` pass has a chance to run. The 
layout isn't affected, but we can print out more variable mappings by delaying 
the printing pass.

In D135488#3928851 , @dblaikie wrote:

>> as a more general diagnostic output, like the other printing passes.
>
> As an aside: I don't think any "printing pass" is designed to be used beyond 
> LLVM compiler engineers - they're implementation details of the compiler, 
> even/much moreso than the optimization remarks infrastructure, which is 
> user-surfaced/clang-flag-supported/passed through suitable APIs (rather than 
> emitted raw to streams from the middle/backend). Optimization remarks are 
> plumbed through the diagnostic infrastructure, can be suppressed/enabled, 
> have file/line info at least some of the time, get all the clang diagnostic 
> formatting infrastructure (eg: current work to have a SARIF output mode would 
> be done up in clang, etc - and raw/direct output from LLVM wouldn't be 
> captured/handled by that work, for instance), colouring, etc.

Thanks for the clarification. Those are good points, so thank you for the 
detailed answer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135488

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


[PATCH] D137473: [vfs] Allow root paths relative to the directory of the vfsoverlay YAML file

2022-11-15 Thread Haowei Wu via Phabricator via cfe-commits
haowei marked 2 inline comments as done.
haowei added inline comments.



Comment at: llvm/include/llvm/Support/VirtualFileSystem.h:1010
 
+  std::error_code makeAbsolute(StringRef WorkingDir,
+   SmallVectorImpl &Path) const;

bnbarham wrote:
> Should be private IMO
Moved it to private section and added comments



Comment at: llvm/lib/Support/VirtualFileSystem.cpp:1369
   // append Path ourselves.
+  if (!sys::path::is_absolute(WorkingDir, sys::path::Style::posix) &&
+  !sys::path::is_absolute(WorkingDir,

bnbarham wrote:
> Did you find this was needed? It's already checked by the normal 
> `makeAbsolute` (which checks this already) and the only other caller is when 
> we're using the overlay directory path, which should always be absolute.
No, it is not needed for now. As the OverlayDir is always abs when it was set. 
The normal makeAbsolute function checks "Path" param but not checking the 
returned WorkDir, which is OK because the return value from 
getCurrentWorkingDirectory will be abs or empty.

It is more to be future proof if someone decide to use this function for other 
purpose and putting a non-abs path in WorkingDir field will causes unexpected 
behaviors.

I also need to exclude empty WorkingDir though because in unit tests, the 
WorkingDir is always empty.




Comment at: llvm/lib/Support/VirtualFileSystem.cpp:1913
+ RedirectingFileSystem::RootRelativeKind::OverlayDir) {
+SmallString<256> FullPath = FS->getOverlayFileDir();
+assert(!FullPath.empty() && "Overlay file directory must exist");

bnbarham wrote:
> This is unused now. Maybe we should just merge the `else if` and `else` 
> branches and just grab either `getOverlayFileDir` or 
> `getCurrentWorkingDirectory` depending on `RootRelative`. They should 
> otherwise be identical.
I merged these 2 else block.
I have to use sys::fs::make_absolute function for now as using FS's CWD will 
break a few tests. It is better to address these test in a separate patch.



Comment at: llvm/unittests/Support/VirtualFileSystemTest.cpp:1875
+
+  IntrusiveRefCntPtr FSOverlayRelative =
+  getFromYAMLString("{\n"

bnbarham wrote:
> Just override the previous `FS`/`S` IMO - that way we avoid the accidental 
> `FS->status` a few lines down 😅
Thanks for pointing that out 😅


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137473

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


[PATCH] D137583: [lldb] Fix simple template names and template params with scope qualifiers

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

Awesome!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137583

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


[PATCH] D137473: [vfs] Allow root paths relative to the directory of the vfsoverlay YAML file

2022-11-15 Thread Haowei Wu via Phabricator via cfe-commits
haowei updated this revision to Diff 475591.
haowei added a comment.

Address review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137473

Files:
  clang/test/VFS/Inputs/root-relative-overlay.yaml
  clang/test/VFS/relative-path.c
  llvm/include/llvm/Support/VirtualFileSystem.h
  llvm/lib/Support/VirtualFileSystem.cpp
  llvm/unittests/Support/VirtualFileSystemTest.cpp

Index: llvm/unittests/Support/VirtualFileSystemTest.cpp
===
--- llvm/unittests/Support/VirtualFileSystemTest.cpp
+++ llvm/unittests/Support/VirtualFileSystemTest.cpp
@@ -1452,18 +1452,20 @@
 
   std::unique_ptr
   getFromYAMLRawString(StringRef Content,
-   IntrusiveRefCntPtr ExternalFS) {
+   IntrusiveRefCntPtr ExternalFS,
+   StringRef YAMLFilePath = "") {
 std::unique_ptr Buffer = MemoryBuffer::getMemBuffer(Content);
-return getVFSFromYAML(std::move(Buffer), CountingDiagHandler, "", this,
-  ExternalFS);
+return getVFSFromYAML(std::move(Buffer), CountingDiagHandler, YAMLFilePath,
+  this, ExternalFS);
   }
 
   std::unique_ptr getFromYAMLString(
   StringRef Content,
-  IntrusiveRefCntPtr ExternalFS = new DummyFileSystem()) {
+  IntrusiveRefCntPtr ExternalFS = new DummyFileSystem(),
+  StringRef YAMLFilePath = "") {
 std::string VersionPlusContent("{\n  'version':0,\n");
 VersionPlusContent += Content.slice(Content.find('{') + 1, StringRef::npos);
-return getFromYAMLRawString(VersionPlusContent, ExternalFS);
+return getFromYAMLRawString(VersionPlusContent, ExternalFS, YAMLFilePath);
   }
 
   // This is intended as a "XFAIL" for windows hosts.
@@ -1849,6 +1851,44 @@
   EXPECT_EQ(0, NumDiagnostics);
 }
 
+TEST_F(VFSFromYAMLTest, RootRelativeTest) {
+  IntrusiveRefCntPtr Lower(new DummyFileSystem());
+  Lower->addDirectory("//root/foo/bar");
+  Lower->addRegularFile("//root/foo/bar/a");
+  IntrusiveRefCntPtr FS =
+  getFromYAMLString("{\n"
+"  'case-sensitive': false,\n"
+"  'root-relative': 'overlay-dir',\n"
+"  'roots': [\n"
+"{ 'name': 'b', 'type': 'file',\n"
+"  'external-contents': '//root/foo/bar/a'\n"
+"}\n"
+"  ]\n"
+"}",
+Lower, "//root/foo/bar/overlay");
+
+  ASSERT_NE(FS.get(), nullptr);
+  ErrorOr S = FS->status("//root/foo/bar/b");
+  ASSERT_FALSE(S.getError());
+  EXPECT_EQ("//root/foo/bar/a", S->getName());
+
+  FS = getFromYAMLString("{\n"
+ "  'case-sensitive': false,\n"
+ "  'overlay-relative': true,\n"
+ "  'root-relative': 'overlay-dir',\n"
+ "  'roots': [\n"
+ "{ 'name': 'b', 'type': 'file',\n"
+ "  'external-contents': 'a'\n"
+ "}\n"
+ "  ]\n"
+ "}",
+ Lower, "//root/foo/bar/overlay");
+  ASSERT_NE(FS.get(), nullptr);
+  S = FS->status("//root/foo/bar/b");
+  ASSERT_FALSE(S.getError());
+  EXPECT_EQ("//root/foo/bar/a", S->getName());
+}
+
 TEST_F(VFSFromYAMLTest, ReturnsInternalPathVFSHit) {
   IntrusiveRefCntPtr BaseFS(
   new vfs::InMemoryFileSystem);
Index: llvm/lib/Support/VirtualFileSystem.cpp
===
--- llvm/lib/Support/VirtualFileSystem.cpp
+++ llvm/lib/Support/VirtualFileSystem.cpp
@@ -1356,22 +1356,33 @@
   if (!WorkingDir)
 return WorkingDir.getError();
 
+  return makeAbsolute(WorkingDir.get(), Path);
+}
+
+std::error_code
+RedirectingFileSystem::makeAbsolute(StringRef WorkingDir,
+SmallVectorImpl &Path) const {
   // We can't use sys::fs::make_absolute because that assumes the path style
   // is native and there is no way to override that.  Since we know WorkingDir
   // is absolute, we can use it to determine which style we actually have and
   // append Path ourselves.
+  if (!WorkingDir.empty() &&
+  !sys::path::is_absolute(WorkingDir, sys::path::Style::posix) &&
+  !sys::path::is_absolute(WorkingDir,
+  sys::path::Style::windows_backslash)) {
+return std::error_code();
+  }
   sys::path::Style style = sys::path::Style::windows_backslash;
-  if (sys::path::is_absolute(WorkingDir.get(), sys::path::Style::posix)) {
+  if (sys::path::is_absolute(WorkingDir, sys::path::Style::posix)) {
 style = sys::path::Style::posix;
   } else {
 // Distinguish between windows_backslash and windows_slash; getExistingStyle
 // returns posix for a path with windows_slash.
-if (getExist

[PATCH] D137470: [Offloading] Initial support for registering offloading entries on COFF targets

2022-11-15 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

In D137470#3928828 , @mstorsjo wrote:

> Sorry, I'm not quite up to speed with exactly what is being done linker-wise 
> here - can you give a more detailed overview? Keep in mind that there's two 
> separate interfaces to lld for COFF; when used in mingw mode, it invokes the 
> `ld.lld` frontend, but with a `-m` option which directs lld to the mingw 
> frontend, which parses `ld.lld` style options and rewrites them to `lld-link` 
> style options and invokes that interface. And when Clang is operating in 
> msvc/clang-cl mode, `lld-link` is invoked (or called directly by the build 
> system).

Sure, there's a bit of documentation 
 for what's going on here, 
but I may need to update it a bit.

Basically, for offloading languages (CUDA, HIP, OpenMP, etc) we compile the 
source code twice, once for the host and once for the target device. We embed 
the device relocatable object inside the host so we follow a standard 
compilation pipeline. This `linker-wrapper` then fishes those relocatable 
objects out and performs the device-linking phase. The linked output is then 
put into a global along with some runtime calls to register the image and 
kernels. That new file gets passed to the wrapped linker job and we get a final 
executable.

My concern is that the linker wrapper keys off of certain arguments to the 
linker to do its job since it's invoked something like `clang-linker-wrapper 
`. I understand these are fundamentally different for `lld-link` 
so I was wondering if this approach in general would work there.




Comment at: clang/tools/clang-linker-wrapper/OffloadWrapper.cpp:145
+  // For COFF targets, sections with 8 or fewer characters containing a '$' 
will
+  // be merged into the same section at runtime. The order is determined by the
+  // alphebetical ordering of the text after the '$' character. Here we 
generate

mstorsjo wrote:
> jhuber6 wrote:
> > mstorsjo wrote:
> > > FWIW, this comment doesn't feel entirely accurate: Regardless of the 
> > > length of the section name, all sections with names of the form 
> > > `name$suffix` will get merged into the same section `name` (sorted by the 
> > > suffix). Then if `name` is 8 chars or less, the name is kept in the 
> > > section table (so that it can easily be looked up at runtime), while if 
> > > it is longer, the full name is kept in the string table (which is not 
> > > mapped at runtime).
> > > 
> > > Also as an extra side note; we added an exception into lld for 
> > > `.eh_frame` - this is 9 chars, but libunwind wants to locate the section 
> > > at runtime. So for that case, lld truncates it to `.eh_fram`. (This 
> > > behaviour is lld specific, to appease libunwind - binutils doesn't do 
> > > that, and libgcc locates that section differently.)
> > I see, I'm not that familiar with the inner workings of the COFF linking 
> > process. All that matters for this use-case is whether or not we can get a 
> > pointer to the array. In that case we shouldn't need to worry about the 
> > eight character limit right?
> If you locate the contents at runtime by using specific symbols that point to 
> the start and end of the data, then yes, you don't need to worry about 
> keeping it below the 8 char limit.
> 
> The 8 char limit is relevant if you enumerate and iterate over the sections 
> of a DLL/EXE at runtime, and try to locate the section dynamically that way.
Good to know, I may change the section names to be more verbose then, something 
like `cuda.entries$OE`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137470

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


[PATCH] D137205: [clang-tidy] Add performance-unnecessary-copy-on-last-use check

2022-11-15 Thread Fabian Keßler via Phabricator via cfe-commits
Febbe updated this revision to Diff 475589.
Febbe added a comment.

fixed lamda detection


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137205

Files:
  clang-tools-extra/clang-tidy/performance/CMakeLists.txt
  clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
  clang-tools-extra/clang-tidy/performance/UnnecessaryCopyOnLastUseCheck.cpp
  clang-tools-extra/clang-tidy/performance/UnnecessaryCopyOnLastUseCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/docs/clang-tidy/checks/performance/unnecessary-copy-on-last-use.rst
  
clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-copy-on-last-use.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-copy-on-last-use.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/performance/unnecessary-copy-on-last-use.cpp
@@ -0,0 +1,262 @@
+// RUN: %check_clang_tidy %s -std=c++17 performance-unnecessary-copy-on-last-use %t
+// RUN: %check_clang_tidy %s -std=c++11 performance-unnecessary-copy-on-last-use %t
+// CHECK-FIXES: #include 
+
+struct Movable {
+  Movable() = default;
+  Movable(Movable const &) = default;
+  Movable(Movable &&) = default;
+  Movable &operator=(Movable const &) = default;
+  Movable &operator=(Movable &&) = default;
+  ~Movable();
+
+  void memberUse() {}
+};
+
+struct Copyable {
+  Copyable() = default;
+  Copyable(Copyable const &) = default;
+  Copyable(Copyable &&) = default;
+  Copyable &operator=(Copyable const &) = default;
+  Copyable &operator=(Copyable &&) = default;
+  ~Copyable() = default; 
+
+  void memberUse() {}
+};
+// static_assert(!std::is_trivially_copyable_v, "Movable must not be trivially copyable");
+
+void valueReceiver(Movable Mov);
+void constRefReceiver(Movable const &Mov);
+
+void valueTester() {
+  Movable Mov{};
+  valueReceiver(Mov);
+  valueReceiver(Mov);
+  // CHECK-MESSAGES: [[@LINE-1]]:17: warning: Parameter 'Mov' is copied on last use, consider moving it instead. [performance-unnecessary-copy-on-last-use]
+  // CHECK-FIXES: valueReceiver(std::move(Mov));
+  Mov = Movable{};
+  valueReceiver(Mov);
+  // CHECK-MESSAGES: [[@LINE-1]]:17: warning: Parameter 'Mov' is copied on last use, consider moving it instead. [performance-unnecessary-copy-on-last-use]
+  // CHECK-FIXES: valueReceiver(std::move(Mov));
+}
+
+void testUsageInBranch(bool Splitter) {
+  Movable Mov{};
+
+  valueReceiver(Mov);
+  if(Splitter){
+Mov.memberUse();
+  } else {
+Mov = Movable{};
+  }
+  valueReceiver(Mov);
+  // CHECK-MESSAGES: [[@LINE-1]]:17: warning: Parameter 'Mov' is copied on last use, consider moving it instead. [performance-unnecessary-copy-on-last-use]
+  // CHECK-FIXES: valueReceiver(std::move(Mov));
+
+  if(Splitter){
+Mov = Movable{};
+  } else {
+Mov = Movable{};
+  }
+  valueReceiver(Mov);
+  Mov.memberUse();
+}
+
+void testExplicitCopy() {
+  Movable Mov{};
+  constRefReceiver(Movable{Mov});
+  // CHECK-MESSAGES: [[@LINE-1]]:28: warning: Parameter 'Mov' is copied on last use, consider moving it instead. [performance-unnecessary-copy-on-last-use]
+  // CHECK-FIXES: constRefReceiver(Movable{std::move(Mov)});
+}
+
+Movable testReturn() {
+  Movable Mov{};
+  return Mov; // no warning, copy elision
+}
+
+Movable testReturn2(Movable && Mov, bool F) {
+  return F? Mov: Movable{}; 
+  // CHECK-MESSAGES: [[@LINE-1]]:13: warning: Parameter 'Mov' is copied on last use, consider moving it instead. [performance-unnecessary-copy-on-last-use] 
+  // CHECK-FIXES: return F? std::move(Mov): Movable{};
+}
+
+void rValReferenceTester(Movable&& Mov) {
+  valueReceiver(Mov);
+  valueReceiver(Mov);
+  // CHECK-MESSAGES: [[@LINE-1]]:17: warning: Parameter 'Mov' is copied on last use, consider moving it instead. [performance-unnecessary-copy-on-last-use]
+  // CHECK-FIXES: valueReceiver(std::move(Mov));
+  Mov = Movable{};
+  valueReceiver(Mov);
+  // CHECK-MESSAGES: [[@LINE-1]]:17: warning: Parameter 'Mov' is copied on last use, consider moving it instead. [performance-unnecessary-copy-on-last-use]
+  // CHECK-FIXES: valueReceiver(std::move(Mov));
+}
+
+void referenceTester(Movable& Mov) {
+  valueReceiver(Mov);
+  valueReceiver(Mov);
+  Mov = Movable{};
+  valueReceiver(Mov);
+}
+
+void pointerTester(Movable* Mov) {
+  valueReceiver(*Mov);
+  valueReceiver(*Mov);
+  *Mov = Movable{};
+  valueReceiver(*Mov);
+}
+
+template 
+struct RemoveRef{
+  using type = T;
+};
+
+template 
+struct RemoveRef{
+  using type = T;
+};
+
+template 
+struct RemoveRef{
+  using type = T;
+};
+
+template
+using RemoveRefT = typename RemoveRef::type;
+
+template 
+void initSomething(Movable&& Mov) {
+  valueReceiver(Mov);
+  valueReceiver(Mov); // no warning: Todo(bug): Is this a bug? Fix or explain.
+  Mov = RemoveRefT{};
+  valueReceiver(Mov);
+  // CHECK-MESSAGE

[PATCH] D135488: [codegen] Display stack layouts in console

2022-11-15 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

> as a more general diagnostic output, like the other printing passes.

As an aside: I don't think any "printing pass" is designed to be used beyond 
LLVM compiler engineers - they're implementation details of the compiler, 
even/much moreso than the optimization remarks infrastructure, which is 
user-surfaced/clang-flag-supported/passed through suitable APIs (rather than 
emitted raw to streams from the middle/backend). Optimization remarks are 
plumbed through the diagnostic infrastructure, can be suppressed/enabled, have 
file/line info at least some of the time, get all the clang diagnostic 
formatting infrastructure (eg: current work to have a SARIF output mode would 
be done up in clang, etc - and raw/direct output from LLVM wouldn't be 
captured/handled by that work, for instance), colouring, etc.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135488

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


[clang] 063a43b - [ObjC] Fix an assertion failure in EvaluateLValue

2022-11-15 Thread Akira Hatanaka via cfe-commits

Author: Akira Hatanaka
Date: 2022-11-15T14:41:28-08:00
New Revision: 063a43b4fd9f869d57c20145302eb41068bfb54e

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

LOG: [ObjC] Fix an assertion failure in EvaluateLValue

Look through parentheses when determining whether the expression is a
@selector expression.

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/test/SemaObjCXX/sel-address.mm

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 34e75723b3f30..e17df5da5cb2d 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8228,7 +8228,7 @@ static bool EvaluateLValue(const Expr *E, LValue &Result, 
EvalInfo &Info,
bool InvalidBaseOK) {
   assert(!E->isValueDependent());
   assert(E->isGLValue() || E->getType()->isFunctionType() ||
- E->getType()->isVoidType() || isa(E));
+ E->getType()->isVoidType() || 
isa(E->IgnoreParens()));
   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
 }
 

diff  --git a/clang/test/SemaObjCXX/sel-address.mm 
b/clang/test/SemaObjCXX/sel-address.mm
index a1209abd4e687..e5661af341691 100644
--- a/clang/test/SemaObjCXX/sel-address.mm
+++ b/clang/test/SemaObjCXX/sel-address.mm
@@ -15,5 +15,6 @@ void h() {
 
   // Shouldn't crash.
   g(&@selector(foo));
+  g(&(@selector(foo)));
 }
 



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


[PATCH] D135488: [codegen] Display stack layouts in console

2022-11-15 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

Any chance we could squirrel the info away (I assume there's a reason we can't 
compute the info where the warn-stack-size LLVM feature is implemented in 
PrologEpilogInserter.cpp) somewhere, and emit it as part of the 
frame-larger-than/warn-stack-size diagnostic?

(also, we do already have an opt remark for stack frame size in general (in 
PrologEpilogInserter, very close to where warn-stack-size is implemented), so 
it seems OK to use the remark infrastructure for a more detailed stack report - 
but ideally if the point is to make frame-larger-than better, it'd be good to 
include the info in that diagnostic)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135488

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


[PATCH] D137470: [Offloading] Initial support for registering offloading entries on COFF targets

2022-11-15 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

In D137470#3928731 , @jhuber6 wrote:

> Another significant portion of getting this workflow to work for Windows / 
> COFF is parsing the linker arguments. I should be able to look at `lld-link` 
> and add necessarily aliases to what `ld.lld` takes I assume? E.g. we use 
> values like `-o` and `-L` in the linker wrapper to set the output and find 
> libraries.

Sorry, I'm not quite up to speed with exactly what is being done linker-wise 
here - can you give a more detailed overview? Keep in mind that there's two 
separate interfaces to lld for COFF; when used in mingw mode, it invokes the 
`ld.lld` frontend, but with a `-m` option which directs lld to the mingw 
frontend, which parses `ld.lld` style options and rewrites them to `lld-link` 
style options and invokes that interface. And when Clang is operating in 
msvc/clang-cl mode, `lld-link` is invoked (or called directly by the build 
system).




Comment at: clang/tools/clang-linker-wrapper/OffloadWrapper.cpp:145
+  // For COFF targets, sections with 8 or fewer characters containing a '$' 
will
+  // be merged into the same section at runtime. The order is determined by the
+  // alphebetical ordering of the text after the '$' character. Here we 
generate

jhuber6 wrote:
> mstorsjo wrote:
> > FWIW, this comment doesn't feel entirely accurate: Regardless of the length 
> > of the section name, all sections with names of the form `name$suffix` will 
> > get merged into the same section `name` (sorted by the suffix). Then if 
> > `name` is 8 chars or less, the name is kept in the section table (so that 
> > it can easily be looked up at runtime), while if it is longer, the full 
> > name is kept in the string table (which is not mapped at runtime).
> > 
> > Also as an extra side note; we added an exception into lld for `.eh_frame` 
> > - this is 9 chars, but libunwind wants to locate the section at runtime. So 
> > for that case, lld truncates it to `.eh_fram`. (This behaviour is lld 
> > specific, to appease libunwind - binutils doesn't do that, and libgcc 
> > locates that section differently.)
> I see, I'm not that familiar with the inner workings of the COFF linking 
> process. All that matters for this use-case is whether or not we can get a 
> pointer to the array. In that case we shouldn't need to worry about the eight 
> character limit right?
If you locate the contents at runtime by using specific symbols that point to 
the start and end of the data, then yes, you don't need to worry about keeping 
it below the 8 char limit.

The 8 char limit is relevant if you enumerate and iterate over the sections of 
a DLL/EXE at runtime, and try to locate the section dynamically that way.



Comment at: clang/tools/clang-linker-wrapper/OffloadWrapper.cpp:337
-  M, DummyInit->getType(), true, GlobalVariable::ExternalLinkage, 
DummyInit,
-  IsHIP ? "__dummy.hip_offloading.entry" : 
"__dummy.cuda_offloading.entry");
-  DummyEntry->setVisibility(GlobalValue::HiddenVisibility);

jhuber6 wrote:
> mstorsjo wrote:
> > I don't quite see where the corresponding GlobalVariable for this case is 
> > created after the refactoring?
> The CUDA / HIP cases did this separately. This patch merged it into a common 
> method `getELFEntriesArray`. Functionally this just changed the order in the 
> output slightly. The `dummy` variable is only necessary for the ELF linkers 
> to generate the begin / end section. For COFF we make the `$a` and `$z` 
> variables which perform a similar role.
Ah, now I see - this is the second half of what's being merged into the 
cuda/hip call below in createRegisterGlobalsFunction.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137470

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


[PATCH] D137570: [Clang][Sema] Refactor category declaration under CheckForIncompatibleAttributes. NFC

2022-11-15 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6dee23919a36: [Clang][Sema] Refactor category declaration 
under… (authored by eopXD).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137570

Files:
  clang/lib/Sema/SemaStmtAttr.cpp


Index: clang/lib/Sema/SemaStmtAttr.cpp
===
--- clang/lib/Sema/SemaStmtAttr.cpp
+++ clang/lib/Sema/SemaStmtAttr.cpp
@@ -306,21 +306,33 @@
   if (!DiagnoseMutualExclusions(S, Attrs))
 return;
 
-  // There are 6 categories of loop hints attributes: vectorize, interleave,
-  // unroll, unroll_and_jam, pipeline and distribute. Except for distribute 
they
-  // come in two variants: a state form and a numeric form.  The state form
-  // selectively defaults/enables/disables the transformation for the loop
-  // (for unroll, default indicates full unrolling rather than enabling the
-  // transformation). The numeric form provides an integer hint (for
-  // example, unroll count) to the transformer. The following array accumulates
-  // the hints encountered while iterating through the attributes to check for
-  // compatibility.
+  enum CategoryType {
+// For the following categories, they come in two variants: a state form 
and
+// a numeric form. The state form may be one of default, enable, and
+// disable. The numeric form provides an integer hint (for example, unroll
+// count) to the transformer.
+Vectorize,
+Interleave,
+UnrollAndJam,
+Pipeline,
+// For unroll, default indicates full unrolling rather than enabling the
+// transformation.
+Unroll,
+// The loop distribution transformation only has a state form that is
+// exposed by #pragma clang loop distribute (enable | disable).
+Distribute,
+// The vector predication only has a state form that is exposed by
+// #pragma clang loop vectorize_predicate (enable | disable).
+VectorizePredicate,
+// This serves as a indicator to how many category are listed in this enum.
+NumberOfCategories
+  };
+  // The following array accumulates the hints encountered while iterating
+  // through the attributes to check for compatibility.
   struct {
 const LoopHintAttr *StateAttr;
 const LoopHintAttr *NumericAttr;
-  } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
-   {nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
-   {nullptr, nullptr}};
+  } HintAttrs[CategoryType::NumberOfCategories] = {};
 
   for (const auto *I : Attrs) {
 const LoopHintAttr *LH = dyn_cast(I);
@@ -329,16 +341,8 @@
 if (!LH)
   continue;
 
+CategoryType Category = CategoryType::NumberOfCategories;
 LoopHintAttr::OptionType Option = LH->getOption();
-enum {
-  Vectorize,
-  Interleave,
-  Unroll,
-  UnrollAndJam,
-  Distribute,
-  Pipeline,
-  VectorizePredicate
-} Category;
 switch (Option) {
 case LoopHintAttr::Vectorize:
 case LoopHintAttr::VectorizeWidth:
@@ -369,7 +373,7 @@
   break;
 };
 
-assert(Category < sizeof(HintAttrs) / sizeof(HintAttrs[0]));
+assert(Category != NumberOfCategories && "Unhandled loop hint option");
 auto &CategoryState = HintAttrs[Category];
 const LoopHintAttr *PrevAttr;
 if (Option == LoopHintAttr::Vectorize ||


Index: clang/lib/Sema/SemaStmtAttr.cpp
===
--- clang/lib/Sema/SemaStmtAttr.cpp
+++ clang/lib/Sema/SemaStmtAttr.cpp
@@ -306,21 +306,33 @@
   if (!DiagnoseMutualExclusions(S, Attrs))
 return;
 
-  // There are 6 categories of loop hints attributes: vectorize, interleave,
-  // unroll, unroll_and_jam, pipeline and distribute. Except for distribute they
-  // come in two variants: a state form and a numeric form.  The state form
-  // selectively defaults/enables/disables the transformation for the loop
-  // (for unroll, default indicates full unrolling rather than enabling the
-  // transformation). The numeric form provides an integer hint (for
-  // example, unroll count) to the transformer. The following array accumulates
-  // the hints encountered while iterating through the attributes to check for
-  // compatibility.
+  enum CategoryType {
+// For the following categories, they come in two variants: a state form and
+// a numeric form. The state form may be one of default, enable, and
+// disable. The numeric form provides an integer hint (for example, unroll
+// count) to the transformer.
+Vectorize,
+Interleave,
+UnrollAndJam,
+Pipeline,
+// For unroll, default indicates full unrolling rather than enabling the
+// transformation.
+Unroll,
+// The loop distribution transformation only has a state form that is
+// exposed by #pragma clang loop distribute (enable | d

[clang] 6dee239 - [Clang][Sema] Refactor category declaration under CheckForIncompatibleAttributes. NFC

2022-11-15 Thread via cfe-commits

Author: eopXD
Date: 2022-11-15T14:37:27-08:00
New Revision: 6dee23919a36a30f3df7e9b20fba8b9edf65340c

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

LOG: [Clang][Sema] Refactor category declaration under 
CheckForIncompatibleAttributes. NFC

This change would allow extension of new categories be aware of adding
more code here.

This patch also updates the comments, which was originally missing the
vector predicate.

Reviewed By: mikerice

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

Added: 


Modified: 
clang/lib/Sema/SemaStmtAttr.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaStmtAttr.cpp b/clang/lib/Sema/SemaStmtAttr.cpp
index 7a35d715eba9..9ec8fe21d0a2 100644
--- a/clang/lib/Sema/SemaStmtAttr.cpp
+++ b/clang/lib/Sema/SemaStmtAttr.cpp
@@ -306,21 +306,33 @@ CheckForIncompatibleAttributes(Sema &S,
   if (!DiagnoseMutualExclusions(S, Attrs))
 return;
 
-  // There are 6 categories of loop hints attributes: vectorize, interleave,
-  // unroll, unroll_and_jam, pipeline and distribute. Except for distribute 
they
-  // come in two variants: a state form and a numeric form.  The state form
-  // selectively defaults/enables/disables the transformation for the loop
-  // (for unroll, default indicates full unrolling rather than enabling the
-  // transformation). The numeric form provides an integer hint (for
-  // example, unroll count) to the transformer. The following array accumulates
-  // the hints encountered while iterating through the attributes to check for
-  // compatibility.
+  enum CategoryType {
+// For the following categories, they come in two variants: a state form 
and
+// a numeric form. The state form may be one of default, enable, and
+// disable. The numeric form provides an integer hint (for example, unroll
+// count) to the transformer.
+Vectorize,
+Interleave,
+UnrollAndJam,
+Pipeline,
+// For unroll, default indicates full unrolling rather than enabling the
+// transformation.
+Unroll,
+// The loop distribution transformation only has a state form that is
+// exposed by #pragma clang loop distribute (enable | disable).
+Distribute,
+// The vector predication only has a state form that is exposed by
+// #pragma clang loop vectorize_predicate (enable | disable).
+VectorizePredicate,
+// This serves as a indicator to how many category are listed in this enum.
+NumberOfCategories
+  };
+  // The following array accumulates the hints encountered while iterating
+  // through the attributes to check for compatibility.
   struct {
 const LoopHintAttr *StateAttr;
 const LoopHintAttr *NumericAttr;
-  } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
-   {nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
-   {nullptr, nullptr}};
+  } HintAttrs[CategoryType::NumberOfCategories] = {};
 
   for (const auto *I : Attrs) {
 const LoopHintAttr *LH = dyn_cast(I);
@@ -329,16 +341,8 @@ CheckForIncompatibleAttributes(Sema &S,
 if (!LH)
   continue;
 
+CategoryType Category = CategoryType::NumberOfCategories;
 LoopHintAttr::OptionType Option = LH->getOption();
-enum {
-  Vectorize,
-  Interleave,
-  Unroll,
-  UnrollAndJam,
-  Distribute,
-  Pipeline,
-  VectorizePredicate
-} Category;
 switch (Option) {
 case LoopHintAttr::Vectorize:
 case LoopHintAttr::VectorizeWidth:
@@ -369,7 +373,7 @@ CheckForIncompatibleAttributes(Sema &S,
   break;
 };
 
-assert(Category < sizeof(HintAttrs) / sizeof(HintAttrs[0]));
+assert(Category != NumberOfCategories && "Unhandled loop hint option");
 auto &CategoryState = HintAttrs[Category];
 const LoopHintAttr *PrevAttr;
 if (Option == LoopHintAttr::Vectorize ||



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


[PATCH] D137116: [AggressiveInstCombine] Remove legacy PM pass

2022-11-15 Thread Arthur Eubanks via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG70dc3b811e49: [AggressiveInstCombine] Remove legacy PM pass 
(authored by aeubanks).

Changed prior to commit:
  https://reviews.llvm.org/D137116?vs=472143&id=475583#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137116

Files:
  clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
  llvm/bindings/python/llvm/core.py
  llvm/include/llvm-c/Initialization.h
  llvm/include/llvm-c/Transforms/AggressiveInstCombine.h
  llvm/include/llvm/InitializePasses.h
  llvm/include/llvm/LinkAllPasses.h
  llvm/include/llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h
  llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp
  llvm/lib/Transforms/IPO/PassManagerBuilder.cpp
  llvm/test/Transforms/PhaseOrdering/X86/pr52078.ll
  llvm/test/Transforms/PhaseOrdering/X86/pr52253.ll
  llvm/tools/bugpoint/bugpoint.cpp
  llvm/tools/llvm-c-test/include-all.c
  llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp
  llvm/tools/opt/opt.cpp

Index: llvm/tools/opt/opt.cpp
===
--- llvm/tools/opt/opt.cpp
+++ llvm/tools/opt/opt.cpp
@@ -465,7 +465,6 @@
   initializeAnalysis(Registry);
   initializeTransformUtils(Registry);
   initializeInstCombine(Registry);
-  initializeAggressiveInstCombine(Registry);
   initializeTarget(Registry);
   // For codegen passes, only passes that do IR to IR transformation are
   // supported.
Index: llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp
===
--- llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp
+++ llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp
@@ -197,7 +197,6 @@
   initializeAnalysis(Registry);
   initializeTransformUtils(Registry);
   initializeInstCombine(Registry);
-  initializeAggressiveInstCombine(Registry);
   initializeTarget(Registry);
 
   // Parse input options
Index: llvm/tools/llvm-c-test/include-all.c
===
--- llvm/tools/llvm-c-test/include-all.c
+++ llvm/tools/llvm-c-test/include-all.c
@@ -35,7 +35,6 @@
 #include "llvm-c/Support.h"
 #include "llvm-c/Target.h"
 #include "llvm-c/TargetMachine.h"
-#include "llvm-c/Transforms/AggressiveInstCombine.h"
 #include "llvm-c/Transforms/InstCombine.h"
 #include "llvm-c/Transforms/IPO.h"
 #include "llvm-c/Transforms/PassManagerBuilder.h"
Index: llvm/tools/bugpoint/bugpoint.cpp
===
--- llvm/tools/bugpoint/bugpoint.cpp
+++ llvm/tools/bugpoint/bugpoint.cpp
@@ -148,7 +148,6 @@
   initializeAnalysis(Registry);
   initializeTransformUtils(Registry);
   initializeInstCombine(Registry);
-  initializeAggressiveInstCombine(Registry);
   initializeTarget(Registry);
 
   if (std::getenv("bar") == (char*) -1) {
Index: llvm/test/Transforms/PhaseOrdering/X86/pr52253.ll
===
--- llvm/test/Transforms/PhaseOrdering/X86/pr52253.ll
+++ llvm/test/Transforms/PhaseOrdering/X86/pr52253.ll
@@ -1,7 +1,7 @@
 ; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
 ; RUN: opt -O3 -S < %s | FileCheck %s
-; RUN: opt -instcombine -sccp -bdce -S < %s | FileCheck %s
-; RUN: opt -aggressive-instcombine -instcombine -sccp -bdce -S < %s | FileCheck %s
+; RUN: opt -passes=instcombine,sccp,bdce -S < %s | FileCheck %s
+; RUN: opt -passes=aggressive-instcombine,instcombine,sccp,bdce -S < %s | FileCheck %s
 
 target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"
Index: llvm/test/Transforms/PhaseOrdering/X86/pr52078.ll
===
--- llvm/test/Transforms/PhaseOrdering/X86/pr52078.ll
+++ llvm/test/Transforms/PhaseOrdering/X86/pr52078.ll
@@ -1,7 +1,7 @@
 ; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
 ; RUN: opt -O2 -S < %s | FileCheck %s
-; RUN: opt -instcombine -S < %s | FileCheck %s --check-prefix=IC
-; RUN: opt -aggressive-instcombine -instcombine -S < %s | FileCheck %s --check-prefix=AIC_AND_IC
+; RUN: opt -passes=instcombine -S < %s | FileCheck %s --check-prefix=IC
+; RUN: opt -passes=aggressive-instcombine,instcombine -S < %s | FileCheck %s --check-prefix=AIC_AND_IC
 
 target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"
Index: llvm/lib/Transforms/IPO/PassManagerBuilder.cpp
===
--- llvm/lib/Transforms/IPO/PassManagerBuilder.cpp
+++ llvm/lib/Transforms/IPO/PassManagerBuilder.cpp
@@ -174,8 +174,6 @@
   createCFGSimplificationPass(SimplifyCFGOptions().convertSwitchRangeToICmp(
   tr

[clang] 70dc3b8 - [AggressiveInstCombine] Remove legacy PM pass

2022-11-15 Thread Arthur Eubanks via cfe-commits

Author: Arthur Eubanks
Date: 2022-11-15T14:35:15-08:00
New Revision: 70dc3b811e4926fa2c88bd3b53b29c46fcba1a90

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

LOG: [AggressiveInstCombine] Remove legacy PM pass

As part of legacy PM optimization pipeline removal.

This shouldn't be used in codegen pipelines so it should be ok to remove.

Reviewed By: asbirlea

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

Added: 


Modified: 
clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
llvm/bindings/python/llvm/core.py
llvm/include/llvm-c/Initialization.h
llvm/include/llvm/InitializePasses.h
llvm/include/llvm/LinkAllPasses.h
llvm/include/llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h
llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp
llvm/lib/Transforms/IPO/PassManagerBuilder.cpp
llvm/test/Transforms/PhaseOrdering/X86/pr52078.ll
llvm/test/Transforms/PhaseOrdering/X86/pr52253.ll
llvm/tools/bugpoint/bugpoint.cpp
llvm/tools/llvm-c-test/include-all.c
llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp
llvm/tools/opt/opt.cpp

Removed: 
llvm/include/llvm-c/Transforms/AggressiveInstCombine.h



diff  --git a/clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp 
b/clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
index 235ff150523e2..94f3b937d83fc 100644
--- a/clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
+++ b/clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
@@ -48,7 +48,6 @@ extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) {
   initializeAnalysis(Registry);
   initializeTransformUtils(Registry);
   initializeInstCombine(Registry);
-  initializeAggressiveInstCombine(Registry);
   initializeTarget(Registry);
 
   CLArgs.push_back("-O2");

diff  --git a/llvm/bindings/python/llvm/core.py 
b/llvm/bindings/python/llvm/core.py
index 4e99aac91182b..a0f8cf56c9637 100644
--- a/llvm/bindings/python/llvm/core.py
+++ b/llvm/bindings/python/llvm/core.py
@@ -464,9 +464,6 @@ def register_library(library):
 library.LLVMInitializeInstCombine.argtypes = [PassRegistry]
 library.LLVMInitializeInstCombine.restype = None
 
-library.LLVMInitializeAggressiveInstCombiner.argtypes = [PassRegistry]
-library.LLVMInitializeAggressiveInstCombiner.restype = None
-
 library.LLVMInitializeIPO.argtypes = [PassRegistry]
 library.LLVMInitializeIPO.restype = None
 

diff  --git a/llvm/include/llvm-c/Initialization.h 
b/llvm/include/llvm-c/Initialization.h
index c7770d911969a..a24fc9598967a 100644
--- a/llvm/include/llvm-c/Initialization.h
+++ b/llvm/include/llvm-c/Initialization.h
@@ -35,7 +35,6 @@ void LLVMInitializeTransformUtils(LLVMPassRegistryRef R);
 void LLVMInitializeScalarOpts(LLVMPassRegistryRef R);
 void LLVMInitializeVectorization(LLVMPassRegistryRef R);
 void LLVMInitializeInstCombine(LLVMPassRegistryRef R);
-void LLVMInitializeAggressiveInstCombiner(LLVMPassRegistryRef R);
 void LLVMInitializeIPO(LLVMPassRegistryRef R);
 void LLVMInitializeAnalysis(LLVMPassRegistryRef R);
 void LLVMInitializeIPA(LLVMPassRegistryRef R);

diff  --git a/llvm/include/llvm-c/Transforms/AggressiveInstCombine.h 
b/llvm/include/llvm-c/Transforms/AggressiveInstCombine.h
deleted file mode 100644
index db061a7ad1fc0..0
--- a/llvm/include/llvm-c/Transforms/AggressiveInstCombine.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*===-- AggressiveInstCombine.h -*- 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 header declares the C interface to libLLVMAggressiveInstCombine.a,
*|
-|* which combines instructions to form fewer, simple IR instructions. 
*|
-|*
*|
-\*===--===*/
-
-#ifndef LLVM_C_TRANSFORMS_AGGRESSIVEINSTCOMBINE_H
-#define LLVM_C_TRANSFORMS_AGGRESSIVEINSTCOMBINE_H
-
-#include "llvm-c/ExternC.h"
-#include "llvm-c/Types.h"
-
-LLVM_C_EXTERN_C_BEGIN
-
-/**
- * @defgroup LLVMCTransformsAggressiveInstCombine Aggressive Instruction 
Combi

[clang] dcfb250 - [clang][deps] Remove checks that were just for exhaustiveness

2022-11-15 Thread Ben Langmuir via cfe-commits

Author: Ben Langmuir
Date: 2022-11-15T14:22:23-08:00
New Revision: dcfb25078c2629450b393e696b9760721a9f

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

LOG: [clang][deps] Remove checks that were just for exhaustiveness

Instead of checking all the paths, just ensure the one we care about is
correct. On a particular platform one of the paths seems to have been
more canonical than we were expecting, which is fine.

Added: 


Modified: 
clang/test/ClangScanDeps/modules-symlink-dir-from-module.c

Removed: 




diff  --git a/clang/test/ClangScanDeps/modules-symlink-dir-from-module.c 
b/clang/test/ClangScanDeps/modules-symlink-dir-from-module.c
index 5dde7708c2538..d1f7479adc6f9 100644
--- a/clang/test/ClangScanDeps/modules-symlink-dir-from-module.c
+++ b/clang/test/ClangScanDeps/modules-symlink-dir-from-module.c
@@ -19,38 +19,11 @@
 // CHECK: "modules": [
 // CHECK:   {
 // CHECK: "command-line": [
+// CHECK-NOT: ]
 // CHECK:   "-fmodule-map-file=[[PREFIX]]/include/module/module.modulemap"
 // CHECK: ]
 // CHECK: "name": "Foo"
 // CHECK:   }
-// CHECK:   {
-// CHECK: "command-line": [
-// FIXME: canonicalize this path
-// CHECK:   
"-fmodule-map-file=[[PREFIX]]/include/symlink-to-module/module.modulemap"
-// CHECK: ]
-// CHECK: "name": "Foo_Private"
-// CHECK:   }
-// CHECK:   {
-// CHECK: "command-line": [
-// CHECK:   "[[PREFIX]]/include/module/module.modulemap"
-// CHECK: ]
-// CHECK: "name": "Mod"
-// CHECK:   }
-// CHECK:   {
-// CHECK: "command-line": [
-// FIXME: canonicalize this path
-// CHECK:   
"-fmodule-map-file=[[PREFIX]]/include/symlink-to-module/module.modulemap"
-// CHECK: ]
-// CHECK: "name": "Other"
-// CHECK:   }
-// CHECK:   {
-// CHECK: "command-line": [
-// FIXME: canonicalize this path
-// CHECK:   
"-fmodule-map-file=[[PREFIX]]/include/symlink-to-module/module.modulemap"
-// CHECK: ]
-// CHECK: "name": "Test"
-// CHECK:   }
-// CHECK: ]
 
 //--- cdb.json.in
 [{



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


[PATCH] D135488: [codegen] Display stack layouts in console

2022-11-15 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth added a comment.

Thanks for the feedback! I have a few questions I'm hoping you can answer.

In D135488#3928559 , @arsenm wrote:

> I don't think we should be pointing users to -mllvm flags. Plus, I don't 
> really think random dbgs() printing is going to interact correctly with other 
> diagnostics

I modeled this pass off of the MachineFunctionPrinterPass, does that mean it it 
should also use a different stream? This seems to be a fairly common pattern, 
so should we be filing bugs and tracking work in this area?

In D135488#3928580 , @arsenm wrote:

> I'd be a bit more comfortable routing this through the backend remarks 
> infrastructure, although it's a lot bigger than everything else currently 
> reported there

I'm not sure that this diagnostic belongs in optimization remarks, though. It 
isn't describing any of the decision making that went into the stack layout, 
which is what I think most remarks typically describe. I'm basing that on 
https://clang.llvm.org/docs/UsersManual.html#options-to-emit-optimization-reports.
 Is my interpretation of that too narrow?

Also, is there something special about the remarks output that makes it better? 
Is the setup/initialization more careful than for the other streams? I'd like 
to understand the trade-off a bit better. Our documentation makes it seem as 
though its geared towards compiler engineers, where I view this as a more 
general diagnostic output, like the other printing passes.




Comment at: llvm/lib/CodeGen/StackFramePrinterPass.cpp:120-122
+  // This is a dead slot, so skip it
+  if (Size == ~0ULL)
+continue;

arsenm wrote:
> Check MFI.isDead instead?
Oh, good suggestion. That check bothered me, but I missed that API. I'll update 
this patch to reflect your suggestion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135488

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


[PATCH] D137851: [OPENMP]Initial support for at clause

2022-11-15 Thread Jennifer Yu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG628fdc3f57ad: [OPENMP]Initial support for at clause 
(authored by jyu2).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137851

Files:
  clang/include/clang/AST/OpenMPClause.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/include/clang/Basic/OpenMPKinds.def
  clang/include/clang/Basic/OpenMPKinds.h
  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/CodeGen/CGStmtOpenMP.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/error_ast_print.cpp
  clang/test/OpenMP/error_message.cpp
  clang/tools/libclang/CIndex.cpp
  flang/lib/Semantics/check-omp-structure.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td

Index: llvm/include/llvm/Frontend/OpenMP/OMP.td
===
--- llvm/include/llvm/Frontend/OpenMP/OMP.td
+++ llvm/include/llvm/Frontend/OpenMP/OMP.td
@@ -301,6 +301,9 @@
   let clangClass = "OMPAtomicDefaultMemOrderClause";
   let flangClass = "OmpAtomicDefaultMemOrderClause";
 }
+def OMPC_At : Clause<"at"> {
+  let clangClass = "OMPAtClause";
+}
 def OMPC_Allocate : Clause<"allocate"> {
   let clangClass = "OMPAllocateClause";
   let flangClass = "OmpAllocateClause";
@@ -527,7 +530,11 @@
 }
 def OMP_TaskYield : Directive<"taskyield"> {}
 def OMP_Barrier : Directive<"barrier"> {}
-def OMP_Error : Directive<"error"> {}
+def OMP_Error : Directive<"error"> {
+  let allowedClauses = [
+VersionedClause
+  ];
+}
 def OMP_TaskWait : Directive<"taskwait"> {
   let allowedClauses = [
 VersionedClause
Index: flang/lib/Semantics/check-omp-structure.cpp
===
--- flang/lib/Semantics/check-omp-structure.cpp
+++ flang/lib/Semantics/check-omp-structure.cpp
@@ -1868,6 +1868,7 @@
 CHECK_SIMPLE_CLAUSE(Use, OMPC_use)
 CHECK_SIMPLE_CLAUSE(Novariants, OMPC_novariants)
 CHECK_SIMPLE_CLAUSE(Nocontext, OMPC_nocontext)
+CHECK_SIMPLE_CLAUSE(At, OMPC_at)
 CHECK_SIMPLE_CLAUSE(Filter, OMPC_filter)
 CHECK_SIMPLE_CLAUSE(When, OMPC_when)
 CHECK_SIMPLE_CLAUSE(AdjustArgs, OMPC_adjust_args)
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -2443,6 +2443,8 @@
 void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
 const OMPAtomicDefaultMemOrderClause *) {}
 
+void OMPClauseEnqueue::VisitOMPAtClause(const OMPAtClause *) {}
+
 void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
   Visitor->AddStmt(C->getDevice());
 }
Index: clang/test/OpenMP/error_message.cpp
===
--- clang/test/OpenMP/error_message.cpp
+++ clang/test/OpenMP/error_message.cpp
@@ -7,19 +7,19 @@
   if (argc)
 #pragma omp error // expected-error {{'#pragma omp error' cannot be an immediate substatement}}
 if (argc) {
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
 }
   while (argc)
 #pragma omp error // expected-error {{'#pragma omp error' cannot be an immediate substatement}}
 while (argc) {
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
 }
   do
 #pragma omp error // expected-error {{'#pragma omp error' cannot be an immediate substatement}}
 while (argc)
   ;
   do {
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
   } while (argc);
   switch (argc)
 #pragma omp error // expected-error {{'#pragma omp error' cannot be an immediate substatement}}
@@ -28,47 +28,75 @@
 #pragma omp error // expected-error {{'#pragma omp error' cannot be an immediate substatement}}
   switch (argc)
   case 1: {
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
   }
   switch (argc) {
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
   case 1:
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
 break;
   default: {
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
   } break;
   }
   for (;;)
 #pragma omp error // expected-error {{'#pragma omp error' cannot be an immediate substatement}}
 for (;;) {
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
 }
 label:
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
 label1 : {
-#pragma omp error
+#pragma omp error // expected-error {{ERROR}}
 }
 if (1)
   label2:
 #pragma omp error // expected-error {{'#pragma omp error' cannot be an immediate substatement}}
 
+// expected-error@+1 {{ERROR}}
+#pragma omp error at() // expe

[PATCH] D137473: [vfs] Allow root paths relative to the directory of the vfsoverlay YAML file

2022-11-15 Thread Haowei Wu via Phabricator via cfe-commits
haowei updated this revision to Diff 475574.
haowei added a comment.

I have to revert back to use process cwd instead of base fs cwd. There are a 
few tests relied the behavior of using process cwd that I need to take a closer 
look.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137473

Files:
  clang/test/VFS/Inputs/root-relative-overlay.yaml
  clang/test/VFS/relative-path.c
  llvm/include/llvm/Support/VirtualFileSystem.h
  llvm/lib/Support/VirtualFileSystem.cpp
  llvm/unittests/Support/VirtualFileSystemTest.cpp

Index: llvm/unittests/Support/VirtualFileSystemTest.cpp
===
--- llvm/unittests/Support/VirtualFileSystemTest.cpp
+++ llvm/unittests/Support/VirtualFileSystemTest.cpp
@@ -1452,18 +1452,20 @@
 
   std::unique_ptr
   getFromYAMLRawString(StringRef Content,
-   IntrusiveRefCntPtr ExternalFS) {
+   IntrusiveRefCntPtr ExternalFS,
+   StringRef YAMLFilePath = "") {
 std::unique_ptr Buffer = MemoryBuffer::getMemBuffer(Content);
-return getVFSFromYAML(std::move(Buffer), CountingDiagHandler, "", this,
-  ExternalFS);
+return getVFSFromYAML(std::move(Buffer), CountingDiagHandler, YAMLFilePath,
+  this, ExternalFS);
   }
 
   std::unique_ptr getFromYAMLString(
   StringRef Content,
-  IntrusiveRefCntPtr ExternalFS = new DummyFileSystem()) {
+  IntrusiveRefCntPtr ExternalFS = new DummyFileSystem(),
+  StringRef YAMLFilePath = "") {
 std::string VersionPlusContent("{\n  'version':0,\n");
 VersionPlusContent += Content.slice(Content.find('{') + 1, StringRef::npos);
-return getFromYAMLRawString(VersionPlusContent, ExternalFS);
+return getFromYAMLRawString(VersionPlusContent, ExternalFS, YAMLFilePath);
   }
 
   // This is intended as a "XFAIL" for windows hosts.
@@ -1849,6 +1851,45 @@
   EXPECT_EQ(0, NumDiagnostics);
 }
 
+TEST_F(VFSFromYAMLTest, RootRelativeTest) {
+  IntrusiveRefCntPtr Lower(new DummyFileSystem());
+  Lower->addDirectory("//root/foo/bar");
+  Lower->addRegularFile("//root/foo/bar/a");
+  IntrusiveRefCntPtr FS =
+  getFromYAMLString("{\n"
+"  'case-sensitive': false,\n"
+"  'root-relative': 'overlay-dir',\n"
+"  'roots': [\n"
+"{ 'name': 'b', 'type': 'file',\n"
+"  'external-contents': '//root/foo/bar/a'\n"
+"}\n"
+"  ]\n"
+"}",
+Lower, "//root/foo/bar/overlay");
+
+  ASSERT_NE(FS.get(), nullptr);
+  ErrorOr S = FS->status("//root/foo/bar/b");
+  ASSERT_FALSE(S.getError());
+  EXPECT_EQ("//root/foo/bar/a", S->getName());
+
+  IntrusiveRefCntPtr FSOverlayRelative =
+  getFromYAMLString("{\n"
+"  'case-sensitive': false,\n"
+"  'overlay-relative': true,\n"
+"  'root-relative': 'overlay-dir',\n"
+"  'roots': [\n"
+"{ 'name': 'b', 'type': 'file',\n"
+"  'external-contents': 'a'\n"
+"}\n"
+"  ]\n"
+"}",
+Lower, "//root/foo/bar/overlay");
+  ASSERT_NE(FSOverlayRelative.get(), nullptr);
+  ErrorOr SOverlayRelative = FS->status("//root/foo/bar/b");
+  ASSERT_FALSE(SOverlayRelative.getError());
+  EXPECT_EQ("//root/foo/bar/a", SOverlayRelative->getName());
+}
+
 TEST_F(VFSFromYAMLTest, ReturnsInternalPathVFSHit) {
   IntrusiveRefCntPtr BaseFS(
   new vfs::InMemoryFileSystem);
Index: llvm/lib/Support/VirtualFileSystem.cpp
===
--- llvm/lib/Support/VirtualFileSystem.cpp
+++ llvm/lib/Support/VirtualFileSystem.cpp
@@ -1356,22 +1356,33 @@
   if (!WorkingDir)
 return WorkingDir.getError();
 
+  return makeAbsolute(WorkingDir.get(), Path);
+}
+
+std::error_code
+RedirectingFileSystem::makeAbsolute(StringRef WorkingDir,
+SmallVectorImpl &Path) const {
   // We can't use sys::fs::make_absolute because that assumes the path style
   // is native and there is no way to override that.  Since we know WorkingDir
   // is absolute, we can use it to determine which style we actually have and
   // append Path ourselves.
+  if (!WorkingDir.empty() &&
+  !sys::path::is_absolute(WorkingDir, sys::path::Style::posix) &&
+  !sys::path::is_absolute(WorkingDir,
+  sys::path::Style::windows_backslash)) {
+return std::error_code();
+  }
   sys::path::Style style = sys::path::Style::windows_backslash;
-  if (sys::path::is_absolute(WorkingDir.get(), sys::path::Style::posix)) {
+  if (sys::path::is_absolute(Wo

[PATCH] D137470: [Offloading] Initial support for registering offloading entries on COFF targets

2022-11-15 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

Thanks for the feedback.

Another significant portion of getting this workflow to work for Windows / COFF 
is parsing the linker arguments. I should be able to look at `lld-link` and add 
necessarily aliases to what `ld.lld` takes I assume? E.g. we use values like 
`-o` and `-L` in the linker wrapper to set the output and find libraries.




Comment at: clang/test/CodeGenCUDA/offloading-entries.cu:92
+// CUDA-COFF-NEXT:  entry:
+// CUDA-COFF-NEXT:[[TMP0:%.*]] = call i32 @cudaLaunch(ptr 
@_Z18__device_stub__barv)
+// CUDA-COFF-NEXT:br label [[SETUP_END:%.*]]

mstorsjo wrote:
> Is this identical to the one above? Should the lines be shared with 
> `--check-prefix=COMMON,COFF` etc? (The number of lines is rather small here 
> so it's maybe not strictly necessary, but I saw that done in the other 
> testcase.)
Yeah it might be valid to collapse it further, this test is mostly just 
copy-pasted directly from the output so we should probably try to keep it 
common.



Comment at: clang/tools/clang-linker-wrapper/OffloadWrapper.cpp:145
+  // For COFF targets, sections with 8 or fewer characters containing a '$' 
will
+  // be merged into the same section at runtime. The order is determined by the
+  // alphebetical ordering of the text after the '$' character. Here we 
generate

mstorsjo wrote:
> FWIW, this comment doesn't feel entirely accurate: Regardless of the length 
> of the section name, all sections with names of the form `name$suffix` will 
> get merged into the same section `name` (sorted by the suffix). Then if 
> `name` is 8 chars or less, the name is kept in the section table (so that it 
> can easily be looked up at runtime), while if it is longer, the full name is 
> kept in the string table (which is not mapped at runtime).
> 
> Also as an extra side note; we added an exception into lld for `.eh_frame` - 
> this is 9 chars, but libunwind wants to locate the section at runtime. So for 
> that case, lld truncates it to `.eh_fram`. (This behaviour is lld specific, 
> to appease libunwind - binutils doesn't do that, and libgcc locates that 
> section differently.)
I see, I'm not that familiar with the inner workings of the COFF linking 
process. All that matters for this use-case is whether or not we can get a 
pointer to the array. In that case we shouldn't need to worry about the eight 
character limit right?



Comment at: clang/tools/clang-linker-wrapper/OffloadWrapper.cpp:337
-  M, DummyInit->getType(), true, GlobalVariable::ExternalLinkage, 
DummyInit,
-  IsHIP ? "__dummy.hip_offloading.entry" : 
"__dummy.cuda_offloading.entry");
-  DummyEntry->setVisibility(GlobalValue::HiddenVisibility);

mstorsjo wrote:
> I don't quite see where the corresponding GlobalVariable for this case is 
> created after the refactoring?
The CUDA / HIP cases did this separately. This patch merged it into a common 
method `getELFEntriesArray`. Functionally this just changed the order in the 
output slightly. The `dummy` variable is only necessary for the ELF linkers to 
generate the begin / end section. For COFF we make the `$a` and `$z` variables 
which perform a similar role.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137470

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


[PATCH] D136806: [Pipelines] Introduce SROA after (final, full) loop unrolling

2022-11-15 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In D136806#3928663 , @asbirlea wrote:

> IIUC compile time impact for adding another SROA (the one outside LTO) is 
> negligible?

Yup.

> Regarding the principle of adding another pass and where in the pipeline, 
> we're still at a case by case basis. We had a discussion/round table at LLVM 
> Dev on the documenting the current new pass manager pipeline precisely for 
> understanding pass dependencies and being able to get resolutions on cases 
> such as this. I'm still putting together the summary for that but it should 
> be up on discourse this week.

We really can't achieve the same effect here in any other reasonable way,
without penalizing the inliner pipeline.

> Testing this change in parallel - I'll follow up tomorrow.

Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136806

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


[PATCH] D138062: [clang] Don't include C++ Standard Library headers when -nostdinc is used

2022-11-15 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a reviewer: clang-vendors.
ldionne added a comment.

I'm not sure who else to add on this review. Since changing the behavior of 
user-facing flags can be breaking, I'm adding the vendors. Feel free to suggest 
more.

Note that this was discovered when landing D136683 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138062

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


[PATCH] D138062: [clang] Don't include C++ Standard Library headers when -nostdinc is used

2022-11-15 Thread Louis Dionne via Phabricator via cfe-commits
ldionne created this revision.
ldionne added reviewers: MaskRay, phosek, arphaman.
Herald added subscribers: pmatos, asb, abrachet, StephenFan, jgravelle-google, 
sbc100, dschuff.
Herald added a project: All.
ldionne requested review of this revision.
Herald added subscribers: cfe-commits, aheejin.
Herald added a project: clang.

This is a follow-up to 53c98d85a 
, which 
made the same change but only
for GNU. It seems that we should try to provide a consistent behavior
across all targets.

This fixes an issue where clang/test/Driver/nostdincxx.cpp would start
failing on non-GNU targets because that test was too loose in its checks.
It would only check that 'file not found' was part of the error message,
but didn't ensure that the file we had not found was .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138062

Files:
  clang/lib/Driver/ToolChains/Darwin.cpp
  clang/lib/Driver/ToolChains/Fuchsia.cpp
  clang/lib/Driver/ToolChains/MinGW.cpp
  clang/lib/Driver/ToolChains/WebAssembly.cpp
  clang/test/Driver/darwin-header-search-libcxx.cpp
  clang/test/Driver/nostdincxx.cpp

Index: clang/test/Driver/nostdincxx.cpp
===
--- clang/test/Driver/nostdincxx.cpp
+++ clang/test/Driver/nostdincxx.cpp
@@ -2,8 +2,8 @@
 // RUN: not %clangxx -nostdinc++ %s 2>&1 | FileCheck %s
 // RUN: not %clangxx -nostdlibinc %s 2>&1 | FileCheck %s
 // RUN: not %clangxx --target=x86_64-unknown-unknown-gnu -fsyntax-only -nostdinc -nostdinc++ %s 2>&1 | FileCheck /dev/null --implicit-check-not=-Wunused-command-line-argument
-// CHECK: file not found
-#include  
+// CHECK: 'vector' file not found
+#include 
 
 // MSVC, PS4, PS5 have C++ headers in the same directory as C headers.
 // UNSUPPORTED: ms-sdk, ps4, ps5
Index: clang/test/Driver/darwin-header-search-libcxx.cpp
===
--- clang/test/Driver/darwin-header-search-libcxx.cpp
+++ clang/test/Driver/darwin-header-search-libcxx.cpp
@@ -92,39 +92,22 @@
 // CHECK-LIBCXX-SYSROOT_AND_TOOLCHAIN-1: "-internal-isystem" "[[TOOLCHAIN]]/usr/bin/../include/c++/v1"
 // CHECK-LIBCXX-SYSROOT_AND_TOOLCHAIN-1-NOT: "-internal-isystem" "[[SYSROOT]]/usr/include/c++/v1"
 
-// Make sure that using -nostdinc does not drop any C++ library include path.
-// This behavior is strange, but it is compatible with the legacy CC1 behavior.
-//
-// RUN: %clang -### %s -fsyntax-only 2>&1 \
-// RUN: --target=x86_64-apple-darwin16 \
-// RUN: -ccc-install-dir %S/Inputs/basic_darwin_toolchain/usr/bin \
-// RUN: -resource-dir=%S/Inputs/resource_dir \
-// RUN: -isysroot %S/Inputs/basic_darwin_sdk_usr_cxx_v1 \
-// RUN: -stdlib=platform \
-// RUN: -nostdinc \
-// RUN:   | FileCheck -DSYSROOT=%S/Inputs/basic_darwin_sdk_usr_cxx_v1 \
-// RUN:   -DTOOLCHAIN=%S/Inputs/basic_darwin_toolchain \
-// RUN:   --check-prefix=CHECK-LIBCXX-NOSTDINC-1 %s
-// CHECK-LIBCXX-NOSTDINC-1: "-cc1"
-// CHECK-LIBCXX-NOSTDINC-1-NOT: "-internal-isystem" "[[SYSROOT]]/usr/include/c++/v1"
-// CHECK-LIBCXX-NOSTDINC-1: "-internal-isystem" "[[TOOLCHAIN]]/usr/bin/../include/c++/v1"
+// Make sure that using -nostdinc, -nostdinc++ or -nostdlib will drop both the toolchain
+// C++ include path and the sysroot one.
 //
 // RUN: %clang -### %s -fsyntax-only 2>&1 \
 // RUN: --target=x86_64-apple-darwin16 \
 // RUN: -ccc-install-dir %S/Inputs/basic_darwin_toolchain/usr/bin \
 // RUN: -resource-dir=%S/Inputs/resource_dir \
-// RUN: -isysroot %S/Inputs/basic_darwin_sdk_no_libcxx \
+// RUN: -isysroot %S/Inputs/basic_darwin_sdk_usr \
 // RUN: -stdlib=platform \
 // RUN: -nostdinc \
-// RUN:   | FileCheck -DSYSROOT=%S/Inputs/basic_darwin_sdk_no_libcxx \
+// RUN:   | FileCheck -DSYSROOT=%S/Inputs/basic_darwin_sdk_usr \
 // RUN:   -DTOOLCHAIN=%S/Inputs/basic_darwin_toolchain \
-// RUN:   --check-prefix=CHECK-LIBCXX-NOSTDINC-2 %s
-// CHECK-LIBCXX-NOSTDINC-2: "-cc1"
-// CHECK-LIBCXX-NOSTDINC-2: "-internal-isystem" "[[TOOLCHAIN]]/usr/bin/../include/c++/v1"
-// CHECK-LIBCXX-NOSTDINC-2-NOT: "-internal-isystem" "[[SYSROOT]]/usr/include/c++/v1"
-
-// Make sure that using -nostdinc++ or -nostdlib will drop both the toolchain
-// C++ include path and the sysroot one.
+// RUN:   --check-prefix=CHECK-LIBCXX-NOSTDLIBINC %s
+// CHECK-LIBCXX-NOSTDINC: "-cc1"
+// CHECK-LIBCXX-NOSTDINC-NOT: "-internal-isystem" "[[TOOLCHAIN]]/usr/bin/../include/c++/v1"
+// CHECK-LIBCXX-NOSTDINC-NOT: "-internal-isystem" "[[SYSROOT]]/usr/include/c++/v1"
 //
 // RUN: %clang -### %s -fsyntax-only 2>&1 \
 // RUN: --target=x86_64-apple-darwin16 \
Index: clang/lib/Driver/ToolChains/WebAssembly.cpp
===
--- clang/lib/Driver/ToolChains/WebAssembly.cpp
+++ clang/lib/Driver/ToolChains/WebAssembly.cpp
@@ -424,8 +424,8 @@
 void WebAssembly::

[PATCH] D137989: [clang][deps] Avoid leaking modulemap paths across unrelated imports

2022-11-15 Thread Ben Langmuir via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG05ec16d90deb: [clang][deps] Avoid leaking modulemap paths 
across unrelated imports (authored by benlangmuir).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137989

Files:
  clang/include/clang/Serialization/ASTReader.h
  clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
  clang/test/ClangScanDeps/modules-symlink-dir-from-module.c

Index: clang/test/ClangScanDeps/modules-symlink-dir-from-module.c
===
--- /dev/null
+++ clang/test/ClangScanDeps/modules-symlink-dir-from-module.c
@@ -0,0 +1,94 @@
+// Check that the path of an imported modulemap file is not influenced by
+// modules outside that module's dependency graph. Specifically, the "Foo"
+// module below does not transitively import Mod via a symlink, so it should not
+// see the symlinked path.
+
+// REQUIRES: shell
+
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s|DIR|%/t|g" %t/cdb.json.in > %t/cdb.json
+// RUN: ln -s module %t/include/symlink-to-module
+
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -j 1 \
+// RUN:   -format experimental-full  -mode=preprocess-dependency-directives \
+// RUN:   -optimize-args -module-files-dir %t/build > %t/deps.json
+
+// RUN: cat %t/deps.json | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t
+
+// CHECK: "modules": [
+// CHECK:   {
+// CHECK: "command-line": [
+// CHECK:   "-fmodule-map-file=[[PREFIX]]/include/module/module.modulemap"
+// CHECK: ]
+// CHECK: "name": "Foo"
+// CHECK:   }
+// CHECK:   {
+// CHECK: "command-line": [
+// FIXME: canonicalize this path
+// CHECK:   "-fmodule-map-file=[[PREFIX]]/include/symlink-to-module/module.modulemap"
+// CHECK: ]
+// CHECK: "name": "Foo_Private"
+// CHECK:   }
+// CHECK:   {
+// CHECK: "command-line": [
+// CHECK:   "[[PREFIX]]/include/module/module.modulemap"
+// CHECK: ]
+// CHECK: "name": "Mod"
+// CHECK:   }
+// CHECK:   {
+// CHECK: "command-line": [
+// FIXME: canonicalize this path
+// CHECK:   "-fmodule-map-file=[[PREFIX]]/include/symlink-to-module/module.modulemap"
+// CHECK: ]
+// CHECK: "name": "Other"
+// CHECK:   }
+// CHECK:   {
+// CHECK: "command-line": [
+// FIXME: canonicalize this path
+// CHECK:   "-fmodule-map-file=[[PREFIX]]/include/symlink-to-module/module.modulemap"
+// CHECK: ]
+// CHECK: "name": "Test"
+// CHECK:   }
+// CHECK: ]
+
+//--- cdb.json.in
+[{
+  "directory": "DIR",
+  "command": "clang -fsyntax-only DIR/test.c -F DIR/Frameworks -I DIR/include -fmodules -fimplicit-module-maps -fmodules-cache-path=DIR/module-cache",
+  "file": "DIR/test.c"
+}]
+
+//--- include/module/module.modulemap
+module Mod { header "mod.h" export * }
+
+//--- include/module/mod.h
+
+//--- include/module.modulemap
+module Other { header "other.h" export * }
+
+//--- include/other.h
+#include "symlink-to-module/mod.h"
+#include "module/mod.h"
+
+//--- Frameworks/Foo.framework/Modules/module.modulemap
+framework module Foo { header "Foo.h" export * }
+//--- Frameworks/Foo.framework/Modules/module.private.modulemap
+framework module Foo_Private { header "Priv.h" export * }
+
+//--- Frameworks/Foo.framework/Headers/Foo.h
+#include "module/mod.h"
+
+//--- Frameworks/Foo.framework/PrivateHeaders/Priv.h
+#include 
+#include "other.h"
+
+//--- module.modulemap
+module Test { header "test.h" export * }
+
+//--- test.h
+#include 
+#include 
+
+//--- test.c
+#include "test.h"
Index: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
===
--- clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -130,22 +130,22 @@
 
   auto DepModuleMapFiles = collectModuleMapFiles(Deps.ClangModuleDeps);
   for (StringRef ModuleMapFile : Deps.ModuleMapFileDeps) {
+// TODO: Track these as `FileEntryRef` to simplify the equality check below.
+auto ModuleMapEntry = ScanInstance.getFileManager().getFile(ModuleMapFile);
+assert(ModuleMapEntry && "module map file entry not found");
+
 // Don't report module maps describing eagerly-loaded dependency. This
 // information will be deserialized from the PCM.
 // TODO: Verify this works fine when modulemap for module A is eagerly
 // loaded from A.pcm, and module map passed on the command line contains
 // definition of a submodule: "explicit module A.Private { ... }".
-if (EagerLoadModules && DepModuleMapFiles.contains(ModuleMapFile))
+if (EagerLoadModules && DepModuleMapFiles.contains(*ModuleMapEntry))
   continue;
 
-  

[clang] 05ec16d - [clang][deps] Avoid leaking modulemap paths across unrelated imports

2022-11-15 Thread Ben Langmuir via cfe-commits

Author: Ben Langmuir
Date: 2022-11-15T13:59:26-08:00
New Revision: 05ec16d90deb747414c8534f98617d25d90bb714

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

LOG: [clang][deps] Avoid leaking modulemap paths across unrelated imports

Use a FileEntryRef when retrieving modulemap paths in the scanner so
that we use a path compatible with the original module import, rather
than a FileEntry which can allow unrelated modules to leak paths into
how we build a module due to FileManager mutating the path.

Note: the current change prevents an "unrelated" path, but does not
change how VFS mapped paths are handled (which would be calling
getNameAsRequested) nor canonicalize the path.

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

Added: 
clang/test/ClangScanDeps/modules-symlink-dir-from-module.c

Modified: 
clang/include/clang/Serialization/ASTReader.h
clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
clang/lib/Frontend/FrontendAction.cpp
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTWriter.cpp
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp

Removed: 




diff  --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index da8b9a9207a03..23c67fc8828d3 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -2338,8 +2338,7 @@ class ASTReader
   /// Visit all the top-level module maps loaded when building the given module
   /// file.
   void visitTopLevelModuleMaps(serialization::ModuleFile &MF,
-   llvm::function_ref<
-   void(const FileEntry *)> Visitor);
+   llvm::function_ref Visitor);
 
   bool isProcessingUpdateRecords() { return ProcessingUpdateRecords; }
 };

diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h 
b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
index 5062c4cc5e265..1cc6208a4c36a 100644
--- a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
+++ b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
@@ -237,7 +237,7 @@ class ModuleDepCollector final : public DependencyCollector 
{
   llvm::function_ref Optimize) const;
 
   /// Collect module map files for given modules.
-  llvm::StringSet<>
+  llvm::DenseSet
   collectModuleMapFiles(ArrayRef ClangModuleDeps) const;
 
   /// Add module map files to the invocation, if needed.

diff  --git a/clang/lib/Frontend/FrontendAction.cpp 
b/clang/lib/Frontend/FrontendAction.cpp
index 45f04eac818da..76ef0cb3b4051 100644
--- a/clang/lib/Frontend/FrontendAction.cpp
+++ b/clang/lib/Frontend/FrontendAction.cpp
@@ -638,11 +638,10 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
 if (&MF != &PrimaryModule)
   CI.getFrontendOpts().ModuleFiles.push_back(MF.FileName);
 
-  ASTReader->visitTopLevelModuleMaps(
-  PrimaryModule, [&](const FileEntry *FE) {
-CI.getFrontendOpts().ModuleMapFiles.push_back(
-std::string(FE->getName()));
-  });
+  ASTReader->visitTopLevelModuleMaps(PrimaryModule, [&](FileEntryRef FE) {
+CI.getFrontendOpts().ModuleMapFiles.push_back(
+std::string(FE.getName()));
+  });
 }
 
 // Set up the input file for replay purposes.

diff  --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index 05e6c6ea7952b..cf3716201dd80 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -9164,14 +9164,14 @@ void 
ASTReader::visitInputFiles(serialization::ModuleFile &MF,
 
 void ASTReader::visitTopLevelModuleMaps(
 serialization::ModuleFile &MF,
-llvm::function_ref Visitor) {
+llvm::function_ref Visitor) {
   unsigned NumInputs = MF.InputFilesLoaded.size();
   for (unsigned I = 0; I < NumInputs; ++I) {
 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
 if (IFI.TopLevelModuleMap)
   // FIXME: This unnecessarily re-reads the InputFileInfo.
   if (auto FE = getInputFile(MF, I + 1).getFile())
-Visitor(FE);
+Visitor(*FE);
   }
 }
 

diff  --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 1dcb5426b314d..cdd65a4461d71 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -1486,12 +1486,14 @@ namespace  {
 
 /// An input file.
 struct InputFileEntry {
-  const FileEntry *File;
+  FileEntryRef File;
   bool IsSystemFile;
   bool IsTransient;
   bool BufferOverridden;
   bool IsTopLevelModuleMap;
   uint32_t ContentHash[2];
+
+  InputFileEntry(FileEntryRef File) : File(File)

[PATCH] D137470: [Offloading] Initial support for registering offloading entries on COFF targets

2022-11-15 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

This looks reasonable to me, overall. I didn't quite try to follow all the 
wall-of-text changes in the tests though, but overall fine. Just a couple 
comments and one case where I didn't find where code went in the refactoring.




Comment at: clang/test/CodeGenCUDA/offloading-entries.cu:92
+// CUDA-COFF-NEXT:  entry:
+// CUDA-COFF-NEXT:[[TMP0:%.*]] = call i32 @cudaLaunch(ptr 
@_Z18__device_stub__barv)
+// CUDA-COFF-NEXT:br label [[SETUP_END:%.*]]

Is this identical to the one above? Should the lines be shared with 
`--check-prefix=COMMON,COFF` etc? (The number of lines is rather small here so 
it's maybe not strictly necessary, but I saw that done in the other testcase.)



Comment at: clang/tools/clang-linker-wrapper/OffloadWrapper.cpp:145
+  // For COFF targets, sections with 8 or fewer characters containing a '$' 
will
+  // be merged into the same section at runtime. The order is determined by the
+  // alphebetical ordering of the text after the '$' character. Here we 
generate

FWIW, this comment doesn't feel entirely accurate: Regardless of the length of 
the section name, all sections with names of the form `name$suffix` will get 
merged into the same section `name` (sorted by the suffix). Then if `name` is 8 
chars or less, the name is kept in the section table (so that it can easily be 
looked up at runtime), while if it is longer, the full name is kept in the 
string table (which is not mapped at runtime).

Also as an extra side note; we added an exception into lld for `.eh_frame` - 
this is 9 chars, but libunwind wants to locate the section at runtime. So for 
that case, lld truncates it to `.eh_fram`. (This behaviour is lld specific, to 
appease libunwind - binutils doesn't do that, and libgcc locates that section 
differently.)



Comment at: clang/tools/clang-linker-wrapper/OffloadWrapper.cpp:337
-  M, DummyInit->getType(), true, GlobalVariable::ExternalLinkage, 
DummyInit,
-  IsHIP ? "__dummy.hip_offloading.entry" : 
"__dummy.cuda_offloading.entry");
-  DummyEntry->setVisibility(GlobalValue::HiddenVisibility);

I don't quite see where the corresponding GlobalVariable for this case is 
created after the refactoring?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137470

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


[PATCH] D137979: parse: process GNU and standard attributes on top-level decls

2022-11-15 Thread Saleem Abdulrasool via Phabricator via cfe-commits
compnerd updated this revision to Diff 475570.
compnerd edited the summary of this revision.

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

https://reviews.llvm.org/D137979

Files:
  clang/include/clang/Parse/Parser.h
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseHLSL.cpp
  clang/lib/Parse/ParseObjc.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Parse/Parser.cpp
  clang/test/Parser/attr-order.cpp
  clang/test/Parser/cxx-attributes.cpp
  clang/test/SemaCXX/attr-unavailable.cpp
  clang/test/SemaObjC/objc-asm-attribute-neg-test.m
  clang/unittests/Tooling/SourceCodeTest.cpp

Index: clang/unittests/Tooling/SourceCodeTest.cpp
===
--- clang/unittests/Tooling/SourceCodeTest.cpp
+++ clang/unittests/Tooling/SourceCodeTest.cpp
@@ -247,14 +247,25 @@
 
   // Includes attributes.
   Visitor.runOverAnnotated(R"cpp(
-  #define ATTR __attribute__((deprecated("message")))
-  $r[[ATTR
+  $r[[__attribute__((deprecated("message")))
   int x;]])cpp");
 
   // Includes attributes and comments together.
   Visitor.runOverAnnotated(R"cpp(
-  #define ATTR __attribute__((deprecated("message")))
-  $r[[ATTR
+  $r[[__attribute__((deprecated("message")))
+  // Comment.
+  int x;]])cpp");
+
+  // Includes attributes through macro expansion.
+  Visitor.runOverAnnotated(R"cpp(
+  #define MACRO_EXPANSION __attribute__((deprecated("message")))
+  $r[[MACRO_EXPANSION
+  int x;]])cpp");
+
+  // Includes attributes through macro expansion with comments.
+  Visitor.runOverAnnotated(R"cpp(
+  #define MACRO_EXPANSION __attribute__((deprecated("message")))
+  $r[[MACRO_EXPANSION
   // Comment.
   int x;]])cpp");
 }
@@ -402,14 +413,25 @@
 
   // Includes attributes.
   Visit(R"cpp(
-  #define ATTR __attribute__((deprecated("message")))
-  $r[[ATTR
+  $r[[__attribute__((deprecated("message")))
   int x;]])cpp");
 
   // Includes attributes and comments together.
   Visit(R"cpp(
-  #define ATTR __attribute__((deprecated("message")))
-  $r[[ATTR
+  $r[[__attribute__((deprecated("message")))
+  // Comment.
+  int x;]])cpp");
+
+  // Includes attributes through macro expansion.
+  Visitor.runOverAnnotated(R"cpp(
+  #define MACRO_EXPANSION __attribute__((deprecated("message")))
+  $r[[MACRO_EXPANSION
+  int x;]])cpp");
+
+  // Includes attributes through macro expansion with comments.
+  Visitor.runOverAnnotated(R"cpp(
+  #define MACRO_EXPANSION __attribute__((deprecated("message")))
+  $r[[MACRO_EXPANSION
   // Comment.
   int x;]])cpp");
 }
Index: clang/test/SemaObjC/objc-asm-attribute-neg-test.m
===
--- clang/test/SemaObjC/objc-asm-attribute-neg-test.m
+++ clang/test/SemaObjC/objc-asm-attribute-neg-test.m
@@ -28,7 +28,7 @@
 @end
 
 __attribute__((objc_runtime_name("MySecretNamespace.ForwardClass")))
-@class ForwardClass; // expected-error {{prefix attribute must be followed by an interface, protocol, or implementation}}
+@class ForwardClass; // expected-error@-1 {{prefix attribute must be followed by an interface, protocol, or implementation}}
 
 __attribute__((objc_runtime_name("MySecretNamespace.ForwardProtocol")))
 @protocol ForwardProtocol;
Index: clang/test/SemaCXX/attr-unavailable.cpp
===
--- clang/test/SemaCXX/attr-unavailable.cpp
+++ clang/test/SemaCXX/attr-unavailable.cpp
@@ -42,18 +42,18 @@
 // delayed process for 'deprecated'.
 //  and 
 enum DeprecatedEnum { DE_A, DE_B } __attribute__((deprecated)); // expected-note {{'DeprecatedEnum' has been explicitly marked deprecated here}}
-__attribute__((deprecated)) typedef enum DeprecatedEnum DeprecatedEnum;
 typedef enum DeprecatedEnum AnotherDeprecatedEnum; // expected-warning {{'DeprecatedEnum' is deprecated}}
 
+__attribute__((deprecated)) typedef enum DeprecatedEnum DeprecatedEnum;
 __attribute__((deprecated))
 DeprecatedEnum testDeprecated(DeprecatedEnum X) { return X; }
 
 
 enum UnavailableEnum { UE_A, UE_B } __attribute__((unavailable)); // expected-note {{'UnavailableEnum' has been explicitly marked unavailable here}}
-__attribute__((unavailable)) typedef enum UnavailableEnum UnavailableEnum;
 typedef enum UnavailableEnum AnotherUnavailableEnum; // expected-error {{'UnavailableEnum' is unavailable}}
+ //
 
-
+__attribute__((unavailable)) typedef enum UnavailableEnum UnavailableEnum;
 __attribute__((unavailable))
 UnavailableEnum testUnavailable(UnavailableEnum X) { return X; }
 
Index: clang/test/Parser/cxx-attributes.cpp
===
--- clang/test/Parser/cxx-attributes.cpp
+++ clang/test/Parser/cxx-attributes.cpp
@@ -1,5 +1,9 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
 
+// GH#58229 - rejects-valid
+__attribute__((__visibilit

[PATCH] D136806: [Pipelines] Introduce SROA after (final, full) loop unrolling

2022-11-15 Thread Alina Sbirlea via Phabricator via cfe-commits
asbirlea added a comment.

IIUC compile time impact for adding another SROA (the one outside LTO) is 
negligible?

Regarding the principle of adding another pass and where in the pipeline, we're 
still at a case by case basis. We had a discussion/round table at LLVM Dev on 
the documenting the current new pass manager pipeline precisely for 
understanding pass dependencies and being able to get resolutions on cases such 
as this. I'm still putting together the summary for that but it should be up on 
discourse this week.

Testing this change in parallel - I'll follow up tomorrow.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136806

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


[PATCH] D137570: [Clang][Sema] Refactor category declaration under CheckForIncompatibleAttributes. NFC

2022-11-15 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
eopXD updated this revision to Diff 475563.
eopXD added a comment.

Rebase to latest main.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137570

Files:
  clang/lib/Sema/SemaStmtAttr.cpp


Index: clang/lib/Sema/SemaStmtAttr.cpp
===
--- clang/lib/Sema/SemaStmtAttr.cpp
+++ clang/lib/Sema/SemaStmtAttr.cpp
@@ -306,21 +306,33 @@
   if (!DiagnoseMutualExclusions(S, Attrs))
 return;
 
-  // There are 6 categories of loop hints attributes: vectorize, interleave,
-  // unroll, unroll_and_jam, pipeline and distribute. Except for distribute 
they
-  // come in two variants: a state form and a numeric form.  The state form
-  // selectively defaults/enables/disables the transformation for the loop
-  // (for unroll, default indicates full unrolling rather than enabling the
-  // transformation). The numeric form provides an integer hint (for
-  // example, unroll count) to the transformer. The following array accumulates
-  // the hints encountered while iterating through the attributes to check for
-  // compatibility.
+  enum CategoryType {
+// For the following categories, they come in two variants: a state form 
and
+// a numeric form. The state form may be one of default, enable, and
+// disable. The numeric form provides an integer hint (for example, unroll
+// count) to the transformer.
+Vectorize,
+Interleave,
+UnrollAndJam,
+Pipeline,
+// For unroll, default indicates full unrolling rather than enabling the
+// transformation.
+Unroll,
+// The loop distribution transformation only has a state form that is
+// exposed by #pragma clang loop distribute (enable | disable).
+Distribute,
+// The vector predication only has a state form that is exposed by
+// #pragma clang loop vectorize_predicate (enable | disable).
+VectorizePredicate,
+// This serves as a indicator to how many category are listed in this enum.
+NumberOfCategories
+  };
+  // The following array accumulates the hints encountered while iterating
+  // through the attributes to check for compatibility.
   struct {
 const LoopHintAttr *StateAttr;
 const LoopHintAttr *NumericAttr;
-  } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
-   {nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr},
-   {nullptr, nullptr}};
+  } HintAttrs[CategoryType::NumberOfCategories] = {};
 
   for (const auto *I : Attrs) {
 const LoopHintAttr *LH = dyn_cast(I);
@@ -329,16 +341,8 @@
 if (!LH)
   continue;
 
+CategoryType Category = CategoryType::NumberOfCategories;
 LoopHintAttr::OptionType Option = LH->getOption();
-enum {
-  Vectorize,
-  Interleave,
-  Unroll,
-  UnrollAndJam,
-  Distribute,
-  Pipeline,
-  VectorizePredicate
-} Category;
 switch (Option) {
 case LoopHintAttr::Vectorize:
 case LoopHintAttr::VectorizeWidth:
@@ -369,7 +373,7 @@
   break;
 };
 
-assert(Category < sizeof(HintAttrs) / sizeof(HintAttrs[0]));
+assert(Category != NumberOfCategories && "Unhandled loop hint option");
 auto &CategoryState = HintAttrs[Category];
 const LoopHintAttr *PrevAttr;
 if (Option == LoopHintAttr::Vectorize ||


Index: clang/lib/Sema/SemaStmtAttr.cpp
===
--- clang/lib/Sema/SemaStmtAttr.cpp
+++ clang/lib/Sema/SemaStmtAttr.cpp
@@ -306,21 +306,33 @@
   if (!DiagnoseMutualExclusions(S, Attrs))
 return;
 
-  // There are 6 categories of loop hints attributes: vectorize, interleave,
-  // unroll, unroll_and_jam, pipeline and distribute. Except for distribute they
-  // come in two variants: a state form and a numeric form.  The state form
-  // selectively defaults/enables/disables the transformation for the loop
-  // (for unroll, default indicates full unrolling rather than enabling the
-  // transformation). The numeric form provides an integer hint (for
-  // example, unroll count) to the transformer. The following array accumulates
-  // the hints encountered while iterating through the attributes to check for
-  // compatibility.
+  enum CategoryType {
+// For the following categories, they come in two variants: a state form and
+// a numeric form. The state form may be one of default, enable, and
+// disable. The numeric form provides an integer hint (for example, unroll
+// count) to the transformer.
+Vectorize,
+Interleave,
+UnrollAndJam,
+Pipeline,
+// For unroll, default indicates full unrolling rather than enabling the
+// transformation.
+Unroll,
+// The loop distribution transformation only has a state form that is
+// exposed by #pragma clang loop distribute (enable | disable).
+Distribute,
+// The vector predication only has a state form that is e

[PATCH] D137570: [Clang][Sema] Refactor category declaration under CheckForIncompatibleAttributes. NFC

2022-11-15 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
eopXD added a comment.

@mikerice @jyu2
May you accept the revision please if this patch looks good to you? Thank you :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137570

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


[PATCH] D135488: [codegen] Display stack layouts in console

2022-11-15 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added a comment.

In D135488#3928567 , @nickdesaulniers 
wrote:

> In D135488#3928559 , @arsenm wrote:
>
>> In D135488#3928557 , 
>> @nickdesaulniers wrote:
>>
>>> Can we add a `Note` diagnostic when we emit a `-Wframe-larger-than=` that 
>>> alludes to re-running with `-mllvm -print-stack-frame` to get additional 
>>> info?
>>>
>>> We should update the release notes of clang to mention this feature, too.
>>
>> I don't think we should be pointing users to -mllvm flags. Plus, I don't 
>> really think random dbgs() printing is going to interact correctly with 
>> other diagnostics
>
> Then how will users know about super cool things? We could create a new front 
> end flag for this `-mllvm` flag, a la https://reviews.llvm.org/D131986.

I'd be a bit more comfortable routing this through the backend remarks 
infrastructure, although it's a lot bigger than everything else currently 
reported there


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135488

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


[PATCH] D135488: [codegen] Display stack layouts in console

2022-11-15 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

In D135488#3928567 , @nickdesaulniers 
wrote:

> In D135488#3928559 , @arsenm wrote:
>
>> In D135488#3928557 , 
>> @nickdesaulniers wrote:
>>
>>> Can we add a `Note` diagnostic when we emit a `-Wframe-larger-than=` that 
>>> alludes to re-running with `-mllvm -print-stack-frame` to get additional 
>>> info?
>>>
>>> We should update the release notes of clang to mention this feature, too.
>>
>> I don't think we should be pointing users to -mllvm flags. Plus, I don't 
>> really think random dbgs() printing is going to interact correctly with 
>> other diagnostics
>
> Then how will users know about super cool things? We could create a new front 
> end flag for this `-mllvm` flag, a la https://reviews.llvm.org/D131986.

Sorry, bad example; that example is adding IR Function attributes, not setting 
`-mllvm` flags (which tend to get dropped during LTO unless re-passed to the 
linker), but there is a `-mllvm` flag for that. https://reviews.llvm.org/D127988

Regardless, we _could_ wire up a frontend flag for more info, I think. Not sure 
we have precedence for that, but it would be really really helpful to folks 
presented with `-Wframe-larger-than=` warnings.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135488

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


[PATCH] D137826: [clang] Allow comparing pointers to string literals

2022-11-15 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann added inline comments.



Comment at: clang/lib/AST/ExprConstant.cpp:12951-12954
+  // ObjC's @encode()
+  if (isa(E->getLHS()->IgnoreParenImpCasts()) ||
+  isa(E->getRHS()->IgnoreParenImpCasts()))
 return Error(E);

A comment to explain this change would be helpful. It isn't intuitive (for me 
anyway) why Objective-C's `@encode` would require special handling here. Was 
this needed to avoid a test failure?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137826

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


[PATCH] D137823: [clang-format][NFC] Moved configuration parsing tests in own file

2022-11-15 Thread Owen Pan via Phabricator via cfe-commits
owenpan accepted this revision.
owenpan added a comment.
This revision is now accepted and ready to land.

Thanks!


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

https://reviews.llvm.org/D137823

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


Re: How can Autoconf help with the transition to stricter compilation defaults?

2022-11-15 Thread Paul Eggert via cfe-commits

On 2022-11-15 11:27, Jonathan Wakely wrote:

Another perspective is that autoconf shouldn't get in the way of
making the C and C++ toolchain more secure by default.


Can you cite any examples of a real-world security flaw what would be 
found by Clang erroring out because 'char foo(void);' is the wrong 
prototype? Is it plausible that any such security flaw exists?


On the contrary, it's more likely that Clang's erroring out here would 
*introduce* a security flaw, because it would cause 'configure' to 
incorrectly infer that an important security-relevant function is 
missing and that a flawed substitute needs to be used.


Let's focus on real problems rather than worrying about imaginary ones.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: How can Autoconf help with the transition to stricter compilation defaults?

2022-11-15 Thread Paul Eggert via cfe-commits

On 2022-11-15 06:50, Jonathan Wakely wrote:

Could you clarify what you mean, with a concrete example? Surely as
long as errors are reported on stderr and the compiler exits with
non-zero status, that's an acceptable way to report errors?


Not if the "error" is harmless as far as Autoconf is concerned, which is 
what led to this thread. The concrete example here is that Autoconf 
needs to check whether a function can be linked to (as opposed to 
checking the function's signature). Clang shouldn't get in the way.


In lots of places the C standard says behavior is undefined, even though 
the behavior is fine on the current platform for the intended use. It's 
not just the example we're talking about; adding zero to a null pointer 
is another such example.


In such cases it's OK for Clang to warn, but having Clang exit with 
nonzero status is overkill and counterproductive.

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


[PATCH] D135488: [codegen] Display stack layouts in console

2022-11-15 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

In D135488#3928559 , @arsenm wrote:

> In D135488#3928557 , 
> @nickdesaulniers wrote:
>
>> Can we add a `Note` diagnostic when we emit a `-Wframe-larger-than=` that 
>> alludes to re-running with `-mllvm -print-stack-frame` to get additional 
>> info?
>>
>> We should update the release notes of clang to mention this feature, too.
>
> I don't think we should be pointing users to -mllvm flags. Plus, I don't 
> really think random dbgs() printing is going to interact correctly with other 
> diagnostics

Then how will users know about super cool things? We could create a new front 
end flag for this `-mllvm` flag, a la https://reviews.llvm.org/D131986.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135488

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


Re: How can Autoconf help with the transition to stricter compilation defaults?

2022-11-15 Thread Aaron Ballman via cfe-commits
On Tue, Nov 15, 2022 at 3:27 PM Paul Eggert  wrote:
>
> On 2022-11-15 11:27, Jonathan Wakely wrote:
> > Another perspective is that autoconf shouldn't get in the way of
> > making the C and C++ toolchain more secure by default.
>
> Can you cite any examples of a real-world security flaw what would be
> found by Clang erroring out because 'char foo(void);' is the wrong
> prototype? Is it plausible that any such security flaw exists?

CVE-2006-1174 is a possibly reasonable example. That one is
specifically about the K&R C open() interface, but the reason the CVE
happened was because a required argument was not passed which is
exactly the kind of problem you'd get from a prototype mismatch.

I think autoconf's usage pattern is well outside of common C coding
practices. Most folks who call a function expect the call to plausibly
happen at runtime (rather than do so just to see if the linker will
complain or not), and I don't know of another context in which anyone
expects calling a function with an incorrect signature will lead to
good outcomes.

> On the contrary, it's more likely that Clang's erroring out here would
> *introduce* a security flaw, because it would cause 'configure' to
> incorrectly infer that an important security-relevant function is
> missing and that a flawed substitute needs to be used.
>
> Let's focus on real problems rather than worrying about imaginary ones.

If the symbol exists and `configure` says it does not, that's the bug
and it's not with the host compiler. You can run into that same bug
with use of `-Werror`, as others have pointed out. So strengthening
warnings doesn't introduce any NEW problems into autoconf, it
exacerbates existing ones.

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


[PATCH] D135488: [codegen] Display stack layouts in console

2022-11-15 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added a comment.

In D135488#3928557 , @nickdesaulniers 
wrote:

> Can we add a `Note` diagnostic when we emit a `-Wframe-larger-than=` that 
> alludes to re-running with `-mllvm -print-stack-frame` to get additional info?
>
> We should update the release notes of clang to mention this feature, too.

I don't think we should be pointing users to -mllvm flags. Plus, I don't really 
think random dbgs() printing is going to interact correctly with other 
diagnostics




Comment at: llvm/lib/CodeGen/StackFramePrinterPass.cpp:120-122
+  // This is a dead slot, so skip it
+  if (Size == ~0ULL)
+continue;

Check MFI.isDead instead?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135488

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


[PATCH] D135488: [codegen] Display stack layouts in console

2022-11-15 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

Can we add a `Note` diagnostic when we emit a `-Wframe-larger-than=` that 
alludes to re-running with `-mllvm -print-stack-frame` to get additional info?

We should update the release notes of clang to mention this feature, too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135488

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


[PATCH] D138058: [Sema] Use the value category of the base expression when creating an ExtVectorElementExpr

2022-11-15 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak created this revision.
ahatanak added a reviewer: rjmccall.
ahatanak added a project: clang.
Herald added a project: All.
ahatanak requested review of this revision.

This fixes a bug where an lvalue `ExtVectorElementExpr` was created when the 
base expression was an ObjC property dot operator.

This reverts 220d08d942ab0df3211388e602ed34fa6139ca61.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D138058

Files:
  clang/lib/Sema/SemaExprMember.cpp
  clang/test/SemaObjC/property-not-lvalue.m


Index: clang/test/SemaObjC/property-not-lvalue.m
===
--- clang/test/SemaObjC/property-not-lvalue.m
+++ clang/test/SemaObjC/property-not-lvalue.m
@@ -7,10 +7,13 @@
} inner;
 } NSSize;
 
+typedef __attribute__((__ext_vector_type__(2))) float simd_float2;
+
 @interface Foo  {
 NSSize _size;
 }
 @property NSSize size;
+@property simd_float2 f2;
 @end
 
 void foo(void) { 
@@ -32,3 +35,8 @@
 }
 - (NSSize)size {}
 @end
+
+// clang used to crash compiling this code.
+void test(Foo *f) {
+  simd_float2 *v = &f.f2.xy; // expected-error {{cannot take the address of an 
rvalue}}
+}
Index: clang/lib/Sema/SemaExprMember.cpp
===
--- clang/lib/Sema/SemaExprMember.cpp
+++ clang/lib/Sema/SemaExprMember.cpp
@@ -1621,16 +1621,7 @@
   if (BaseType->isExtVectorType()) {
 // FIXME: this expr should store IsArrow.
 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
-ExprValueKind VK;
-if (IsArrow)
-  VK = VK_LValue;
-else {
-  if (PseudoObjectExpr *POE = dyn_cast(BaseExpr.get()))
-VK = POE->getSyntacticForm()->getValueKind();
-  else
-VK = BaseExpr.get()->getValueKind();
-}
-
+ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
Member, MemberLoc);
 if (ret.isNull())


Index: clang/test/SemaObjC/property-not-lvalue.m
===
--- clang/test/SemaObjC/property-not-lvalue.m
+++ clang/test/SemaObjC/property-not-lvalue.m
@@ -7,10 +7,13 @@
 		} inner;
 } NSSize;
 
+typedef __attribute__((__ext_vector_type__(2))) float simd_float2;
+
 @interface Foo  {
 NSSize _size;
 }
 @property NSSize size;
+@property simd_float2 f2;
 @end
 
 void foo(void) { 
@@ -32,3 +35,8 @@
 }
 - (NSSize)size {}
 @end
+
+// clang used to crash compiling this code.
+void test(Foo *f) {
+  simd_float2 *v = &f.f2.xy; // expected-error {{cannot take the address of an rvalue}}
+}
Index: clang/lib/Sema/SemaExprMember.cpp
===
--- clang/lib/Sema/SemaExprMember.cpp
+++ clang/lib/Sema/SemaExprMember.cpp
@@ -1621,16 +1621,7 @@
   if (BaseType->isExtVectorType()) {
 // FIXME: this expr should store IsArrow.
 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
-ExprValueKind VK;
-if (IsArrow)
-  VK = VK_LValue;
-else {
-  if (PseudoObjectExpr *POE = dyn_cast(BaseExpr.get()))
-VK = POE->getSyntacticForm()->getValueKind();
-  else
-VK = BaseExpr.get()->getValueKind();
-}
-
+ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
Member, MemberLoc);
 if (ret.isNull())
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137488: [clang][Interp] Array initialization via string literal

2022-11-15 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann added inline comments.



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:1098-1099
+
+unsigned N = SL->getLength();
+for (size_t I = 0; I != NumElems; ++I) {
+  uint32_t CodePoint = I < N ? SL->getCodeUnit(I) : 0;

Aren't `N` and `NumElems` guaranteed to have the same value here? Both are 
derived from `SL`. The code seems to be written with the expectation that 
`NumElems` corresponds to the number of elements to be iniitialized in the 
target array.



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:1100
+for (size_t I = 0; I != NumElems; ++I) {
+  uint32_t CodePoint = I < N ? SL->getCodeUnit(I) : 0;
+  // TODO(Perf): 0 is implicit; we can just stop iterating at that point.

`CodePoint` should be `CodeUnit` here. `char` and friends all hold code units 
(in some cases, those code units may also constitute a code point).



Comment at: clang/test/AST/Interp/literals.cpp:354-359
+  constexpr char foo[12] = "abc";
+  static_assert(foo[0] == 'a', "");
+  static_assert(foo[1] == 'b', "");
+  static_assert(foo[2] == 'c', "");
+  static_assert(foo[3] == 0, "");
+  static_assert(foo[11] == 0, "");

aaron.ballman wrote:
> I'd like to see some tests for the other encodings, as well as a test with 
> embedded null characters in the literal.
> 
> Testing a string literal that's longer than the array is something we should 
> think about. That code is ill-formed in C++, so I don't think we can add a 
> test for it yet, but it's only a warning in C.
I agree with Aaron's requests. Please also extend the test to include a `char` 
element that would be negative for a `signed` 8-bit `char`. Something like:
  constexpr char foo[12] = "abc\xff";
  ...
  #if defined(__CHAR_UNSIGNED__) || __CHAR_BIT__ > 8
  static_assert(foo[3] == 255, "");
  #else
  static_assert(foo[3] == -1, "");
  #endif

A couple of more tests to add:
- One where the string literal has the same length (including the implicit 
terminator) as the array; to ensure that the implicit terminator is properly 
accounted for.
- One where the target array size is deduced from the string literal; to ensure 
there are no dependencies on an explicit array size.


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

https://reviews.llvm.org/D137488

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


Re: How can Autoconf help with the transition to stricter compilation defaults?

2022-11-15 Thread Aaron Ballman via cfe-commits
On Tue, Nov 15, 2022 at 2:08 PM Paul Eggert  wrote:
>
> On 2022-11-15 06:50, Jonathan Wakely wrote:
> > Could you clarify what you mean, with a concrete example? Surely as
> > long as errors are reported on stderr and the compiler exits with
> > non-zero status, that's an acceptable way to report errors?
>
> Not if the "error" is harmless as far as Autoconf is concerned, which is
> what led to this thread. The concrete example here is that Autoconf
> needs to check whether a function can be linked to (as opposed to
> checking the function's signature). Clang shouldn't get in the way.

What is harmless to autoconf is a critical flaw in another context.

> In lots of places the C standard says behavior is undefined, even though
> the behavior is fine on the current platform for the intended use. It's
> not just the example we're talking about; adding zero to a null pointer
> is another such example.
>
> In such cases it's OK for Clang to warn, but having Clang exit with
> nonzero status is overkill and counterproductive.

I don't know that this is particularly persuasive -- it effectively
boils down to another variant of "I want to rely on a specific
behavior for something that is UB". I don't think Clang can promise
that we're not going to turn more statically-known UB into errors.

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


[PATCH] D136176: Implement support for option 'fexcess-precision'.

2022-11-15 Thread Andy Kaylor via Phabricator via cfe-commits
andrew.w.kaylor added a comment.

Can you update the clang user's manual to describe the behavior of this option? 
The excess precision issue is also mentioned in the clang language extensions 
document 
(https://clang.llvm.org/docs/LanguageExtensions.html#half-precision-floating-point).




Comment at: clang/include/clang/Basic/LangOptions.def:320
 BENIGN_ENUM_LANGOPT(FPEvalMethod, FPEvalMethodKind, 2, FEM_UnsetOnCommandLine, 
"FP type used for floating point arithmetic")
+BENIGN_ENUM_LANGOPT(FPPrecisionMode, FPExcessPrecisionModeKind, 2, 
FPP_Standard, "FP precision used for floating point arithmetic")
 LANGOPT(NoBitFieldTypeAlign , 1, 0, "bit-field type alignment")

A lot of people mix up precision and accuracy, so I think this description is 
likely to be ambiguous. I'd suggest "Intermediate truncation behavior for 
floating point arithmetic"



Comment at: clang/include/clang/Basic/LangOptions.h:300
+FPP_Fast,
+FPP_None
+  };

Is FPP_None somehow the same as fexcess-precision=16? If not, what does it mean?



Comment at: clang/include/clang/Driver/Options.td:1564
+def fexcess_precision_EQ : Joined<["-"], "fexcess-precision=">, 
Group, Flags<[CC1Option]>,
+  HelpText<"Specifies the precision in which this floating-point operations 
will be calculated.">,
+  Values<"standard,fast,16">, NormalizedValuesScope<"LangOptions">,

Again, I think this is ambiguous. My understanding is that the option is more 
about the rules for when intermediate values are truncated to source precision 
than when what precision is prescribed for the calculation. For targets that 
have native support for half precision types, the calculations should always be 
done at source precision and this option will have no effect. It's only when 
the native ISA doesn't support the source precision that this is needed and 
even then we will always perform calculations at the nearest precision to 
source precision that is available, right?



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:2995
+  StringRef Val = A->getValue();
+   if (TC.getTriple().getArch() == llvm::Triple::x86 && Val.equals("16"))
+D.Diag(diag::err_drv_unsupported_opt_for_target)

Why is 16 only supported for x86? Is it only here for gcc compatibility?



Comment at: clang/test/CodeGen/X86/fexcess-precise.c:89
+// CHECK-EXT-NEXT:[[EXT1:%.*]] = fpext half [[TMP1]] to float
+// CHECK-EXT-NEXT:[[MUL:%.*]] = fmul float [[EXT]], [[EXT1]]
+// CHECK-EXT-NEXT:[[TMP2:%.*]] = load half, ptr [[C_ADDR]], align 2

This is not what I'd expect to see. I'd expect the operations to use the half 
type with explicit truncation inserted where needed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136176

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


[PATCH] D137058: [Driver] [Modules] Support -fsave-std-c++-module-file (1/2)

2022-11-15 Thread Ben Boeckel via Phabricator via cfe-commits
ben.boeckel added a comment.

I'm not too concerned with the spelling of the flag myself.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137058

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


[PATCH] D137897: Extend the number of case Sema::CheckForIntOverflow covers

2022-11-15 Thread Shafik Yaghmour via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9332ddfba69c: [Clang] Extend the number of case 
Sema::CheckForIntOverflow covers (authored by shafik).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D137897?vs=475528&id=475553#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137897

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/integer-overflow.cpp


Index: clang/test/Sema/integer-overflow.cpp
===
--- /dev/null
+++ clang/test/Sema/integer-overflow.cpp
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 %s -Wno-unused-value -verify -fsyntax-only
+
+namespace GH58944 {
+struct A {
+  A(unsigned long) ;
+};
+
+A a(1024 * 1024 * 1024 * 1024 * 1024ull); // expected-warning {{overflow in 
expression; result is 0 with type 'int'}}
+
+void f() {
+  new int[1024 * 1024 * 1024 * 1024 * 1024ull]; // expected-warning {{overflow 
in expression; result is 0 with type 'int'}}
+
+  int arr[]{1,2,3};
+  arr[1024 * 1024 * 1024 * 1024 * 1024ull]; // expected-warning {{overflow in 
expression; result is 0 with type 'int'}}
+
+  (int){1024 * 1024 * 1024 * 1024 * 1024}; // expected-warning {{overflow in 
expression; result is 0 with type 'int'}}
+}
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -14660,6 +14660,17 @@
   Exprs.append(Call->arg_begin(), Call->arg_end());
 else if (auto Message = dyn_cast(E))
   Exprs.append(Message->arg_begin(), Message->arg_end());
+else if (auto Construct = dyn_cast(E))
+  Exprs.append(Construct->arg_begin(), Construct->arg_end());
+else if (auto Array = dyn_cast(E))
+  Exprs.push_back(Array->getIdx());
+else if (auto Compound = dyn_cast(E))
+  Exprs.push_back(Compound->getInitializer());
+else if (auto New = dyn_cast(E)) {
+  if (New->isArray())
+if (auto ArraySize = New->getArraySize())
+  Exprs.push_back(ArraySize.value());
+}
   } while (!Exprs.empty());
 }
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -388,6 +388,8 @@
 - Clang now diagnoses use of invalid or reserved module names in a module
   export declaration. Both are diagnosed as an error, but the diagnostic is
   suppressed for use of reserved names in a system header.
+- ``-Winteger-overflow`` will diagnose overflow in more cases. This fixes
+  `Issue 58944 `_.
 
 Non-comprehensive list of changes in this release
 -


Index: clang/test/Sema/integer-overflow.cpp
===
--- /dev/null
+++ clang/test/Sema/integer-overflow.cpp
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 %s -Wno-unused-value -verify -fsyntax-only
+
+namespace GH58944 {
+struct A {
+  A(unsigned long) ;
+};
+
+A a(1024 * 1024 * 1024 * 1024 * 1024ull); // expected-warning {{overflow in expression; result is 0 with type 'int'}}
+
+void f() {
+  new int[1024 * 1024 * 1024 * 1024 * 1024ull]; // expected-warning {{overflow in expression; result is 0 with type 'int'}}
+
+  int arr[]{1,2,3};
+  arr[1024 * 1024 * 1024 * 1024 * 1024ull]; // expected-warning {{overflow in expression; result is 0 with type 'int'}}
+
+  (int){1024 * 1024 * 1024 * 1024 * 1024}; // expected-warning {{overflow in expression; result is 0 with type 'int'}}
+}
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -14660,6 +14660,17 @@
   Exprs.append(Call->arg_begin(), Call->arg_end());
 else if (auto Message = dyn_cast(E))
   Exprs.append(Message->arg_begin(), Message->arg_end());
+else if (auto Construct = dyn_cast(E))
+  Exprs.append(Construct->arg_begin(), Construct->arg_end());
+else if (auto Array = dyn_cast(E))
+  Exprs.push_back(Array->getIdx());
+else if (auto Compound = dyn_cast(E))
+  Exprs.push_back(Compound->getInitializer());
+else if (auto New = dyn_cast(E)) {
+  if (New->isArray())
+if (auto ArraySize = New->getArraySize())
+  Exprs.push_back(ArraySize.value());
+}
   } while (!Exprs.empty());
 }
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -388,6 +388,8 @@
 - Clang now diagnoses use of invalid or reserved module names in a module
   export declaration. Both are diagnosed as an error, but the diagnostic is
   suppressed for use of reserved names i

[clang] 9332ddf - [Clang] Extend the number of case Sema::CheckForIntOverflow covers

2022-11-15 Thread Shafik Yaghmour via cfe-commits

Author: Shafik Yaghmour
Date: 2022-11-15T12:07:03-08:00
New Revision: 9332ddfba69c38f9ceef4175b042fba0bb8e67bb

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

LOG: [Clang] Extend the number of case Sema::CheckForIntOverflow covers

Currently Sema::CheckForIntOverflow misses several case that other compilers
diagnose for overflow in integral constant expressions. This includes the
arguments of a CXXConstructExpr as well as the expressions used in an
ArraySubscriptExpr, CXXNewExpr and CompoundLiteralExpr.

This fixes https://github.com/llvm/llvm-project/issues/58944

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

Added: 
clang/test/Sema/integer-overflow.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaChecking.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 89f1548d86b02..8e32a69f69353 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -388,6 +388,8 @@ Improvements to Clang's diagnostics
 - Clang now diagnoses use of invalid or reserved module names in a module
   export declaration. Both are diagnosed as an error, but the diagnostic is
   suppressed for use of reserved names in a system header.
+- ``-Winteger-overflow`` will diagnose overflow in more cases. This fixes
+  `Issue 58944 `_.
 
 Non-comprehensive list of changes in this release
 -

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index f46a4d3efc64a..5a9c1750d8b32 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -14660,6 +14660,17 @@ void Sema::CheckForIntOverflow (Expr *E) {
   Exprs.append(Call->arg_begin(), Call->arg_end());
 else if (auto Message = dyn_cast(E))
   Exprs.append(Message->arg_begin(), Message->arg_end());
+else if (auto Construct = dyn_cast(E))
+  Exprs.append(Construct->arg_begin(), Construct->arg_end());
+else if (auto Array = dyn_cast(E))
+  Exprs.push_back(Array->getIdx());
+else if (auto Compound = dyn_cast(E))
+  Exprs.push_back(Compound->getInitializer());
+else if (auto New = dyn_cast(E)) {
+  if (New->isArray())
+if (auto ArraySize = New->getArraySize())
+  Exprs.push_back(ArraySize.value());
+}
   } while (!Exprs.empty());
 }
 

diff  --git a/clang/test/Sema/integer-overflow.cpp 
b/clang/test/Sema/integer-overflow.cpp
new file mode 100644
index 0..be9397e3d170e
--- /dev/null
+++ b/clang/test/Sema/integer-overflow.cpp
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 %s -Wno-unused-value -verify -fsyntax-only
+
+namespace GH58944 {
+struct A {
+  A(unsigned long) ;
+};
+
+A a(1024 * 1024 * 1024 * 1024 * 1024ull); // expected-warning {{overflow in 
expression; result is 0 with type 'int'}}
+
+void f() {
+  new int[1024 * 1024 * 1024 * 1024 * 1024ull]; // expected-warning {{overflow 
in expression; result is 0 with type 'int'}}
+
+  int arr[]{1,2,3};
+  arr[1024 * 1024 * 1024 * 1024 * 1024ull]; // expected-warning {{overflow in 
expression; result is 0 with type 'int'}}
+
+  (int){1024 * 1024 * 1024 * 1024 * 1024}; // expected-warning {{overflow in 
expression; result is 0 with type 'int'}}
+}
+}



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


[PATCH] D137948: [clang][dataflow] Add widening API and implement it for built-in boolean model.

2022-11-15 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun accepted this revision.
xazax.hun added a comment.
This revision is now accepted and ready to land.

LGTM, thanks!




Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h:114
   bool isEqualTypeErased(const TypeErasedLattice &E1,
  const TypeErasedLattice &E2) final {
 const Lattice &L1 = llvm::any_cast(E1.Value);

ymandel wrote:
> xazax.hun wrote:
> > Maybe this is another case where we want to mark the whole class `final` 
> > instead of the individual methods? It is fine to address this in a separate 
> > PR.
> Unfortunately not, since this class is used for CRTP.
Whoops, indeed, I missed that.



Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h:135
+  // between overloads.
+  struct Rank1 {};
+  struct Rank0 : Rank1 {};

ymandel wrote:
> xazax.hun wrote:
> > Is there ever a reason to instantiate `Rank1`? If no, should we do 
> > something (like make its ctor private and friends with `Rank0`?). Although 
> > possibly not important enough to worth the hassle.
> No reason to instantiate it that I can see, but since it's a already private 
> to this class, I think it's good enough. But, I just borrowed this from Eric, 
> so I'm not an expert in this pattern. Happy to take suggested improvements.
Let's leave as is.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137948

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


[PATCH] D137948: [clang][dataflow] Add widening API and implement it for built-in boolean model.

2022-11-15 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 475548.
ymandel marked an inline comment as done.
ymandel added a comment.

tweaks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137948

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/include/clang/Analysis/FlowSensitive/DataflowLattice.h
  clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/Value.h
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -9,7 +9,6 @@
 #include "TestingSupport.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
-#include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "clang/Analysis/FlowSensitive/NoopAnalysis.h"
@@ -63,7 +62,7 @@
  LangStandard::Kind Std = LangStandard::lang_cxx17,
  bool ApplyBuiltinTransfer = true,
  llvm::StringRef TargetFun = "target") {
-  runDataflow(Code, Match,
+  runDataflow(Code, std::move(Match),
   {ApplyBuiltinTransfer ? TransferOptions{}
 : llvm::Optional()},
   Std, TargetFun);
@@ -3255,8 +3254,7 @@
 
 TEST(TransferTest, LoopWithAssignmentConverges) {
   std::string Code = R"(
-
-bool &foo();
+bool foo();
 
 void target() {
do {
@@ -3285,9 +3283,45 @@
   });
 }
 
-TEST(TransferTest, LoopWithReferenceAssignmentConverges) {
+TEST(TransferTest, LoopWithStagedAssignments) {
   std::string Code = R"(
+bool foo();
+
+void target() {
+  bool Bar = false;
+  bool Err = false;
+  while (foo()) {
+if (Bar)
+  Err = true;
+Bar = true;
+/*[[p]]*/
+  }
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> &Results,
+ ASTContext &ASTCtx) {
+ASSERT_THAT(Results.keys(), UnorderedElementsAre("p"));
+const Environment &Env = getEnvironmentAtAnnotation(Results, "p");
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+const ValueDecl *ErrDecl = findValueDecl(ASTCtx, "Err");
+ASSERT_THAT(ErrDecl, NotNull());
+
+auto &BarVal = *cast(Env.getValue(*BarDecl, SkipPast::None));
+auto &ErrVal = *cast(Env.getValue(*ErrDecl, SkipPast::None));
+EXPECT_TRUE(Env.flowConditionImplies(BarVal));
+// An unsound analysis, for example only evaluating the loop once, can
+// conclude that `Err` is false. So, we test that this conclusion is not
+// reached.
+EXPECT_FALSE(Env.flowConditionImplies(Env.makeNot(ErrVal)));
+  });
+}
 
+TEST(TransferTest, LoopWithReferenceAssignmentConverges) {
+  std::string Code = R"(
 bool &foo();
 
 void target() {
@@ -3299,9 +,8 @@
   } while (true);
 }
   )";
-  // The key property that we are verifying is implicit in `runDataflow` --
-  // namely, that the analysis succeeds, rather than hitting the maximum number
-  // of iterations.
+  // The key property that we are verifying is that the analysis succeeds,
+  // rather than hitting the maximum number of iterations.
   runDataflow(
   Code,
   [](const llvm::StringMap> &Results,
Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -23,6 +23,7 @@
 #include "clang/Analysis/Analyses/PostOrderCFGView.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/DataflowLattice.h"
 #include "clang/Analysis/FlowSensitive/DataflowWorklist.h"
 #include "clang/Analysis/FlowSensitive/Transfer.h"
 #include "clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h"
@@ -69,6 +70,20 @@
   return BlockPos - Pred.succ_begin();
 }
 
+static bool isLoopHead(const CFGBlock &B) {
+  if (const auto *T = B.getTerminatorStmt())
+switch (T->getStmtClass()) {
+  case Stmt::WhileStmtClass:
+  case Stmt::DoStmtClass:
+  case Stmt::ForStmtClass:
+return true;
+  default:
+return false;
+}
+
+  return false;
+}
+
 // The return type of the visit functions in TerminatorVisitor. The first
 // element represents the terminat

[PATCH] D137948: [clang][dataflow] Add widening API and implement it for built-in boolean model.

2022-11-15 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked an inline comment as done.
ymandel added inline comments.



Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h:114
   bool isEqualTypeErased(const TypeErasedLattice &E1,
  const TypeErasedLattice &E2) final {
 const Lattice &L1 = llvm::any_cast(E1.Value);

xazax.hun wrote:
> Maybe this is another case where we want to mark the whole class `final` 
> instead of the individual methods? It is fine to address this in a separate 
> PR.
Unfortunately not, since this class is used for CRTP.



Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h:135
+  // between overloads.
+  struct Rank1 {};
+  struct Rank0 : Rank1 {};

xazax.hun wrote:
> Is there ever a reason to instantiate `Rank1`? If no, should we do something 
> (like make its ctor private and friends with `Rank0`?). Although possibly not 
> important enough to worth the hassle.
No reason to instantiate it that I can see, but since it's a already private to 
this class, I think it's good enough. But, I just borrowed this from Eric, so 
I'm not an expert in this pattern. Happy to take suggested improvements.



Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h:108
 
+  LatticeJoinEffect widenTypeErased(TypeErasedLattice &Current,
+const TypeErasedLattice &Previous) final {

xazax.hun wrote:
> ymandel wrote:
> > xazax.hun wrote:
> > > I wonder if `LatticeJoinEffect` is the right name if we also use this for 
> > > widening. (Also, are we in the process of removing these?)
> > I had the same thought. How about just `LatticeEffect`? Open to other 
> > suggestions as well. Either way, though, I should update in a separate 
> > patch in case that breaks something unexpected.
> > 
> > As for removing -- yes, we should remove from join, because we never use 
> > it. But, it actually makes sense here.
> `LatticeEffect` sounds good to me.
Added FIXME



Comment at: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp:424-425
+  }
+  if (WidenedEnv.DeclToLoc.size() != PrevEnv.DeclToLoc.size() ||
+  WidenedEnv.ExprToLoc.size() != PrevEnv.ExprToLoc.size() ||
+  WidenedEnv.LocToVal.size() != PrevEnv.LocToVal.size() ||

xazax.hun wrote:
> Isn't some of these tautologically false, as we only read from them?
Well, `Model`'s `widen` function could change them, as much as that seems 
wrong. I suppose we could specify in the API that it shouldn't, or we could 
further restructure the environment so that models don't have access to these 
fields. Either way, if we want these to be assertable, we'll need an API change.

But, more to the point, since I've changed it to update-in-place, we'll now 
also capture any changes that may have occured between Prev and Current. Those 
should converge pretty quickly, because they related to static features of the 
code, so I think this is a reasonable check now.



Comment at: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp:374-378
+  Environment WidenedEnv(*DACtx);
+
+  WidenedEnv.CallStack = CallStack;
+  WidenedEnv.ReturnLoc = ReturnLoc;
+  WidenedEnv.ThisPointeeLoc = ThisPointeeLoc;

xazax.hun wrote:
> ymandel wrote:
> > xazax.hun wrote:
> > > Shouldn't we have a simple copy ctor from PrefEnv that could populate all 
> > > these fields?
> > > 
> > > Also, this makes me wonder if we actually want to move some of these out 
> > > from environment, since these presumably would not change between basic 
> > > blocks.
> > > Shouldn't we have a simple copy ctor from PrefEnv that could populate all 
> > > these fields?
> > We *do* have such a copy constructor. The problem is that it's overkill 
> > because we want to build LocToVal ourselves by point-wise widening of the 
> > elements. For that matter, I wish we could share, rather than copy, 
> > `DeclToLoc` and `ExprToLoc` but I don't know of any way to do that. 
> > Alternatively: is it possible that we can update in place and don't need a 
> > separate `WidenedEnv`?
> > 
> > > Also, this makes me wonder if we actually want to move some of these out 
> > > from environment, since these presumably would not change between basic 
> > > blocks.
> > Agreed. Added a fixme with an associated issue to track.
> > 
> > 
> > For that matter, I wish we could share, rather than copy, DeclToLoc and 
> > ExprToLoc.
> 
> One way to maximize sharing (and making copies free) is to use the immutable 
> datastructures in LLVM: 
> https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/ADT/ImmutableMap.h
> 
> Unfortunately, these have their own costs so it might not be easy to decide 
> when it is worth to use them. The Clang Static Analyzer was designed from the 
> ground up with immutable data structures in mind. 
> 
> On the other hand, I see that you want a more ad-hoc/oppo

  1   2   3   >