[PATCH] D140415: [flang] stack arrays pass

2023-02-07 Thread Jean Perier via Phabricator via cfe-commits
jeanPerier accepted this revision.
jeanPerier added a comment.

I do not have any further comments, thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140415

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


[PATCH] D143472: [clang] Cast the pointer to right type with different address space

2023-02-07 Thread Chunyang, Dai via Phabricator via cfe-commits
cdai2 created this revision.
Herald added subscribers: pengfei, arichardson, Anastasia.
Herald added a project: All.
cdai2 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The source type has OpenCL general address space but dest type does
not have address space. Address space cast is needed for this scenario.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D143472

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/X86/x86-builtins-intrinsic.cl

Index: clang/test/CodeGen/X86/x86-builtins-intrinsic.cl
===
--- /dev/null
+++ clang/test/CodeGen/X86/x86-builtins-intrinsic.cl
@@ -0,0 +1,73 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN:  %clang_cc1 -no-opaque-pointers %s -triple x86_64-pc-linux  \
+// RUN:   -emit-llvm  -O0  -x cl -cl-std=CL2.0 -ffake-address-space-map \
+// RUN:   -target-cpu skx -o - | FileCheck %s
+
+typedef int __v16si __attribute__((__vector_size__(64)));
+
+// CHECK-LABEL: @load(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[__U_ADDR:%.*]] = alloca i16, align 2
+// CHECK-NEXT:[[__P_ADDR:%.*]] = alloca i8 addrspace(4)*, align 8
+// CHECK-NEXT:[[DD:%.*]] = alloca <16 x i32>, align 64
+// CHECK-NEXT:store i16 [[__U:%.*]], i16* [[__U_ADDR]], align 2
+// CHECK-NEXT:store i8 addrspace(4)* [[__P:%.*]], i8 addrspace(4)** [[__P_ADDR]], align 8
+// CHECK-NEXT:store <16 x i32> zeroinitializer, <16 x i32>* [[DD]], align 64
+// CHECK-NEXT:[[TMP0:%.*]] = load i8 addrspace(4)*, i8 addrspace(4)** [[__P_ADDR]], align 8
+// CHECK-NEXT:[[TMP1:%.*]] = bitcast i8 addrspace(4)* [[TMP0]] to i32 addrspace(4)*
+// CHECK-NEXT:[[TMP2:%.*]] = load <16 x i32>, <16 x i32>* [[DD]], align 64
+// CHECK-NEXT:[[TMP3:%.*]] = load i16, i16* [[__U_ADDR]], align 2
+// CHECK-NEXT:[[TMP4:%.*]] = addrspacecast i32 addrspace(4)* [[TMP1]] to <16 x i32>*
+// CHECK-NEXT:[[TMP5:%.*]] = bitcast i16 [[TMP3]] to <16 x i1>
+// CHECK-NEXT:[[TMP6:%.*]] = call <16 x i32> @llvm.masked.load.v16i32.p0v16i32(<16 x i32>* [[TMP4]], i32 1, <16 x i1> [[TMP5]], <16 x i32> [[TMP2]])
+// CHECK-NEXT:ret void
+//
+void load(unsigned short __U, void const *__P)
+{
+  __v16si dd = { 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0 };
+  __builtin_ia32_loaddqusi512_mask(__P, dd, __U);
+}
+
+// CHECK-LABEL: @store(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[__U_ADDR:%.*]] = alloca i16, align 2
+// CHECK-NEXT:[[__P_ADDR:%.*]] = alloca i8 addrspace(4)*, align 8
+// CHECK-NEXT:[[AA:%.*]] = alloca <16 x i32>, align 64
+// CHECK-NEXT:store i16 [[__U:%.*]], i16* [[__U_ADDR]], align 2
+// CHECK-NEXT:store i8 addrspace(4)* [[__P:%.*]], i8 addrspace(4)** [[__P_ADDR]], align 8
+// CHECK-NEXT:store <16 x i32> zeroinitializer, <16 x i32>* [[AA]], align 64
+// CHECK-NEXT:[[TMP0:%.*]] = load i8 addrspace(4)*, i8 addrspace(4)** [[__P_ADDR]], align 8
+// CHECK-NEXT:[[TMP1:%.*]] = bitcast i8 addrspace(4)* [[TMP0]] to i32 addrspace(4)*
+// CHECK-NEXT:[[TMP2:%.*]] = load <16 x i32>, <16 x i32>* [[AA]], align 64
+// CHECK-NEXT:[[TMP3:%.*]] = load i16, i16* [[__U_ADDR]], align 2
+// CHECK-NEXT:[[TMP4:%.*]] = addrspacecast i32 addrspace(4)* [[TMP1]] to <16 x i32>*
+// CHECK-NEXT:[[TMP5:%.*]] = bitcast i16 [[TMP3]] to <16 x i1>
+// CHECK-NEXT:call void @llvm.masked.store.v16i32.p0v16i32(<16 x i32> [[TMP2]], <16 x i32>* [[TMP4]], i32 1, <16 x i1> [[TMP5]])
+// CHECK-NEXT:ret void
+//
+void store(unsigned short __U, void const *__P)
+{
+  __v16si aa = { 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0 };
+  __builtin_ia32_storedqusi512_mask((int*)__P, aa, __U);
+}
+
+// CHECK-LABEL: @foo(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[PLOADSTORE_ADDR:%.*]] = alloca i8 addrspace(4)*, align 8
+// CHECK-NEXT:[[MASK_ADDR:%.*]] = alloca i16, align 2
+// CHECK-NEXT:store i8 addrspace(4)* [[PLOADSTORE:%.*]], i8 addrspace(4)** [[PLOADSTORE_ADDR]], align 8
+// CHECK-NEXT:store i16 [[MASK:%.*]], i16* [[MASK_ADDR]], align 2
+// CHECK-NEXT:[[TMP0:%.*]] = load i16, i16* [[MASK_ADDR]], align 2
+// CHECK-NEXT:[[TMP1:%.*]] = load i8 addrspace(4)*, i8 addrspace(4)** [[PLOADSTORE_ADDR]], align 8
+// CHECK-NEXT:call void @load(i16 noundef zeroext [[TMP0]], i8 addrspace(4)* noundef [[TMP1]]) #[[ATTR4:[0-9]+]]
+// CHECK-NEXT:[[TMP2:%.*]] = load i16, i16* [[MASK_ADDR]], align 2
+// CHECK-NEXT:[[TMP3:%.*]] = load i8 addrspace(4)*, i8 addrspace(4)** [[PLOADSTORE_ADDR]], align 8
+// CHECK-NEXT:call void @store(i16 noundef zeroext [[TMP2]], i8 addrspace(4)* noundef [[TMP3]]) #[[ATTR4]]
+// CHECK-NEXT:ret void
+//
+void  foo(void const *pLoadStore, unsigned short mask)
+{
+  load(mask, pLoadStore);
+  store(mask, pLoadStore);
+}
+
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib

[PATCH] D142890: [clangd] Add config option for fast diagnostics mode

2023-02-07 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 495407.
kadircet added a comment.

- Update tests after discussions in D143096  
to be line-oriented, rather than being directive-oriented.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142890

Files:
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
  clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
  clang-tools-extra/clangd/unittests/PreambleTests.cpp

Index: clang-tools-extra/clangd/unittests/PreambleTests.cpp
===
--- clang-tools-extra/clangd/unittests/PreambleTests.cpp
+++ clang-tools-extra/clangd/unittests/PreambleTests.cpp
@@ -8,9 +8,13 @@
 
 #include "Annotations.h"
 #include "Compiler.h"
+#include "Config.h"
+#include "Diagnostics.h"
 #include "Headers.h"
 #include "Hover.h"
+#include "ParsedAST.h"
 #include "Preamble.h"
+#include "Protocol.h"
 #include "SourceCode.h"
 #include "TestFS.h"
 #include "TestTU.h"
@@ -19,10 +23,12 @@
 #include "clang/Format/Format.h"
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Frontend/PrecompiledPreamble.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/VirtualFileSystem.h"
+#include "llvm/Testing/Support/SupportHelpers.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest-matchers.h"
 #include "gtest/gtest.h"
@@ -32,9 +38,14 @@
 #include 
 
 using testing::Contains;
+using testing::ElementsAre;
 using testing::Field;
+using testing::IsEmpty;
 using testing::Matcher;
 using testing::MatchesRegex;
+using testing::Not;
+using testing::UnorderedElementsAre;
+using testing::UnorderedElementsAreArray;
 
 namespace clang {
 namespace clangd {
@@ -197,9 +208,12 @@
   Field(&Inclusion::FileKind, SrcMgr::CharacteristicKind::C_User;
 }
 
-std::optional createPatchedAST(llvm::StringRef Baseline,
-  llvm::StringRef Modified) {
-  auto BaselinePreamble = TestTU::withCode(Baseline).preamble();
+std::optional
+createPatchedAST(llvm::StringRef Baseline, llvm::StringRef Modified,
+ llvm::StringMap AdditionalFiles = {}) {
+  auto PreambleTU = TestTU::withCode(Baseline);
+  PreambleTU.AdditionalFiles = AdditionalFiles;
+  auto BaselinePreamble = PreambleTU.preamble();
   if (!BaselinePreamble) {
 ADD_FAILURE() << "Failed to build baseline preamble";
 return std::nullopt;
@@ -208,6 +222,7 @@
   IgnoreDiagnostics Diags;
   MockFS FS;
   auto TU = TestTU::withCode(Modified);
+  TU.AdditionalFiles = std::move(AdditionalFiles);
   auto CI = buildCompilerInvocation(TU.inputs(FS), Diags);
   if (!CI) {
 ADD_FAILURE() << "Failed to build compiler invocation";
@@ -586,6 +601,137 @@
 TU.inputs(FS), *BaselinePreamble);
   EXPECT_TRUE(PP.text().empty());
 }
+
+std::vector mainFileDiagRanges(const ParsedAST &AST) {
+  std::vector Result;
+  auto AddRangeIfInMainfile = [&Result](const DiagBase &DB) {
+if (DB.InsideMainFile)
+  Result.emplace_back(DB.Range);
+  };
+  for (auto &D : *AST.getDiagnostics()) {
+AddRangeIfInMainfile(D);
+for (auto &N : D.Notes)
+  AddRangeIfInMainfile(N);
+  }
+  return Result;
+}
+
+TEST(PreamblePatch, DiagnosticsFromMainASTAreInRightPlace) {
+  Config Cfg;
+  Cfg.Diagnostics.AllowStalePreamble = true;
+  WithContextValue WithCfg(Config::Key, std::move(Cfg));
+
+  llvm::StringLiteral BaselinePreamble = "#define FOO\n";
+  {
+// Check with removals from preamble.
+Annotations Code("[[x]];/* error-ok */");
+auto AST = createPatchedAST(BaselinePreamble, Code.code());
+EXPECT_THAT(mainFileDiagRanges(*AST), ElementsAre(Code.range()));
+  }
+  {
+// Check with additions to preamble.
+Annotations Code((BaselinePreamble + R"(
+#define BAR
+[[x]];/* error-ok */)")
+ .str());
+auto AST = createPatchedAST(BaselinePreamble, Code.code());
+EXPECT_THAT(mainFileDiagRanges(*AST), ElementsAre(Code.range()));
+  }
+}
+
+TEST(PreamblePatch, DiagnosticsToPreamble) {
+  Config Cfg;
+  Cfg.Diagnostics.AllowStalePreamble = true;
+  Cfg.Diagnostics.UnusedIncludes = Config::UnusedIncludesPolicy::Strict;
+  WithContextValue WithCfg(Config::Key, std::move(Cfg));
+
+  llvm::StringMap AdditionalFiles;
+  AdditionalFiles["foo.h"] = "#pragma once";
+  AdditionalFiles["bar.h"] = "#pragma once";
+  llvm::StringLiteral BaselinePreamble(R"(
+  // Test comment
+  [[#include "foo.h"]])");
+  {
+// Check with removals from preamble.
+ 

[PATCH] D143093: [clangd] #undef macros inside preamble patch

2023-02-07 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 495409.
kadircet added a comment.

- Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143093

Files:
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/unittests/PreambleTests.cpp


Index: clang-tools-extra/clangd/unittests/PreambleTests.cpp
===
--- clang-tools-extra/clangd/unittests/PreambleTests.cpp
+++ clang-tools-extra/clangd/unittests/PreambleTests.cpp
@@ -272,6 +272,7 @@
 #define BAR
 [[BAR]])cpp",
   R"cpp(#line 0 ".*main.cpp"
+#undef BAR
 #line 2
 #define BAR
 )cpp",
@@ -283,6 +284,7 @@
 
 [[BAR]])cpp",
   R"cpp(#line 0 ".*main.cpp"
+#undef BAR
 #line 2
 #define BAR
 )cpp",
@@ -294,6 +296,7 @@
 BAR
 [[BAR]])cpp",
   R"cpp(#line 0 ".*main.cpp"
+#undef BAR
 #line 3
 #define BAR
 )cpp",
@@ -326,8 +329,10 @@
   )cpp");
 
   llvm::StringLiteral ExpectedPatch(R"cpp(#line 0 ".*main.cpp"
+#undef BAR
 #line 2
 #define BAR\(X, Y\) X Y
+#undef BAR
 #line 3
 #define BAR\(X\) X
 )cpp");
@@ -670,14 +675,13 @@
 llvm::StringLiteral BaselinePreamble = "#define [[FOO]] 1\n";
 Annotations Code(BaselinePreamble);
 // Check ranges for notes.
-Annotations NewCode(("#define [[BARXYZ]] 1\n" + BaselinePreamble +
+Annotations NewCode(("#define BARXYZ 1\n" + BaselinePreamble +
  "void foo();\n#define [[FOO]] 2")
 .str());
 auto AST = createPatchedAST(Code.code(), NewCode.code(), AdditionalFiles);
-// FIXME: We shouldn't be warning for BARXYZ, and pointing at the FOO 
inside
-// the baselinepreamble.
+// FIXME: We should be pointing at the first definition of FOO in NewCode.
 EXPECT_THAT(mainFileDiagRanges(*AST),
-UnorderedElementsAre(NewCode.ranges()[0], 
NewCode.ranges()[2]));
+UnorderedElementsAre(NewCode.ranges()[1]));
   }
 }
 
Index: clang-tools-extra/clangd/Preamble.cpp
===
--- clang-tools-extra/clangd/Preamble.cpp
+++ clang-tools-extra/clangd/Preamble.cpp
@@ -213,6 +213,9 @@
   // Full text that's representing the directive, including the `#`.
   std::string Text;
   unsigned Offset;
+  tok::PPKeywordKind Directive;
+  // Name of the macro being defined in the case of a #define directive.
+  std::string MacroName;
 
   bool operator==(const TextualPPDirective &RHS) const {
 return std::tie(DirectiveLine, Offset, Text) ==
@@ -283,6 +286,8 @@
   return;
 TextualDirectives.emplace_back();
 TextualPPDirective &TD = TextualDirectives.back();
+TD.Directive = tok::pp_define;
+TD.MacroName = MacroNameTok.getIdentifierInfo()->getName().str();
 
 const auto *MI = MD->getMacroInfo();
 TD.Text =
@@ -722,6 +727,10 @@
 // reduce complexity. The former might cause problems because scanning is
 // imprecise and might pick directives from disabled regions.
 for (const auto &TD : ModifiedScan->TextualDirectives) {
+  // Introduce an #undef directive before #defines to suppress any
+  // re-definition warnings.
+  if (TD.Directive == tok::pp_define)
+Patch << "#undef " << TD.MacroName << '\n';
   Patch << "#line " << TD.DirectiveLine << '\n';
   Patch << TD.Text << '\n';
 }


Index: clang-tools-extra/clangd/unittests/PreambleTests.cpp
===
--- clang-tools-extra/clangd/unittests/PreambleTests.cpp
+++ clang-tools-extra/clangd/unittests/PreambleTests.cpp
@@ -272,6 +272,7 @@
 #define BAR
 [[BAR]])cpp",
   R"cpp(#line 0 ".*main.cpp"
+#undef BAR
 #line 2
 #define BAR
 )cpp",
@@ -283,6 +284,7 @@
 
 [[BAR]])cpp",
   R"cpp(#line 0 ".*main.cpp"
+#undef BAR
 #line 2
 #define BAR
 )cpp",
@@ -294,6 +296,7 @@
 BAR
 [[BAR]])cpp",
   R"cpp(#line 0 ".*main.cpp"
+#undef BAR
 #line 3
 #define BAR
 )cpp",
@@ -326,8 +329,10 @@
   )cpp");
 
   llvm::StringLiteral ExpectedPatch(R"cpp(#line 0 ".*main.cpp"
+#undef BAR
 #line 2
 #define BAR\(X, Y\) X Y
+#undef BAR
 #line 3
 #define BAR\(X\) X
 )cpp");
@@ -670,14 +675,13 @@
 llvm::StringLiteral BaselinePreamble = "#define [[FOO]] 1\n";
 Annotations Code(BaselinePreamble);
 // Check ranges for notes.
-Annotations NewCode(("#define [[BARXYZ]] 1\n" + BaselinePreamble +
+Annotations NewCode(("#define BARXYZ 1\n" + BaselinePreamble +
  "void foo();\n#define [[FOO]] 2")
 .str());
 auto AST = createPatchedAST(Code.code(), NewCode.code(), AdditionalFiles);
-// FIXME: We shouldn't be warning for BARXYZ, and pointing at the FOO inside
-// the baselinepreamble.
+// FIXME: We should be pointing at the first

[PATCH] D143095: [clangd] Respect preamble-patch when handling diags

2023-02-07 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 495410.
kadircet added a comment.

- Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143095

Files:
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/unittests/PreambleTests.cpp

Index: clang-tools-extra/clangd/unittests/PreambleTests.cpp
===
--- clang-tools-extra/clangd/unittests/PreambleTests.cpp
+++ clang-tools-extra/clangd/unittests/PreambleTests.cpp
@@ -39,6 +39,7 @@
 
 using testing::Contains;
 using testing::ElementsAre;
+using testing::ElementsAreArray;
 using testing::Field;
 using testing::IsEmpty;
 using testing::Matcher;
@@ -679,9 +680,8 @@
  "void foo();\n#define [[FOO]] 2")
 .str());
 auto AST = createPatchedAST(Code.code(), NewCode.code(), AdditionalFiles);
-// FIXME: We should be pointing at the first definition of FOO in NewCode.
 EXPECT_THAT(mainFileDiagRanges(*AST),
-UnorderedElementsAre(NewCode.ranges()[1]));
+UnorderedElementsAreArray(NewCode.ranges()));
   }
 }
 
Index: clang-tools-extra/clangd/SourceCode.h
===
--- clang-tools-extra/clangd/SourceCode.h
+++ clang-tools-extra/clangd/SourceCode.h
@@ -333,6 +333,10 @@
  (isUppercase(Name[1]) || Name[1] == '_');
 }
 
+/// Translates locations inside preamble patch to their main-file equivalent
+/// using presumed locations. Returns \p Loc if it isn't inside preamble patch.
+SourceLocation translatePreamblePatchLocation(SourceLocation Loc,
+  const SourceManager &SM);
 } // namespace clangd
 } // namespace clang
 #endif
Index: clang-tools-extra/clangd/SourceCode.cpp
===
--- clang-tools-extra/clangd/SourceCode.cpp
+++ clang-tools-extra/clangd/SourceCode.cpp
@@ -1219,5 +1219,30 @@
   return SM.getBufferData(FID).startswith(ProtoHeaderComment);
 }
 
+SourceLocation translatePreamblePatchLocation(SourceLocation Loc,
+  const SourceManager &SM) {
+  // Checks whether \p FileName is a valid spelling of main file.
+  auto IsMainFile = [](llvm::StringRef FileName, const SourceManager &SM) {
+auto FE = SM.getFileManager().getFile(FileName);
+return FE && *FE == SM.getFileEntryForID(SM.getMainFileID());
+  };
+
+  auto DefFile = SM.getFileID(Loc);
+  if (auto FE = SM.getFileEntryRefForID(DefFile)) {
+auto IncludeLoc = SM.getIncludeLoc(DefFile);
+// Preamble patch is included inside the builtin file.
+if (IncludeLoc.isValid() && SM.isWrittenInBuiltinFile(IncludeLoc) &&
+FE->getName().endswith(PreamblePatch::HeaderName)) {
+  auto Presumed = SM.getPresumedLoc(Loc);
+  // Check that line directive is pointing at main file.
+  if (Presumed.isValid() && Presumed.getFileID().isInvalid() &&
+  IsMainFile(Presumed.getFilename(), SM)) {
+Loc = SM.translateLineCol(SM.getMainFileID(), Presumed.getLine(),
+  Presumed.getColumn());
+  }
+}
+  }
+  return Loc;
+}
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/Preamble.h
===
--- clang-tools-extra/clangd/Preamble.h
+++ clang-tools-extra/clangd/Preamble.h
@@ -157,6 +157,8 @@
   /// Whether diagnostics generated using this patch are trustable.
   bool preserveDiagnostics() const;
 
+  static constexpr llvm::StringLiteral HeaderName = "__preamble_patch__.h";
+
 private:
   static PreamblePatch create(llvm::StringRef FileName,
   const ParseInputs &Modified,
@@ -172,11 +174,6 @@
   PreambleBounds ModifiedBounds = {0, false};
 };
 
-/// Translates locations inside preamble patch to their main-file equivalent
-/// using presumed locations. Returns \p Loc if it isn't inside preamble patch.
-SourceLocation translatePreamblePatchLocation(SourceLocation Loc,
-  const SourceManager &SM);
-
 } // namespace clangd
 } // namespace clang
 
Index: clang-tools-extra/clangd/Preamble.cpp
===
--- clang-tools-extra/clangd/Preamble.cpp
+++ clang-tools-extra/clangd/Preamble.cpp
@@ -53,7 +53,6 @@
 namespace clang {
 namespace clangd {
 namespace {
-constexpr llvm::StringLiteral PreamblePatchHeaderName = "__preamble_patch__.h";
 
 bool compileCommandsAreEqual(const tooling::CompileCommand &LHS,
  const tooling::CompileCommand &RHS) {
@@ -381,12 +380,6 @@
   llvm_unreachable("not an include directive");
 }
 
-//

[PATCH] D143096: [clangd] Provide patched diagnostics with preamble patch

2023-02-07 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet marked an inline comment as done.
kadircet added a comment.

In D143096#4099662 , @sammccall wrote:

> It looks like this fixes up the location only of diagnostics attached to 
> particular directives (`#include`) based on some "deep" idea about the 
> content of the directive (the spelled header name).
>
> Some shortcomings:
>
> - This misses diagnostics attached to other directives / continued lines in 
> macro definitions / etc
> - it allows diagnostics to be translated across lines even if the directive 
> spelling changed (in which case the ranges are incorrect since only line 
> numbers are updated.)
> - it requires modelling the directive content in some way that needs to be 
> extended if we find another place that diagnostics can be attached
>
> We discussed the idea of attaching to the text of the line, which seems 
> pretty generic. Needs some handling of duplicate line content but seems like 
> something pretty naive (closest line number with matching content?) would 
> work well, be just as simple and more generic. Any reason this alternative 
> was rejected?

agreed this is better, also somewhat more elegant on the implementation side. 
switching to a line-content based translation, while keeping the logic around 
limiting diagnostics to single lines. as multiple lines seem more wonky and 
unclear how common they're.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143096

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


[PATCH] D143096: [clangd] Provide patched diagnostics with preamble patch

2023-02-07 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 495411.
kadircet added a comment.

- Change to a line based translation logic


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143096

Files:
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/unittests/PreambleTests.cpp

Index: clang-tools-extra/clangd/unittests/PreambleTests.cpp
===
--- clang-tools-extra/clangd/unittests/PreambleTests.cpp
+++ clang-tools-extra/clangd/unittests/PreambleTests.cpp
@@ -696,24 +696,21 @@
 Annotations Code(BaselinePreamble);
 Annotations NewCode(("#define BAR\n" + BaselinePreamble).str());
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: We should point at the NewCode.
-EXPECT_THAT(mainFileDiagRanges(*AST), ElementsAre(Code.range()));
+EXPECT_THAT(mainFileDiagRanges(*AST), ElementsAreArray(NewCode.ranges()));
   }
   {
 // Check with removals from preamble.
 Annotations Code(("#define BAR\n" + BaselinePreamble).str());
 Annotations NewCode(BaselinePreamble);
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: We should point at the NewCode.
-EXPECT_THAT(mainFileDiagRanges(*AST), ElementsAre(Code.range()));
+EXPECT_THAT(mainFileDiagRanges(*AST), ElementsAreArray(NewCode.ranges()));
   }
   {
 // Drop line with diags.
 Annotations Code(BaselinePreamble);
 Annotations NewCode("#define BAR\n#define BAZ\n");
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: No diagnostics.
-EXPECT_THAT(mainFileDiagRanges(*AST), ElementsAre(Code.range()));
+EXPECT_THAT(mainFileDiagRanges(*AST), IsEmpty());
   }
   {
 // Picks closest line in case of multiple alternatives.
@@ -724,16 +721,14 @@
 #define BAR
 #include )");
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: Should point at ranges in NewCode.
-EXPECT_THAT(mainFileDiagRanges(*AST), ElementsAre(Code.range()));
+EXPECT_THAT(mainFileDiagRanges(*AST), ElementsAre(NewCode.range()));
   }
   {
 // Drop diag if line spelling has changed.
 Annotations Code(BaselinePreamble);
 Annotations NewCode(" # include ");
 auto AST = createPatchedAST(Code.code(), NewCode.code());
-// FIXME: No diags.
-EXPECT_THAT(mainFileDiagRanges(*AST), ElementsAre(Code.range()));
+EXPECT_THAT(mainFileDiagRanges(*AST), IsEmpty());
   }
 }
 } // namespace
Index: clang-tools-extra/clangd/Preamble.h
===
--- clang-tools-extra/clangd/Preamble.h
+++ clang-tools-extra/clangd/Preamble.h
@@ -34,6 +34,7 @@
 #include "clang/Frontend/PrecompiledPreamble.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Tooling/CompilationDatabase.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/StringRef.h"
 
 #include 
@@ -157,6 +158,9 @@
   /// Whether diagnostics generated using this patch are trustable.
   bool preserveDiagnostics() const;
 
+  /// Returns diag locations for Modified contents, only contains diags attached
+  /// to an #include or #define directive.
+  llvm::ArrayRef patchedDiags() const { return PatchedDiags; }
   static constexpr llvm::StringLiteral HeaderName = "__preamble_patch__.h";
 
 private:
@@ -168,9 +172,11 @@
   PreamblePatch() = default;
   std::string PatchContents;
   std::string PatchFileName;
-  /// Includes that are present in both \p Baseline and \p Modified. Used for
-  /// patching includes of baseline preamble.
+  // Includes that are present in both \p Baseline and \p Modified. Used for
+  // patching includes of baseline preamble.
   std::vector PreambleIncludes;
+  // Diags that were attached to an #include or a #define directive.
+  std::vector PatchedDiags;
   PreambleBounds ModifiedBounds = {0, false};
 };
 
Index: clang-tools-extra/clangd/Preamble.cpp
===
--- clang-tools-extra/clangd/Preamble.cpp
+++ clang-tools-extra/clangd/Preamble.cpp
@@ -9,6 +9,7 @@
 #include "Preamble.h"
 #include "Compiler.h"
 #include "Config.h"
+#include "Diagnostics.h"
 #include "Headers.h"
 #include "SourceCode.h"
 #include "clang-include-cleaner/Record.h"
@@ -35,6 +36,8 @@
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -43,7 +46,9 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/raw_ostream.h"
-#include 
+#include 
+#include 
+#include 
 #include 
 #include 
 #include 
@@ -306,6 +311,8 @@
 struct ScannedPreamble {
   std::vector Includes;
   std::vector TextualDirectives;
+

[PATCH] D143399: [Tooling/Inclusion] Move the generated mapping .inc file to private places.

2023-02-07 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc751264aa198: [Tooling/Inclusion] Move the generated mapping 
.inc file to private places. (authored by hokein).

Changed prior to commit:
  https://reviews.llvm.org/D143399?vs=495118&id=495412#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143399

Files:
  clang/include/clang/Tooling/Inclusions/CSymbolMap.inc
  clang/include/clang/Tooling/Inclusions/StdSymbolMap.inc
  clang/lib/Tooling/Inclusions/Stdlib/CSymbolMap.inc
  clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
  clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
  utils/bazel/llvm-project-overlay/clang/BUILD.bazel


Index: utils/bazel/llvm-project-overlay/clang/BUILD.bazel
===
--- utils/bazel/llvm-project-overlay/clang/BUILD.bazel
+++ utils/bazel/llvm-project-overlay/clang/BUILD.bazel
@@ -1078,10 +1078,10 @@
 name = "tooling_inclusions",
 srcs = glob([
 "lib/Tooling/Inclusions/**/*.cpp",
+"lib/Tooling/Inclusions/**/*.inc",
 ]),
 hdrs = glob([
 "include/clang/Tooling/Inclusions/**/*.h",
-"include/clang/Tooling/Inclusions/**/*.inc",
 ]),
 deps = [
 ":ast",
Index: clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
===
--- clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
+++ clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
@@ -55,10 +55,10 @@
 #define SYMBOL(Name, NS, Header) ++SymCount;
   switch (Language) {
   case Lang::C:
-#include "clang/Tooling/Inclusions/CSymbolMap.inc"
+#include "CSymbolMap.inc"
 break;
   case Lang::CXX:
-#include "clang/Tooling/Inclusions/StdSymbolMap.inc"
+#include "StdSymbolMap.inc"
 break;
   }
 #undef SYMBOL
@@ -112,10 +112,10 @@
 #define SYMBOL(Name, NS, Header) Add(#NS #Name, strlen(#NS), #Header);
   switch (Language) {
   case Lang::C:
-#include "clang/Tooling/Inclusions/CSymbolMap.inc"
+#include "CSymbolMap.inc"
 break;
   case Lang::CXX:
-#include "clang/Tooling/Inclusions/StdSymbolMap.inc"
+#include "StdSymbolMap.inc"
 break;
   }
 #undef SYMBOL


Index: utils/bazel/llvm-project-overlay/clang/BUILD.bazel
===
--- utils/bazel/llvm-project-overlay/clang/BUILD.bazel
+++ utils/bazel/llvm-project-overlay/clang/BUILD.bazel
@@ -1078,10 +1078,10 @@
 name = "tooling_inclusions",
 srcs = glob([
 "lib/Tooling/Inclusions/**/*.cpp",
+"lib/Tooling/Inclusions/**/*.inc",
 ]),
 hdrs = glob([
 "include/clang/Tooling/Inclusions/**/*.h",
-"include/clang/Tooling/Inclusions/**/*.inc",
 ]),
 deps = [
 ":ast",
Index: clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
===
--- clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
+++ clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
@@ -55,10 +55,10 @@
 #define SYMBOL(Name, NS, Header) ++SymCount;
   switch (Language) {
   case Lang::C:
-#include "clang/Tooling/Inclusions/CSymbolMap.inc"
+#include "CSymbolMap.inc"
 break;
   case Lang::CXX:
-#include "clang/Tooling/Inclusions/StdSymbolMap.inc"
+#include "StdSymbolMap.inc"
 break;
   }
 #undef SYMBOL
@@ -112,10 +112,10 @@
 #define SYMBOL(Name, NS, Header) Add(#NS #Name, strlen(#NS), #Header);
   switch (Language) {
   case Lang::C:
-#include "clang/Tooling/Inclusions/CSymbolMap.inc"
+#include "CSymbolMap.inc"
 break;
   case Lang::CXX:
-#include "clang/Tooling/Inclusions/StdSymbolMap.inc"
+#include "StdSymbolMap.inc"
 break;
   }
 #undef SYMBOL
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D138655: [clang-tidy] Fix `cppcoreguidelines-init-variables` for invalid vardecl

2023-02-07 Thread gehry via Phabricator via cfe-commits
Sockke updated this revision to Diff 495413.
Sockke added a comment.

Rebased.


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

https://reviews.llvm.org/D138655

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s cppcoreguidelines-init-variables %t -- -- 
-fno-delayed-template-parsing -fexceptions
+// RUN: %check_clang_tidy %s cppcoreguidelines-init-variables -fix-errors %t 
-- -- -fno-delayed-template-parsing -fexceptions
 // CHECK-FIXES: {{^}}#include 
 
 // Ensure that function declarations are not changed.
@@ -124,3 +124,13 @@
   Fruit fruit;
   // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: variable 'fruit' is not 
initialized [cppcoreguidelines-init-variables]
 }
+
+void test_clang_diagnostic_error() {
+  int a;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: variable 'a' is not initialized 
[cppcoreguidelines-init-variables]
+  // CHECK-FIXES: {{^}}  int a = 0;{{$}}
+
+  UnknownType b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: error: unknown type name 'UnknownType' 
[clang-diagnostic-error]
+  // CHECK-FIXES-NOT: {{^}}  UnknownType b = 0;{{$}}
+}
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
@@ -59,6 +59,10 @@
   const ASTContext &Context = *Result.Context;
   const SourceManager &Source = Context.getSourceManager();
 
+  // Clang diagnostic error may cause the variable to be an invalid int vardecl
+  if (MatchedDecl->isInvalidDecl())
+return;
+
   // We want to warn about cases where the type name
   // comes from a macro like this:
   //


Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s cppcoreguidelines-init-variables %t -- -- -fno-delayed-template-parsing -fexceptions
+// RUN: %check_clang_tidy %s cppcoreguidelines-init-variables -fix-errors %t -- -- -fno-delayed-template-parsing -fexceptions
 // CHECK-FIXES: {{^}}#include 
 
 // Ensure that function declarations are not changed.
@@ -124,3 +124,13 @@
   Fruit fruit;
   // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: variable 'fruit' is not initialized [cppcoreguidelines-init-variables]
 }
+
+void test_clang_diagnostic_error() {
+  int a;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: variable 'a' is not initialized [cppcoreguidelines-init-variables]
+  // CHECK-FIXES: {{^}}  int a = 0;{{$}}
+
+  UnknownType b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: error: unknown type name 'UnknownType' [clang-diagnostic-error]
+  // CHECK-FIXES-NOT: {{^}}  UnknownType b = 0;{{$}}
+}
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
@@ -59,6 +59,10 @@
   const ASTContext &Context = *Result.Context;
   const SourceManager &Source = Context.getSourceManager();
 
+  // Clang diagnostic error may cause the variable to be an invalid int vardecl
+  if (MatchedDecl->isInvalidDecl())
+return;
+
   // We want to warn about cases where the type name
   // comes from a macro like this:
   //
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 03f5326 - [Tooling/Inclusion] Introduce a human-edit file for C++ std symbols

2023-02-07 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2023-02-07T10:15:50+01:00
New Revision: 03f5326d81665efa7db0b0d3dcd440e2ab632be2

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

LOG: [Tooling/Inclusion] Introduce a human-edit file for C++ std symbols

This file is allowed to be edit by human, and it overlays the generated symbol 
file.
It contains a list of multiple-header symbols.
This patch introduces the file only. Usage will come afterwards.

Reviewed By: kadircet

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

Added: 
clang/include/clang/Tooling/Inclusions/StdSpecialSymbolMap.inc

Modified: 


Removed: 




diff  --git a/clang/include/clang/Tooling/Inclusions/StdSpecialSymbolMap.inc 
b/clang/include/clang/Tooling/Inclusions/StdSpecialSymbolMap.inc
new file mode 100644
index 0..21cadd3c190bc
--- /dev/null
+++ b/clang/include/clang/Tooling/Inclusions/StdSpecialSymbolMap.inc
@@ -0,0 +1,204 @@
+//===-- StdSpecialSymbolMap.inc -*- C++ 
-*-===//
+//
+// This is a hand-curated list for C++ symbols that cannot be parsed/extracted
+// via the include-mapping tool (gen_std.py).
+//
+//===--===//
+
+// Symbols that can be provided by any of the headers, ordered by the header
+// preference.
+// cppreference mentions the  header is an alternative for these 
symbols,
+// but they are not per the standard.
+SYMBOL(consume_header, std::, )
+SYMBOL(generate_header, std::, )
+SYMBOL(little_endian, std::, )
+
+SYMBOL(mbstate_t, std::, )
+SYMBOL(mbstate_t, std::, )
+SYMBOL(size_t, std::, )
+SYMBOL(size_t, std::, )
+SYMBOL(size_t, std::, )
+SYMBOL(size_t, std::, )
+SYMBOL(size_t, std::, )
+SYMBOL(size_t, std::, )
+SYMBOL(size_t, std::, )
+SYMBOL(unwrap_ref_decay, std::, )
+SYMBOL(unwrap_ref_decay, std::, )
+SYMBOL(unwrap_reference, std::, )
+SYMBOL(unwrap_reference, std::, )
+SYMBOL(unwrap_ref_decay_t, std::, )
+SYMBOL(unwrap_ref_decay_t, std::, )
+SYMBOL(wint_t, std::, )
+SYMBOL(wint_t, std::, )
+// C++ [iterator.range 25.7]: In addition to being available via inclusion of
+// the  header, the function templates in [iterator.range] are
+// available when any of the following headers are included: , ,
+// , ... and .
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBO

[PATCH] D143160: [include-mapping] Introduce a human-edit CXXSymbolMapping file

2023-02-07 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG03f5326d8166: [Tooling/Inclusion] Introduce a human-edit 
file for C++ std symbols (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143160

Files:
  clang/include/clang/Tooling/Inclusions/StdSpecialSymbolMap.inc

Index: clang/include/clang/Tooling/Inclusions/StdSpecialSymbolMap.inc
===
--- /dev/null
+++ clang/include/clang/Tooling/Inclusions/StdSpecialSymbolMap.inc
@@ -0,0 +1,204 @@
+//===-- StdSpecialSymbolMap.inc -*- C++ -*-===//
+//
+// This is a hand-curated list for C++ symbols that cannot be parsed/extracted
+// via the include-mapping tool (gen_std.py).
+//
+//===--===//
+
+// Symbols that can be provided by any of the headers, ordered by the header
+// preference.
+// cppreference mentions the  header is an alternative for these symbols,
+// but they are not per the standard.
+SYMBOL(consume_header, std::, )
+SYMBOL(generate_header, std::, )
+SYMBOL(little_endian, std::, )
+
+SYMBOL(mbstate_t, std::, )
+SYMBOL(mbstate_t, std::, )
+SYMBOL(size_t, std::, )
+SYMBOL(size_t, std::, )
+SYMBOL(size_t, std::, )
+SYMBOL(size_t, std::, )
+SYMBOL(size_t, std::, )
+SYMBOL(size_t, std::, )
+SYMBOL(size_t, std::, )
+SYMBOL(unwrap_ref_decay, std::, )
+SYMBOL(unwrap_ref_decay, std::, )
+SYMBOL(unwrap_reference, std::, )
+SYMBOL(unwrap_reference, std::, )
+SYMBOL(unwrap_ref_decay_t, std::, )
+SYMBOL(unwrap_ref_decay_t, std::, )
+SYMBOL(wint_t, std::, )
+SYMBOL(wint_t, std::, )
+// C++ [iterator.range 25.7]: In addition to being available via inclusion of
+// the  header, the function templates in [iterator.range] are
+// available when any of the following headers are included: , ,
+// , ... and .
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(begin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cbegin, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(cend, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crbegin, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(crend, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(data, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(empty, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBOL(end, std::, )
+SYMBOL(rbegin, std::, )
+SYMBOL(rbegin, std::, )
+SYMBOL(rbegin, std::, )
+SYMBOL(rbegin, std::, )
+SYMBOL(rbegin, std::, )
+SYMBOL(rbegin, std::, )
+SYMBOL(rbegin, std::, )
+SYMBOL(rbegin, std::, )
+SYMBOL(rbegin, std::, )
+SYMBOL(rbegin, std::, )
+SYMBOL(rbegin, std::, )
+SYMBOL(rbegin,

[PATCH] D142914: [MLIR][OpenMP] Added OMPIRBuilder support for Target Data directives.

2023-02-07 Thread Alex Zinenko via Phabricator via cfe-commits
ftynse added inline comments.



Comment at: mlir/include/mlir/Target/LLVMIR/Dialect/Utils.h:13
+
+#ifndef MLIR_DIALECT_UTILS_H
+#define MLIR_DIALECT_UTILS_H

This tag is wrong. It should be `MLIR_TARGET_LLVMIR_DIALECT_UTILS_H`.



Comment at: mlir/include/mlir/Target/LLVMIR/Dialect/Utils.h:59
+#endif // MLIR_DIALECT_UTILS_H
\ No newline at end of file


Nit: please add a newline.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142914

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


[PATCH] D142914: [MLIR][OpenMP] Added OMPIRBuilder support for Target Data directives.

2023-02-07 Thread Alex Zinenko via Phabricator via cfe-commits
ftynse added inline comments.



Comment at: mlir/include/mlir/Target/LLVMIR/Dialect/Utils.h:27
+/// Create a constant string location from the MLIR Location information.
+static llvm::Constant *
+createSourceLocStrFromLocation(Location loc, llvm::OpenMPIRBuilder &builder,

It's not great to have static functions in a header. I suppose this is done to 
avoid build dependencies, but it's better to get the dependencies right.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142914

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


[clang] 8a09d60 - [Tooling/Inclusion] Move the StdSpecialSymbolMap.inc to the private lib place.

2023-02-07 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2023-02-07T10:31:41+01:00
New Revision: 8a09d60b71c0f9cac25834553c9eafb1e9bd58d6

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

LOG: [Tooling/Inclusion] Move the StdSpecialSymbolMap.inc to the private lib 
place.

I missed it in c751264aa19865beab12d94db3ea966c6accd428.

Added: 
clang/lib/Tooling/Inclusions/Stdlib/StdSpecialSymbolMap.inc

Modified: 


Removed: 
clang/include/clang/Tooling/Inclusions/StdSpecialSymbolMap.inc



diff  --git a/clang/include/clang/Tooling/Inclusions/StdSpecialSymbolMap.inc 
b/clang/lib/Tooling/Inclusions/Stdlib/StdSpecialSymbolMap.inc
similarity index 100%
rename from clang/include/clang/Tooling/Inclusions/StdSpecialSymbolMap.inc
rename to clang/lib/Tooling/Inclusions/Stdlib/StdSpecialSymbolMap.inc



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


[PATCH] D143478: [RFC][Flang][driver] Try to support `flang -fc1as`

2023-02-07 Thread Shao-Ce SUN via Phabricator via cfe-commits
sunshaoce created this revision.
sunshaoce added reviewers: rovka, kiranchandramohan, Leporacanthicus, 
awarzynski, sscalpone, liaolucy.
Herald added projects: Flang, All.
sunshaoce requested review of this revision.
Herald added subscribers: cfe-commits, jdoerfert, MaskRay.
Herald added a project: clang.

I'm trying to support `flang-new *.s`. Since I'm new to flang, I'm not sure if 
this is the right way to do it.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D143478

Files:
  clang/include/clang/Driver/Options.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Flang.cpp
  clang/lib/Driver/ToolChains/Flang.h
  flang/tools/flang-driver/CMakeLists.txt
  flang/tools/flang-driver/driver.cpp
  flang/tools/flang-driver/fc1as_main.cpp

Index: flang/tools/flang-driver/fc1as_main.cpp
===
--- /dev/null
+++ flang/tools/flang-driver/fc1as_main.cpp
@@ -0,0 +1,672 @@
+//===-- fc1as_main.cpp - Flang Assembler  -===//
+//
+// 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 is the entry point to the flang -fc1as functionality, which implements
+// the direct interface to the LLVM MC based assembler.
+//
+//===--===//
+
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Driver/DriverDiagnostic.h"
+#include "clang/Driver/Options.h"
+#include "clang/Frontend/FrontendDiagnostic.h"
+#include "clang/Frontend/TextDiagnosticPrinter.h"
+#include "clang/Frontend/Utils.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringSwitch.h"
+#include "llvm/ADT/Triple.h"
+#include "llvm/IR/DataLayout.h"
+#include "llvm/MC/MCAsmBackend.h"
+#include "llvm/MC/MCAsmInfo.h"
+#include "llvm/MC/MCCodeEmitter.h"
+#include "llvm/MC/MCContext.h"
+#include "llvm/MC/MCInstrInfo.h"
+#include "llvm/MC/MCObjectFileInfo.h"
+#include "llvm/MC/MCObjectWriter.h"
+#include "llvm/MC/MCParser/MCAsmParser.h"
+#include "llvm/MC/MCParser/MCTargetAsmParser.h"
+#include "llvm/MC/MCRegisterInfo.h"
+#include "llvm/MC/MCSectionMachO.h"
+#include "llvm/MC/MCStreamer.h"
+#include "llvm/MC/MCSubtargetInfo.h"
+#include "llvm/MC/MCTargetOptions.h"
+#include "llvm/MC/TargetRegistry.h"
+#include "llvm/Option/Arg.h"
+#include "llvm/Option/ArgList.h"
+#include "llvm/Option/OptTable.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/FormattedStream.h"
+#include "llvm/Support/Host.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Process.h"
+#include "llvm/Support/Signals.h"
+#include "llvm/Support/SourceMgr.h"
+#include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/Timer.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+#include 
+#include 
+using namespace clang;
+using namespace clang::driver;
+using namespace clang::driver::options;
+using namespace llvm;
+using namespace llvm::opt;
+
+namespace {
+
+/// Helper class for representing a single invocation of the assembler.
+struct AssemblerInvocation {
+  /// @name Target Options
+  /// @{
+
+  /// The name of the target triple to assemble for.
+  std::string triple;
+
+  /// If given, the name of the target CPU to determine which instructions
+  /// are legal.
+  std::string cpu;
+
+  /// The list of target specific features to enable or disable -- this should
+  /// be a list of strings starting with '+' or '-'.
+  std::vector features;
+
+  /// The list of symbol definitions.
+  std::vector symbolDefs;
+
+  /// @}
+  /// @name Language Options
+  /// @{
+
+  std::vector includePaths;
+  unsigned noInitialTextSection : 1;
+  unsigned saveTemporaryLabels : 1;
+  unsigned genDwarfForAssembly : 1;
+  unsigned relaxElfRelocations : 1;
+  unsigned dwarf64 : 1;
+  unsigned dwarfVersion;
+  std::string dwarfDebugFlags;
+  std::string dwarfDebugProducer;
+  std::string debugCompilationDir;
+  std::map debugPrefixMap;
+  llvm::DebugCompressionType compressDebugSections =
+  llvm::DebugCompressionType::None;
+  std::string mainFileName;
+  std::string splitDwarfOutput;
+
+  /// @}
+  /// @name Frontend Options
+  /// @{
+
+  std::string inputFile;
+  std::vector llvmArgs;
+  std::string outputPath;
+  enum FileType {
+FT_Asm,  ///< Assembly (.s) output, transliterate mode.
+FT_Null, ///< No output, for timing purposes.
+FT_Obj   ///< Object file output.
+  };
+  FileType outputType;
+  unsigned showHelp : 1;
+  unsigned showVersion : 1;
+
+  /// @}
+  /// @name Transliterate Options
+  /// @{
+
+

[PATCH] D143478: [RFC][Flang][driver] Try to support `flang -fc1as`

2023-02-07 Thread Valentin Clement via Phabricator via cfe-commits
clementval added a comment.

There should be some tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143478

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


[PATCH] D143411: [NFC][clang] Fix static analyzer concern about uninitialized variable

2023-02-07 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8681797e595d: [NFC][clang] Fix static analyzer concern about 
uninitialized variable (authored by Fznamznon).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143411

Files:
  clang/lib/Sema/AnalysisBasedWarnings.cpp


Index: clang/lib/Sema/AnalysisBasedWarnings.cpp
===
--- clang/lib/Sema/AnalysisBasedWarnings.cpp
+++ clang/lib/Sema/AnalysisBasedWarnings.cpp
@@ -574,6 +574,7 @@
 D.diag_AlwaysFallThrough_HasNoReturn = 0;
 D.diag_AlwaysFallThrough_ReturnsNonVoid =
 diag::warn_falloff_nonvoid_coroutine;
+D.diag_NeverFallThroughOrReturn = 0;
 D.funMode = Coroutine;
 return D;
   }


Index: clang/lib/Sema/AnalysisBasedWarnings.cpp
===
--- clang/lib/Sema/AnalysisBasedWarnings.cpp
+++ clang/lib/Sema/AnalysisBasedWarnings.cpp
@@ -574,6 +574,7 @@
 D.diag_AlwaysFallThrough_HasNoReturn = 0;
 D.diag_AlwaysFallThrough_ReturnsNonVoid =
 diag::warn_falloff_nonvoid_coroutine;
+D.diag_NeverFallThroughOrReturn = 0;
 D.funMode = Coroutine;
 return D;
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 8681797 - [NFC][clang] Fix static analyzer concern about uninitialized variable

2023-02-07 Thread Mariya Podchishchaeva via cfe-commits

Author: Mariya Podchishchaeva
Date: 2023-02-07T04:40:44-05:00
New Revision: 8681797e595d52f0ee6710172b64aafd29b67ad1

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

LOG: [NFC][clang] Fix static analyzer concern about uninitialized variable

Reviewed By: xazax.hun

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

Added: 


Modified: 
clang/lib/Sema/AnalysisBasedWarnings.cpp

Removed: 




diff  --git a/clang/lib/Sema/AnalysisBasedWarnings.cpp 
b/clang/lib/Sema/AnalysisBasedWarnings.cpp
index f079471f9084..b6dce0808705 100644
--- a/clang/lib/Sema/AnalysisBasedWarnings.cpp
+++ b/clang/lib/Sema/AnalysisBasedWarnings.cpp
@@ -574,6 +574,7 @@ struct CheckFallThroughDiagnostics {
 D.diag_AlwaysFallThrough_HasNoReturn = 0;
 D.diag_AlwaysFallThrough_ReturnsNonVoid =
 diag::warn_falloff_nonvoid_coroutine;
+D.diag_NeverFallThroughOrReturn = 0;
 D.funMode = Coroutine;
 return D;
   }



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


[PATCH] D143479: [Clang] Emit error when caller cannot meet target feature requirement from always-inlining callee

2023-02-07 Thread Qiu Chaofan via Phabricator via cfe-commits
qiucf created this revision.
qiucf added reviewers: echristo, LiuChen3, erichkeane, GBuella.
Herald added subscribers: steven.zhang, kbarton, nemanjai.
Herald added a project: All.
qiucf requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Currently clang emits error when both `always_inline` and `target` attributes 
are on callee, but caller doesn't have some feature:

  // RUN: %clang_cc1 -triple powerpc64le -target-feature -htm
  
  __attribute__((always_inline))
  __attribute__((target("htm")))
  void foo() {}
  
  void bar() { foo(); }
  
  // error: always_inline function 'foo' requires target feature 'htm', but 
would be inlined into function 'bar' that is compiled without support for 'htm'

But when the `always_inline` attribute is on caller, clang has no diagnose. If 
any builtin or inline asm really need the feature, backend will crash.

  // RUN: %clang_cc1 -triple powerpc64le -target-feature +htm
  
  __attribute__((always_inline))
  void foo() {
// No error, but uncommenting line below triggers ICE
// __builtin_ttest();
  }
  
  __attribute__((target("no-htm")))
  void bar() { foo(); }

This patch will fix the second case.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D143479

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/test/Sema/ppc-attr-target-inline.c


Index: clang/test/Sema/ppc-attr-target-inline.c
===
--- /dev/null
+++ clang/test/Sema/ppc-attr-target-inline.c
@@ -0,0 +1,14 @@
+// REQUIRES: powerpc-registered-target
+// RUN: %clang_cc1 -triple powerpc64le -target-feature +htm -fsyntax-only 
-emit-llvm %s -verify
+
+__attribute__((always_inline))
+int test1(int *x) {
+  *x = __builtin_ttest();
+  return *x;
+}
+
+__attribute__((target("no-htm")))
+int test2(int *x) {
+  *x = test1(x); // expected-error {{always_inline function 'test1' requires 
target feature 'htm', but would be inlined into function 'test2' that is 
compiled without support for 'htm'}}
+  return 0;
+}
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -2611,6 +2611,16 @@
 }))
   CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
   << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
+  } else if (!FD->isMultiVersion() && FD->hasAttr()) {
+llvm::StringMap CalleeFeatureMap;
+CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
+
+for (const auto &F : CalleeFeatureMap) {
+  if (F.getValue() && (!CallerFeatureMap.lookup(F.getKey()) ||
+   !CallerFeatureMap.find(F.getKey())->getValue()))
+CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
+<< FD->getDeclName() << TargetDecl->getDeclName() << F.getKey();
+}
   }
 }
 
Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -4761,7 +4761,8 @@
 // the proper cpu features (and it won't cause code generation issues due 
to
 // function based code generation).
 if (TargetDecl->hasAttr() &&
-TargetDecl->hasAttr())
+(TargetDecl->hasAttr() ||
+ (CurFuncDecl && CurFuncDecl->hasAttr(
   checkTargetFeatures(Loc, FD);
 
 // Some architectures (such as x86-64) have the ABI changed based on


Index: clang/test/Sema/ppc-attr-target-inline.c
===
--- /dev/null
+++ clang/test/Sema/ppc-attr-target-inline.c
@@ -0,0 +1,14 @@
+// REQUIRES: powerpc-registered-target
+// RUN: %clang_cc1 -triple powerpc64le -target-feature +htm -fsyntax-only -emit-llvm %s -verify
+
+__attribute__((always_inline))
+int test1(int *x) {
+  *x = __builtin_ttest();
+  return *x;
+}
+
+__attribute__((target("no-htm")))
+int test2(int *x) {
+  *x = test1(x); // expected-error {{always_inline function 'test1' requires target feature 'htm', but would be inlined into function 'test2' that is compiled without support for 'htm'}}
+  return 0;
+}
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -2611,6 +2611,16 @@
 }))
   CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
   << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
+  } else if (!FD->isMultiVersion() && FD->hasAttr()) {
+llvm::StringMap CalleeFeatureMap;
+CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
+
+for (const auto &F : CalleeFeatureMap) {
+  if (F.getValue() && (!CallerFeatureMap.lookup(F.getKey()) ||
+   !CallerFeatureMap.find

[PATCH] D143436: [clangd] Apply standard adaptors to CDBs pushed from LSP

2023-02-07 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin updated this revision to Diff 495431.
DmitryPolukhin added a comment.

Fix clang-format sources


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143436

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
  clang-tools-extra/clangd/GlobalCompilationDatabase.h
  clang-tools-extra/clangd/test/did-change-configuration-params.test
  clang/include/clang/Tooling/CompilationDatabase.h
  clang/lib/Tooling/CompilationDatabase.cpp

Index: clang/lib/Tooling/CompilationDatabase.cpp
===
--- clang/lib/Tooling/CompilationDatabase.cpp
+++ clang/lib/Tooling/CompilationDatabase.cpp
@@ -378,6 +378,11 @@
StringRef());
 }
 
+FixedCompilationDatabase::FixedCompilationDatabase(
+CompileCommand &&CommandLine) {
+  CompileCommands.emplace_back(CommandLine);
+}
+
 std::vector
 FixedCompilationDatabase::getCompileCommands(StringRef FilePath) const {
   std::vector Result(CompileCommands);
Index: clang/include/clang/Tooling/CompilationDatabase.h
===
--- clang/include/clang/Tooling/CompilationDatabase.h
+++ clang/include/clang/Tooling/CompilationDatabase.h
@@ -199,6 +199,9 @@
   FixedCompilationDatabase(const Twine &Directory,
ArrayRef CommandLine);
 
+  /// Constructs a compilation data base from passed CompileCommand.
+  FixedCompilationDatabase(CompileCommand &&CommandLine);
+
   /// Returns the given compile command.
   ///
   /// Will always return a vector with one entry that contains the directory
Index: clang-tools-extra/clangd/test/did-change-configuration-params.test
===
--- clang-tools-extra/clangd/test/did-change-configuration-params.test
+++ clang-tools-extra/clangd/test/did-change-configuration-params.test
@@ -45,13 +45,17 @@
 # CHECK-NEXT:"uri": "file://{{.*}}/foo.c",
 # CHECK-NEXT:"version": 0
 # CHECK-NEXT:  }
+---
+{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"compilationDatabaseChanges":{"/clangd-test/foo.c": {"workingDirectory":"/clangd-test2", "compilationCommand": ["riscv64-unknown-elf-gcc", "-c", "foo.c", "-Wall", "-Werror"]}
+#  CHECK:  "method": "textDocument/publishDiagnostics",
 #
 # ERR: ASTWorker building file {{.*}}foo.c version 0 with command
 # ERR: [{{.*}}clangd-test2]
 # ERR: clang -c -Wall -Werror {{.*}} -- {{.*}}foo.c
+# ERR: ASTWorker building file {{.*}}foo.c version 0 with command
+# ERR: [{{.*}}clangd-test2]
+# ERR: riscv64-unknown-elf-gcc --target=riscv64-unknown-elf -c -Wall -Werror {{.*}} -- {{.*}}foo.c
 ---
 {"jsonrpc":"2.0","id":5,"method":"shutdown"}
 ---
 {"jsonrpc":"2.0","method":"exit"}
-
-
Index: clang-tools-extra/clangd/GlobalCompilationDatabase.h
===
--- clang-tools-extra/clangd/GlobalCompilationDatabase.h
+++ clang-tools-extra/clangd/GlobalCompilationDatabase.h
@@ -169,6 +169,11 @@
 SystemIncludeExtractorFn
 getSystemIncludeExtractor(llvm::ArrayRef QueryDriverGlobs);
 
+/// Creates standard set of CDB adaptors arround passed CDB.
+std::unique_ptr
+wrapCDBInExpandingAndInferingAdaptors(
+std::unique_ptr &&CDB);
+
 /// Wraps another compilation database, and supports overriding the commands
 /// using an in-memory mapping.
 class OverlayCDB : public DelegatingCDB {
Index: clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
===
--- clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
+++ clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
@@ -239,20 +239,25 @@
   return {LoadResult::FoundNewData, std::move(*Buf)};
 }
 
+std::unique_ptr
+wrapCDBInExpandingAndInferingAdaptors(
+std::unique_ptr &&CDB) {
+  // FS used for expanding response files.
+  // FIXME: ExpandResponseFilesDatabase appears not to provide the usual
+  // thread-safety guarantees, as the access to FS is not locked!
+  // For now, use the real FS, which is known to be threadsafe (if we don't
+  // use/change working directory, which ExpandResponseFilesDatabase doesn't).
+  auto FS = llvm::vfs::getRealFileSystem();
+  return tooling::inferTargetAndDriverMode(tooling::inferMissingCompileCommands(
+  expandResponseFiles(std::move(CDB), std::move(FS;
+}
+
 // Adapt CDB-loading functions to a common interface for DirectoryCache::load().
 static std::unique_ptr
 parseJSON(PathRef Path, llvm::StringRef Data, std::string &Error) {
   if (auto CDB = tooling::JSONCompilationDatabase::loadFromBuffer(
   Data, Error, tooling::JSONCommandLineSyntax::AutoDetect)) {
-// FS used for expanding response files.
-// FIXME: ExpandResponseFilesDatabase appears not to provide the usual
-// thread-safety guarantees

[PATCH] D143478: [RFC][Flang][driver] Try to support `flang -fc1as`

2023-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Thanks for working on this! Before diving any deeper

- Does LLVM Flang require `flang-new -fc1as`?
- If yes, why can't Flang and Clang share it?

For better visibility, I suggest raising these questions on Discourse 
. As this could potentially affect both Flang and 
Clang, could you post in one of the generic sections? Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143478

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


[PATCH] D143480: [clang][Interp] Fix derived-to-base casts for >1 levels

2023-02-07 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: aaron.ballman, erichkeane, tahonermann, shafik.
Herald added a project: All.
tbaeder requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

  The GetPtrBasePop op we were using only works for direct base classes.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D143480

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/test/AST/Interp/records.cpp


Index: clang/test/AST/Interp/records.cpp
===
--- clang/test/AST/Interp/records.cpp
+++ clang/test/AST/Interp/records.cpp
@@ -258,6 +258,10 @@
   class _B : public _A {};
   class _C : public _B {};
   constexpr _C c{12};
+
+  // Cast from A to C.
+  constexpr _A a = c;
+  static_assert(a.a == 12);
 };
 #endif
 
Index: clang/lib/AST/Interp/ByteCodeExprGen.h
===
--- clang/lib/AST/Interp/ByteCodeExprGen.h
+++ clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -263,6 +263,8 @@
   }
 
   bool emitRecordDestruction(const Descriptor *Desc);
+  bool emitDerivedToBaseCasts(const RecordType *DerivedType,
+  const RecordType *BaseType, const Expr *E);
 
 protected:
   /// Variable to storage mapping.
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -88,15 +88,8 @@
 if (!this->visit(SubExpr))
   return false;
 
-const CXXRecordDecl *FromDecl = getRecordDecl(SubExpr);
-assert(FromDecl);
-const CXXRecordDecl *ToDecl = getRecordDecl(CE);
-assert(ToDecl);
-const Record *R = getRecord(FromDecl);
-const Record::Base *ToBase = R->getBase(ToDecl);
-assert(ToBase);
-
-return this->emitGetPtrBasePop(ToBase->Offset, CE);
+return this->emitDerivedToBaseCasts(getRecordTy(SubExpr->getType()),
+getRecordTy(CE->getType()), CE);
   }
 
   case CK_FloatingCast: {
@@ -1949,6 +1942,38 @@
 C->emitDestruction();
 }
 
+template 
+bool ByteCodeExprGen::emitDerivedToBaseCasts(
+const RecordType *DerivedType, const RecordType *BaseType, const Expr *E) {
+  // Pointer of derived type is already on the stack.
+  const CXXRecordDecl *FinalDecl = cast(BaseType->getDecl());
+  const RecordDecl *CurDecl = DerivedType->getDecl();
+  const Record *CurRecord = getRecord(CurDecl);
+  assert(CurDecl && FinalDecl);
+  for (;;) {
+assert(CurRecord->getNumBases() > 0);
+// One level up
+for (const Record::Base &B : CurRecord->bases()) {
+  const CXXRecordDecl *BaseDecl = cast(B.Decl);
+
+  if (BaseDecl == FinalDecl || BaseDecl->isDerivedFrom(FinalDecl)) {
+// This decl will lead us to the final decl, so emit a base cast.
+if (!this->emitGetPtrBasePop(B.Offset, E))
+  return false;
+
+CurRecord = B.R;
+CurDecl = BaseDecl;
+break;
+  }
+}
+if (CurDecl == FinalDecl)
+  return true;
+  }
+
+  llvm_unreachable("Couldn't find the base class?");
+  return false;
+}
+
 /// When calling this, we have a pointer of the local-to-destroy
 /// on the stack.
 /// Emit destruction of record types (or arrays of record types).


Index: clang/test/AST/Interp/records.cpp
===
--- clang/test/AST/Interp/records.cpp
+++ clang/test/AST/Interp/records.cpp
@@ -258,6 +258,10 @@
   class _B : public _A {};
   class _C : public _B {};
   constexpr _C c{12};
+
+  // Cast from A to C.
+  constexpr _A a = c;
+  static_assert(a.a == 12);
 };
 #endif
 
Index: clang/lib/AST/Interp/ByteCodeExprGen.h
===
--- clang/lib/AST/Interp/ByteCodeExprGen.h
+++ clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -263,6 +263,8 @@
   }
 
   bool emitRecordDestruction(const Descriptor *Desc);
+  bool emitDerivedToBaseCasts(const RecordType *DerivedType,
+  const RecordType *BaseType, const Expr *E);
 
 protected:
   /// Variable to storage mapping.
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -88,15 +88,8 @@
 if (!this->visit(SubExpr))
   return false;
 
-const CXXRecordDecl *FromDecl = getRecordDecl(SubExpr);
-assert(FromDecl);
-const CXXRecordDecl *ToDecl = getRecordDecl(CE);
-assert(ToDecl);
-const Record *R = getRecord(FromDecl);
-const Record::Base *ToBase = R->getBase(ToDecl);
-assert(ToBase);
-
-return this->emitGetPtrBasePop(ToBase->Offset, CE);
+return this->emitDerivedToBaseCasts(getRecordTy(SubExpr->getType()),
+getRecordT

[PATCH] D143482: [SanitizerBinaryMetadata] Optimize used space for features and UAR stack args

2023-02-07 Thread Marco Elver via Phabricator via cfe-commits
melver created this revision.
melver added a reviewer: dvyukov.
Herald added subscribers: Enna1, hiraditya.
Herald added a project: All.
melver requested review of this revision.
Herald added projects: clang, Sanitizers, LLVM.
Herald added subscribers: llvm-commits, Sanitizers, cfe-commits.

Optimize the encoding of "covered" metadata by:

1. Reducing feature mask from 4 bytes to 1 byte (needs increase once we reach 
more than 8 features).
2. Only emitting UAR stack args size if it is non-zero, saving 4 bytes in the 
common case.

One caveat is that the emitted metadata for function PC (offset), size,
and UAR size (if enabled) are no longer aligned to 4 bytes.

SanitizerBinaryMetadata version base is increased to 2, since the change
is backwards incompatible.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D143482

Files:
  clang/test/CodeGen/sanitize-metadata.c
  compiler-rt/test/metadata/common.h
  compiler-rt/test/metadata/covered.cpp
  compiler-rt/test/metadata/lit.site.cfg.py.in
  compiler-rt/test/metadata/uar.cpp
  llvm/include/llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h
  llvm/lib/CodeGen/SanitizerBinaryMetadata.cpp
  llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
  llvm/test/Instrumentation/SanitizerBinaryMetadata/atomics.ll

Index: llvm/test/Instrumentation/SanitizerBinaryMetadata/atomics.ll
===
--- llvm/test/Instrumentation/SanitizerBinaryMetadata/atomics.ll
+++ llvm/test/Instrumentation/SanitizerBinaryMetadata/atomics.ll
@@ -2039,7 +2039,7 @@
 ; CHECK-DAG: entry:
 ; CHECK-NEXT:  br i1 icmp ne (ptr @__sanitizer_metadata_atomics_add, ptr null), label %callfunc, label %ret
 ; CHECK-DAG: callfunc:
-; CHECK-NEXT:  call void @__sanitizer_metadata_atomics_add(i32 1, ptr @__start_sanmd_atomics, ptr @__stop_sanmd_atomics)
+; CHECK-NEXT:  call void @__sanitizer_metadata_atomics_add(i32 2, ptr @__start_sanmd_atomics, ptr @__stop_sanmd_atomics)
 ; CHECK-NEXT:  br label %ret
 ; CHECK-DAG: ret:
 ; CHECK-NEXT:  ret void
@@ -2048,7 +2048,7 @@
 ; CHECK-DAG: entry:
 ; CHECK-NEXT:  br i1 icmp ne (ptr @__sanitizer_metadata_atomics_del, ptr null), label %callfunc, label %ret
 ; CHECK-DAG: callfunc:
-; CHECK-NEXT:  call void @__sanitizer_metadata_atomics_del(i32 1, ptr @__start_sanmd_atomics, ptr @__stop_sanmd_atomics)
+; CHECK-NEXT:  call void @__sanitizer_metadata_atomics_del(i32 2, ptr @__start_sanmd_atomics, ptr @__stop_sanmd_atomics)
 ; CHECK-NEXT:  br label %ret
 ; CHECK-DAG: ret:
 ; CHECK-NEXT:  ret void
@@ -2057,7 +2057,7 @@
 ; CHECK-DAG: entry:
 ; CHECK-NEXT:  br i1 icmp ne (ptr @__sanitizer_metadata_covered_add, ptr null), label %callfunc, label %ret
 ; CHECK-DAG: callfunc:
-; CHECK-NEXT:  call void @__sanitizer_metadata_covered_add(i32 1, ptr @__start_sanmd_covered, ptr @__stop_sanmd_covered)
+; CHECK-NEXT:  call void @__sanitizer_metadata_covered_add(i32 2, ptr @__start_sanmd_covered, ptr @__stop_sanmd_covered)
 ; CHECK-NEXT:  br label %ret
 ; CHECK-DAG: ret:
 ; CHECK-NEXT:  ret void
@@ -2066,11 +2066,11 @@
 ; CHECK-DAG: entry:
 ; CHECK-NEXT:  br i1 icmp ne (ptr @__sanitizer_metadata_covered_del, ptr null), label %callfunc, label %ret
 ; CHECK-DAG: callfunc:
-; CHECK-NEXT:  call void @__sanitizer_metadata_covered_del(i32 1, ptr @__start_sanmd_covered, ptr @__stop_sanmd_covered)
+; CHECK-NEXT:  call void @__sanitizer_metadata_covered_del(i32 2, ptr @__start_sanmd_covered, ptr @__stop_sanmd_covered)
 ; CHECK-NEXT:  br label %ret
 ; CHECK-DAG: ret:
 ; CHECK-NEXT:  ret void
 
 ; CHECK: !0 = !{!"sanmd_covered", !1}
-; CHECK: !1 = !{i32 1}
+; CHECK: !1 = !{i8 1}
 ; CHECK: !2 = !{!"sanmd_atomics"}
Index: llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
===
--- llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
+++ llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
@@ -43,6 +43,7 @@
 
 #include 
 #include 
+#include 
 
 using namespace llvm;
 
@@ -52,7 +53,7 @@
 
 //===--- Constants ===//
 
-constexpr uint32_t kVersionBase = 1;// occupies lower 16 bits
+constexpr uint32_t kVersionBase = 2;// occupies lower 16 bits
 constexpr uint32_t kVersionPtrSizeRel = (1u << 16); // offsets are pointer-sized
 constexpr int kCtorDtorPriority = 2;
 
@@ -266,9 +267,10 @@
 const auto *MI = &MetadataInfo::Covered;
 MIS.insert(MI);
 const StringRef Section = getSectionName(MI->SectionSuffix);
-// The feature mask will be placed after the size (32 bit) of the function,
-// so in total one covered entry will use `sizeof(void*) + 4 + 4`.
-Constant *CFM = IRB.getInt32(FeatureMask);
+// The feature mask will be placed after the size of the function.
+assert(FeatureMask <= std::numeric_limits::max() &&
+   "Increase feature mask bytes and bump version");
+Constant *CFM = IRB.getInt8(FeatureMask)

[PATCH] D143484: [SanitizerBinaryMetadata] Emit constants as ULEB128

2023-02-07 Thread Marco Elver via Phabricator via cfe-commits
melver created this revision.
melver added a reviewer: dvyukov.
Herald added subscribers: Enna1, pengfei, hiraditya.
Herald added a project: All.
melver requested review of this revision.
Herald added projects: clang, Sanitizers, LLVM.
Herald added subscribers: llvm-commits, Sanitizers, cfe-commits.

Emit all constant integers produced by SanitizerBinaryMetadata as
ULEB128 to further reduce binary space used. Increasing the version is
not necessary given this change depends on (and will land) along with
the bump to v2.

To support this, the !pcsections metadata format is extended to allow
for per-section options, encoded in the first MD operator which must
always be a string and contain the section: "!".

Depends on D143482 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D143484

Files:
  clang/test/CodeGen/sanitize-metadata.c
  compiler-rt/test/metadata/common.h
  llvm/docs/PCSectionsMetadata.rst
  llvm/include/llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h
  llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
  llvm/lib/CodeGen/SanitizerBinaryMetadata.cpp
  llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
  llvm/test/CodeGen/X86/pcsections.ll
  llvm/test/Instrumentation/SanitizerBinaryMetadata/atomics.ll

Index: llvm/test/Instrumentation/SanitizerBinaryMetadata/atomics.ll
===
--- llvm/test/Instrumentation/SanitizerBinaryMetadata/atomics.ll
+++ llvm/test/Instrumentation/SanitizerBinaryMetadata/atomics.ll
@@ -2071,6 +2071,6 @@
 ; CHECK-DAG: ret:
 ; CHECK-NEXT:  ret void
 
-; CHECK: !0 = !{!"sanmd_covered", !1}
-; CHECK: !1 = !{i8 1}
-; CHECK: !2 = !{!"sanmd_atomics"}
+; CHECK: !0 = !{!"sanmd_covered!C", !1}
+; CHECK: !1 = !{i64 1}
+; CHECK: !2 = !{!"sanmd_atomics!C"}
Index: llvm/test/CodeGen/X86/pcsections.ll
===
--- llvm/test/CodeGen/X86/pcsections.ll
+++ llvm/test/CodeGen/X86/pcsections.ll
@@ -137,9 +137,32 @@
   ret void
 }
 
+define void @multiple_uleb128() !pcsections !6 {
+; CHECK-LABEL: multiple_uleb128:
+; CHECK:   .section	section_aux,"awo",@progbits,.text
+; CHECK-NEXT:  .Lpcsection_base8:
+; DEFCM-NEXT:  .long	.Lfunc_begin3-.Lpcsection_base8
+; LARGE-NEXT:  .quad	.Lfunc_begin3-.Lpcsection_base8
+; CHECK-NEXT:  .uleb128	.Lfunc_end6-.Lfunc_begin3
+; CHECK-NEXT:  .byte	42
+; CHECK-NEXT:  .ascii	"\345\216&"
+; CHECK-NEXT:  .byte	255
+; CHECK-NEXT:  .section	section_aux_21264,"awo",@progbits,.text
+; CHECK-NEXT:  .Lpcsection_base9:
+; DEFCM-NEXT:  .long	.Lfunc_begin3-.Lpcsection_base9
+; LARGE-NEXT:  .quad	.Lfunc_begin3-.Lpcsection_base9
+; CHECK-NEXT:  .long	.Lfunc_end6-.Lfunc_begin3
+; CHECK-NEXT:  .long	21264
+; CHECK-NEXT:  .text
+entry:
+  ret void
+}
+
 !0 = !{!"section_no_aux"}
 !1 = !{!"section_aux", !3}
 !2 = !{!"section_aux_42", !4, !"section_aux_21264", !5}
 !3 = !{i32 10, i32 20, i32 30}
 !4 = !{i32 42}
 !5 = !{i32 21264}
+!6 = !{!"section_aux!C", !7, !"section_aux_21264", !5}
+!7 = !{i64 42, i32 624485, i8 255}
Index: llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
===
--- llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
+++ llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
@@ -36,14 +36,15 @@
 #include "llvm/InitializePasses.h"
 #include "llvm/Pass.h"
 #include "llvm/ProfileData/InstrProf.h"
+#include "llvm/Support/Allocator.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/StringSaver.h"
 #include "llvm/Transforms/Instrumentation.h"
 #include "llvm/Transforms/Utils/ModuleUtils.h"
 
 #include 
 #include 
-#include 
 
 using namespace llvm;
 
@@ -148,7 +149,7 @@
   // to determine if a memory operation is atomic or not in modules compiled
   // with SanitizerBinaryMetadata.
   bool runOn(Instruction &I, MetadataInfoSet &MIS, MDBuilder &MDB,
- uint32_t &FeatureMask);
+ uint64_t &FeatureMask);
 
   // Get start/end section marker pointer.
   GlobalVariable *getSectionMarker(const Twine &MarkerName, Type *Ty);
@@ -169,6 +170,8 @@
   const SanitizerBinaryMetadataOptions Options;
   const Triple TargetTriple;
   IRBuilder<> IRB;
+  BumpPtrAllocator Alloc;
+  UniqueStringSaver StringPool{Alloc};
 };
 
 bool SanitizerBinaryMetadata::run() {
@@ -242,7 +245,7 @@
 
   // The metadata features enabled for this function, stored along covered
   // metadata (if enabled).
-  uint32_t FeatureMask = 0;
+  uint64_t FeatureMask = 0;
   // Don't emit unnecessary covered metadata for all functions to save space.
   bool RequiresCovered = false;
 
@@ -267,10 +270,8 @@
 const auto *MI = &MetadataInfo::Covered;
 MIS.insert(MI);
 const StringRef Section = getSectionName(MI->SectionSuffix);
-// The feature mask will be placed after the size of the function.
-assert(FeatureMask <= std::numeric_limits::max() &&
- 

[PATCH] D143478: [RFC][Flang][driver] Try to support `flang -fc1as`

2023-02-07 Thread Shao-Ce SUN via Phabricator via cfe-commits
sunshaoce added a comment.

In D143478#4109479 , @awarzynski 
wrote:

> Thanks for working on this! Before diving any deeper
>
> - Does LLVM Flang require `flang-new -fc1as`?
> - If yes, why can't Flang and Clang share it?
>
> For better visibility, I suggest raising these questions on Discourse 
> . As this could potentially affect both Flang 
> and Clang, could you post in one of the generic sections? Thanks!

Thanks! I opened a topic: 
https://discourse.llvm.org/t/rfc-flang-driver-try-to-support-flang-fc1as/68267


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143478

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


[PATCH] D143478: [RFC][Flang][driver] Try to support `flang -fc1as`

2023-02-07 Thread Shao-Ce SUN via Phabricator via cfe-commits
sunshaoce added a comment.

In D143478#4109412 , @clementval 
wrote:

> There should be some tests.

I'm not sure how to check the generated binaries, can you provide a test case 
for reference? Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143478

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


[clang] cc14bf2 - [flang] add a pass to move array temporaries to the stack

2023-02-07 Thread Tom Eccles via cfe-commits

Author: Tom Eccles
Date: 2023-02-07T10:27:52Z
New Revision: cc14bf22bddf7abb1f13099c2d6ace5cdb8b7a5f

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

LOG: [flang] add a pass to move array temporaries to the stack

This pass implements the `-fstack-arrays` flag. See the RFC in
`flang/docs/fstack-arrays.md` for more information.

Differential revision: https://reviews.llvm.org/D140415

Added: 
flang/lib/Optimizer/Transforms/StackArrays.cpp
flang/test/Transforms/stack-arrays.f90
flang/test/Transforms/stack-arrays.fir

Modified: 
clang/docs/tools/clang-formatted-files.txt
flang/include/flang/Optimizer/Builder/MutableBox.h
flang/include/flang/Optimizer/Dialect/FIRAttr.h
flang/include/flang/Optimizer/Transforms/Passes.h
flang/include/flang/Optimizer/Transforms/Passes.td
flang/lib/Lower/Allocatable.cpp
flang/lib/Optimizer/Builder/MutableBox.cpp
flang/lib/Optimizer/Transforms/CMakeLists.txt
flang/test/Lower/HLFIR/allocatable-and-pointer-status-change.f90
flang/test/Lower/Intrinsics/c_loc.f90
flang/test/Lower/Intrinsics/system_clock.f90

Removed: 




diff  --git a/clang/docs/tools/clang-formatted-files.txt 
b/clang/docs/tools/clang-formatted-files.txt
index 0cea49221d949..45970232d0c0f 100644
--- a/clang/docs/tools/clang-formatted-files.txt
+++ b/clang/docs/tools/clang-formatted-files.txt
@@ -2299,6 +2299,7 @@ flang/lib/Optimizer/Transforms/MemoryAllocation.cpp
 flang/lib/Optimizer/Transforms/MemRefDataFlowOpt.cpp
 flang/lib/Optimizer/Transforms/PassDetail.h
 flang/lib/Optimizer/Transforms/RewriteLoop.cpp
+flang/lib/Optimizer/Transforms/StackArrays.cpp
 flang/lib/Parser/basic-parsers.h
 flang/lib/Parser/char-block.cpp
 flang/lib/Parser/char-buffer.cpp

diff  --git a/flang/include/flang/Optimizer/Builder/MutableBox.h 
b/flang/include/flang/Optimizer/Builder/MutableBox.h
index d49d2e7ae8119..3f3354d93530e 100644
--- a/flang/include/flang/Optimizer/Builder/MutableBox.h
+++ b/flang/include/flang/Optimizer/Builder/MutableBox.h
@@ -127,8 +127,8 @@ void genFinalization(fir::FirOpBuilder &builder, 
mlir::Location loc,
 void genInlinedAllocation(fir::FirOpBuilder &builder, mlir::Location loc,
   const fir::MutableBoxValue &box,
   mlir::ValueRange lbounds, mlir::ValueRange extents,
-  mlir::ValueRange lenParams,
-  llvm::StringRef allocName);
+  mlir::ValueRange lenParams, llvm::StringRef 
allocName,
+  bool mustBeHeap = false);
 
 void genInlinedDeallocate(fir::FirOpBuilder &builder, mlir::Location loc,
   const fir::MutableBoxValue &box);

diff  --git a/flang/include/flang/Optimizer/Dialect/FIRAttr.h 
b/flang/include/flang/Optimizer/Dialect/FIRAttr.h
index f88d6c6a4f97f..2b14e15c906c3 100644
--- a/flang/include/flang/Optimizer/Dialect/FIRAttr.h
+++ b/flang/include/flang/Optimizer/Dialect/FIRAttr.h
@@ -57,6 +57,15 @@ class SubclassAttr
   mlir::Type getType() const;
 };
 
+/// Attribute which can be applied to a fir.allocmem operation, specifying that
+/// the allocation may not be moved to the heap by passes
+class MustBeHeapAttr : public mlir::BoolAttr {
+public:
+  using BoolAttr::BoolAttr;
+
+  static constexpr llvm::StringRef getAttrName() { return "fir.must_be_heap"; }
+};
+
 // Attributes for building SELECT CASE multiway branches
 
 /// A closed interval (including the bound values) is an interval with both an

diff  --git a/flang/include/flang/Optimizer/Transforms/Passes.h 
b/flang/include/flang/Optimizer/Transforms/Passes.h
index 54a5d958d7315..efe55cecce30b 100644
--- a/flang/include/flang/Optimizer/Transforms/Passes.h
+++ b/flang/include/flang/Optimizer/Transforms/Passes.h
@@ -55,6 +55,7 @@ std::unique_ptr 
createExternalNameConversionPass();
 std::unique_ptr createMemDataFlowOptPass();
 std::unique_ptr createPromoteToAffinePass();
 std::unique_ptr createMemoryAllocationPass();
+std::unique_ptr createStackArraysPass();
 std::unique_ptr createSimplifyIntrinsicsPass();
 std::unique_ptr createAddDebugFoundationPass();
 

diff  --git a/flang/include/flang/Optimizer/Transforms/Passes.td 
b/flang/include/flang/Optimizer/Transforms/Passes.td
index 85a412ab046d6..13a73667965e5 100644
--- a/flang/include/flang/Optimizer/Transforms/Passes.td
+++ b/flang/include/flang/Optimizer/Transforms/Passes.td
@@ -235,6 +235,16 @@ def MemoryAllocationOpt : Pass<"memory-allocation-opt", 
"mlir::func::FuncOp"> {
   let constructor = "::fir::createMemoryAllocationPass()";
 }
 
+def StackArrays : Pass<"stack-arrays", "mlir::ModuleOp"> {
+  let summary = "Move local array allocations from heap memory into stack 
memory";
+  let description = [{
+Convert heap allocations for arrays, even those

[clang] bf81ba3 - [flang] add -fstack-arrays flag

2023-02-07 Thread Tom Eccles via cfe-commits

Author: Tom Eccles
Date: 2023-02-07T10:27:52Z
New Revision: bf81ba37262880a8391f63c1747d61e4851344c4

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

LOG: [flang] add -fstack-arrays flag

The implementation of -fstack-arrays was added in
https://reviews.llvm.org/D140415

The new macro BoolOptionWithoutMarshalling in Options.td avoids
generating code to store the flags in clang data structures. For
example, writing something like

  defm stack_arrays : BoolOption<"f", "stack-arrays",
 CodeGenOpts<"StackArrays">, [...]

Would generate code referring to `clang::CodeGenOpts::StackArrays`, which
does not exist.

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

Added: 


Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Flang.cpp
flang/docs/FlangDriver.md
flang/include/flang/Frontend/CodeGenOptions.def
flang/include/flang/Tools/CLOptions.inc
flang/lib/Frontend/CompilerInvocation.cpp
flang/lib/Frontend/FrontendActions.cpp
flang/test/Driver/driver-help-hidden.f90
flang/test/Driver/driver-help.f90
flang/test/Driver/fast_math.f90
flang/test/Transforms/stack-arrays.f90

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 03e6e7c52d63a..6392597153e34 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -482,6 +482,40 @@ multiclass BoolGOption;
 }
 
+// Works like BoolOption except without marshalling
+multiclass BoolOptionWithoutMarshalling> {
+  defvar flag1 = FlagDefExpanded.Result, 
prefix,
+ NAME, spelling_base>;
+
+  defvar flag2 = FlagDefExpanded.Result, 
prefix,
+ NAME, spelling_base>;
+
+  // The flags must have 
diff erent polarity, 
diff erent values, and only
+  // one can be implied.
+  assert !xor(flag1.Polarity, flag2.Polarity),
+ "the flags must have 
diff erent polarity: flag1: " #
+ flag1.Polarity # ", flag2: " # flag2.Polarity;
+  assert !ne(flag1.Value, flag2.Value),
+ "the flags must have 
diff erent values: flag1: " #
+ flag1.Value # ", flag2: " # flag2.Value;
+  assert !not(!and(flag1.CanBeImplied, flag2.CanBeImplied)),
+ "only one of the flags can be implied: flag1: " #
+ flag1.CanBeImplied # ", flag2: " # flag2.CanBeImplied;
+
+  defvar implied = !if(flag1.CanBeImplied, flag1, flag2);
+
+  def flag1.RecordName : Flag<["-"], flag1.Spelling>, Flags,
+ HelpText,
+ ImpliedByAnyOf
+ {}
+  def flag2.RecordName : Flag<["-"], flag2.Spelling>, Flags,
+ HelpText,
+ ImpliedByAnyOf
+ {}
+}
+
 // FIXME: Diagnose if target does not support protected visibility.
 class MarshallingInfoVisibility
   : MarshallingInfoEnum,
@@ -4986,7 +5020,6 @@ defm recursive : BooleanFFlag<"recursive">, 
Group;
 defm repack_arrays : BooleanFFlag<"repack-arrays">, Group;
 defm second_underscore : BooleanFFlag<"second-underscore">, 
Group;
 defm sign_zero : BooleanFFlag<"sign-zero">, Group;
-defm stack_arrays : BooleanFFlag<"stack-arrays">, Group;
 defm underscoring : BooleanFFlag<"underscoring">, Group;
 defm whole_file : BooleanFFlag<"whole-file">, Group;
 
@@ -5066,6 +5099,10 @@ defm implicit_none : OptInFC1FFlag<"implicit-none", "No 
implicit typing allowed
 def fno_automatic : Flag<["-"], "fno-automatic">, Group,
   HelpText<"Implies the SAVE attribute for non-automatic local objects in 
subprograms unless RECURSIVE">;
 
+defm stack_arrays : BoolOptionWithoutMarshalling<"f", "stack-arrays",
+  PosFlag,
+  NegFlag>;
+
 } // let Flags = [FC1Option, FlangOption, FlangOnlyOption]
 
 def J : JoinedOrSeparate<["-"], "J">,

diff  --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 4ee046be9ea97..8d9fae58ce50e 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -57,6 +57,13 @@ void Flang::addOtherOptions(const ArgList &Args, 
ArgStringList &CmdArgs) const {
options::OPT_fintrinsic_modules_path, options::OPT_pedantic,
options::OPT_std_EQ, options::OPT_W_Joined,
options::OPT_fconvert_EQ, options::OPT_fpass_plugin_EQ});
+
+  Arg *stackArrays =
+  Args.getLastArg(options::OPT_Ofast, options::OPT_fstack_arrays,
+  options::OPT_fno_stack_arrays);
+  if (stackArrays &&
+  !stackArrays->getOption().matches(options::OPT_fno_stack_arrays))
+CmdArgs.push_back("-fstack-arrays");
 }
 
 void Flang::addPicOptions(const ArgList &Args, ArgStringList &CmdArgs) const {

diff

[PATCH] D140415: [flang] stack arrays pass

2023-02-07 Thread Tom Eccles via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGcc14bf22bddf: [flang] add a pass to move array temporaries 
to the stack (authored by tblah).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140415

Files:
  clang/docs/tools/clang-formatted-files.txt
  flang/include/flang/Optimizer/Builder/MutableBox.h
  flang/include/flang/Optimizer/Dialect/FIRAttr.h
  flang/include/flang/Optimizer/Transforms/Passes.h
  flang/include/flang/Optimizer/Transforms/Passes.td
  flang/lib/Lower/Allocatable.cpp
  flang/lib/Optimizer/Builder/MutableBox.cpp
  flang/lib/Optimizer/Transforms/CMakeLists.txt
  flang/lib/Optimizer/Transforms/StackArrays.cpp
  flang/test/Lower/HLFIR/allocatable-and-pointer-status-change.f90
  flang/test/Lower/Intrinsics/c_loc.f90
  flang/test/Lower/Intrinsics/system_clock.f90
  flang/test/Transforms/stack-arrays.f90
  flang/test/Transforms/stack-arrays.fir

Index: flang/test/Transforms/stack-arrays.fir
===
--- /dev/null
+++ flang/test/Transforms/stack-arrays.fir
@@ -0,0 +1,309 @@
+// RUN: fir-opt --stack-arrays %s | FileCheck %s
+
+// Simplest transformation
+func.func @simple() {
+  %0 = fir.allocmem !fir.array<42xi32>
+  fir.freemem %0 : !fir.heap>
+  return
+}
+// CHECK: func.func @simple() {
+// CHECK-NEXT: fir.alloca !fir.array<42xi32>
+// CHECK-NEXT: return
+// CHECK-NEXT: }
+
+// Check fir.must_be_heap allocations are not moved
+func.func @must_be_heap() {
+  %0 = fir.allocmem !fir.array<42xi32> {fir.must_be_heap = true}
+  fir.freemem %0 : !fir.heap>
+  return
+}
+// CHECK:  func.func @must_be_heap() {
+// CHECK-NEXT:   %[[ALLOC:.*]] = fir.allocmem !fir.array<42xi32> {fir.must_be_heap = true}
+// CHECK-NEXT:   fir.freemem %[[ALLOC]] : !fir.heap>
+// CHECK-NEXT:   return
+// CHECK-NEXT: }
+
+// Check the data-flow-analysis can detect cases where we aren't sure if memory
+// is freed by the end of the function
+func.func @dfa1(%arg0: !fir.ref> {fir.bindc_name = "cond"}) {
+  %7 = arith.constant 42 : index
+  %8 = fir.allocmem !fir.array, %7 {uniq_name = "_QFdfa1Earr.alloc"}
+  %9 = fir.load %arg0 : !fir.ref>
+  %10 = fir.convert %9 : (!fir.logical<4>) -> i1
+  fir.if %10 {
+fir.freemem %8 : !fir.heap>
+  } else {
+  }
+  return
+}
+// CHECK:  func.func @dfa1(%arg0: !fir.ref> {fir.bindc_name = "cond"}) {
+// CHECK-NEXT:   %[[C42:.*]] = arith.constant 42 : index
+// CHECK-NEXT:   %[[MEM:.*]] = fir.allocmem !fir.array, %[[C42]] {uniq_name = "_QFdfa1Earr.alloc"}
+// CHECK-NEXT:   %[[LOGICAL:.*]] = fir.load %arg0 : !fir.ref>
+// CHECK-NEXT:   %[[BOOL:.*]] = fir.convert %[[LOGICAL]] : (!fir.logical<4>) -> i1
+// CHECK-NEXT:   fir.if %[[BOOL]] {
+// CHECK-NEXT: fir.freemem %[[MEM]] : !fir.heap>
+// CHECK-NEXT:   } else {
+// CHECK-NEXT:   }
+// CHECK-NEXT:   return
+// CHECK-NEXT: }
+
+// Check scf.if (fir.if is not considered a branch operation)
+func.func @dfa2(%arg0: i1) {
+  %a = fir.allocmem !fir.array<1xi8>
+  scf.if %arg0 {
+fir.freemem %a : !fir.heap>
+  } else {
+  }
+  return
+}
+// CHECK: func.func @dfa2(%arg0: i1) {
+// CHECK-NEXT:  %[[MEM:.*]] = fir.allocmem !fir.array<1xi8>
+// CHECK-NEXT:  scf.if %arg0 {
+// CHECK-NEXT:fir.freemem %[[MEM]] : !fir.heap>
+// CHECK-NEXT:  } else {
+// CHECK-NEXT:  }
+// CHECK-NEXT:  return
+// CHECK-NEXT:  }
+
+// check the alloca is placed after all operands become available
+func.func @placement1() {
+  // do some stuff with other ssa values
+  %1 = arith.constant 1 : index
+  %2 = arith.constant 2 : index
+  %3 = arith.addi %1, %2 : index
+  // operand is now available
+  %4 = fir.allocmem !fir.array, %3
+  // ...
+  fir.freemem %4 : !fir.heap>
+  return
+}
+// CHECK:  func.func @placement1() {
+// CHECK-NEXT:   %[[ONE:.*]] = arith.constant 1 : index
+// CHECK-NEXT:   %[[TWO:.*]] = arith.constant 2 : index
+// CHECK-NEXT:   %[[ARG:.*]] = arith.addi %[[ONE]], %[[TWO]] : index
+// CHECK-NEXT:   %[[MEM:.*]] = fir.alloca !fir.array, %[[ARG]]
+// CHECK-NEXT:   return
+// CHECK-NEXT: }
+
+// check that if there are no operands, then the alloca is placed early
+func.func @placement2() {
+  // do some stuff with other ssa values
+  %1 = arith.constant 1 : index
+  %2 = arith.constant 2 : index
+  %3 = arith.addi %1, %2 : index
+  %4 = fir.allocmem !fir.array<42xi32>
+  // ...
+  fir.freemem %4 : !fir.heap>
+  return
+}
+// CHECK:  func.func @placement2() {
+// CHECK-NEXT:   %[[MEM:.*]] = fir.alloca !fir.array<42xi32>
+// CHECK-NEXT:   %[[ONE:.*]] = arith.constant 1 : index
+// CHECK-NEXT:   %[[TWO:.*]] = arith.constant 2 : index
+// CHECK-NEXT:   %[[SUM:.*]] = arith.addi %[[ONE]], %[[TWO]] : index
+// CHECK-NEXT:   return
+// CHECK-NEXT: }
+
+// check that stack allocations which must be placed in loops use stacksave
+func.func @placement3() {
+  %c1 = arith.constant 1 : index
+  %c1_i32 = fir.convert %c1 : (index) -> i32
+  %c2 = arith.con

[PATCH] D140972: [flang] Add -fstack-arrays flag

2023-02-07 Thread Tom Eccles 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 rGbf81ba372628: [flang] add -fstack-arrays flag (authored by 
tblah).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140972

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/docs/FlangDriver.md
  flang/include/flang/Frontend/CodeGenOptions.def
  flang/include/flang/Tools/CLOptions.inc
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/fast_math.f90
  flang/test/Transforms/stack-arrays.f90

Index: flang/test/Transforms/stack-arrays.f90
===
--- flang/test/Transforms/stack-arrays.f90
+++ flang/test/Transforms/stack-arrays.f90
@@ -1,5 +1,10 @@
 ! RUN: %flang_fc1 -emit-fir %s -o - | fir-opt --array-value-copy | fir-opt --stack-arrays | FileCheck %s
 
+! In order to verify the whole MLIR pipeline, make the driver generate LLVM IR.
+! This is only to check that -fstack-arrays enables the stack-arrays pass so
+! only check the first example
+! RUN: %flang_fc1 -emit-llvm -o - -fstack-arrays %s | FileCheck --check-prefix=LLVM-IR %s
+
 ! check simple array value copy case
 subroutine array_value_copy_simple(arr)
   integer, intent(inout) :: arr(4)
@@ -14,6 +19,15 @@
 ! CHECK: return
 ! CHECK-NEXT: }
 
+! LLVM-IR: array_value_copy_simple
+! LLVM-IR-NOT: malloc
+! LLVM-IR-NOT: free
+! LLVM-IR: alloca [4 x i32]
+! LLVM-IR-NOT: malloc
+! LLVM-IR-NOT: free
+! LLVM-IR: ret void
+! LLVM-IR-NEXT: }
+
 ! check complex array value copy case
 module stuff
   type DerivedWithAllocatable
Index: flang/test/Driver/fast_math.f90
===
--- flang/test/Driver/fast_math.f90
+++ flang/test/Driver/fast_math.f90
@@ -1,25 +1,35 @@
 ! Test for correct forwarding of fast-math flags from the compiler driver to the
 ! frontend driver
 
-! -Ofast => -ffast-math -O3
+! -Ofast => -ffast-math -O3 -fstack-arrays
 ! RUN: %flang -Ofast -fsyntax-only -### %s -o %t 2>&1 \
 ! RUN: | FileCheck --check-prefix=CHECK-OFAST %s
 ! CHECK-OFAST: -fc1
 ! CHECK-OFAST-SAME: -ffast-math
+! CHECK-OFAST-SAME: -fstack-arrays
 ! CHECK-OFAST-SAME: -O3
 
-! TODO: update once -fstack-arays is added
-! RUN: %flang -fstack-arrays -fsyntax-only %s -o %t 2>&1 \
+! RUN: %flang -fstack-arrays -fsyntax-only -### %s -o %t 2>&1 \
 ! RUN: | FileCheck --check-prefix=CHECK-STACK-ARRAYS %s
-! CHECK-STACK-ARRAYS: warning: argument unused during compilation: '-fstack-arrays'
+! CHECK-STACK-ARRAYS: -fc1
+! CHECK-STACK-ARRAYS-SAME: -fstack-arrays
 
-! -Ofast -fno-fast-math => -O3
+! -Ofast -fno-fast-math => -O3 -fstack-arrays
 ! RUN: %flang -Ofast -fno-fast-math -fsyntax-only -### %s -o %t 2>&1 \
 ! RUN: | FileCheck --check-prefix=CHECK-OFAST-NO-FAST %s
 ! CHECK-OFAST-NO-FAST: -fc1
 ! CHECK-OFAST-NO-FAST-NOT: -ffast-math
+! CHECK-OFAST-NO-FAST-SAME: -fstack-arrays
 ! CHECK-OFAST-NO-FAST-SAME: -O3
 
+! -Ofast -fno-stack-arrays -> -O3 -ffast-math
+! RUN: %flang -Ofast -fno-stack-arrays -fsyntax-only -### %s -o %t 2>&1 \
+! RUN: | FileCheck --check-prefix=CHECK-OFAST-NO-SA %s
+! CHECK-OFAST-NO-SA: -fc1
+! CHECK-OFAST-NO-SA-SAME: -ffast-math
+! CHECK-OFAST-NO-SA-NOT: -fstack-arrays
+! CHECK-OFAST-NO-SA-SAME: -O3
+
 ! -ffast-math => -ffast-math
 ! RUN: %flang -ffast-math -fsyntax-only -### %s -o %t 2>&1 \
 ! RUN: | FileCheck --check-prefix=CHECK-FFAST %s
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -45,10 +45,12 @@
 ! HELP-NEXT: -fno-color-diagnostics  Disable colors in diagnostics
 ! HELP-NEXT: -fno-integrated-as  Disable the integrated assembler
 ! HELP-NEXT: -fno-signed-zeros  Allow optimizations that ignore the sign of floating point zeros
+! HELP-NEXT: -fno-stack-arrays  Allocate array temporaries on the heap (default)
 ! HELP-NEXT: -fopenacc  Enable OpenACC
 ! HELP-NEXT: -fopenmp   Parse OpenMP pragmas and generate parallel code.
 ! HELP-NEXT: -fpass-plugin= Load pass plugin from a dynamic shared object file (only with new pass manager).
 ! HELP-NEXT: -freciprocal-math  Allow division operations to be reassociated
+! HELP-NEXT: -fstack-arrays Attempt to allocate array temporaries on the stack, no matter their size
 ! HELP-NEXT: -fsyntax-only  Run the preprocessor, parser and semantic analysis stages
 ! HELP-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
 ! HELP-NEXT: -help  Display available options
@@ -133,10 +135,12 @@
 ! HELP-FC1-NEXT: -fno-debug-pass-manager Disables debug printing for the new pass manager
 !

[PATCH] D143484: [SanitizerBinaryMetadata] Emit constants as ULEB128

2023-02-07 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 495442.
melver added a comment.

Move AsmPrinter LEB128 helpers to AsmPrinter.cpp and use them.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143484

Files:
  clang/test/CodeGen/sanitize-metadata.c
  compiler-rt/test/metadata/common.h
  llvm/docs/PCSectionsMetadata.rst
  llvm/include/llvm/CodeGen/AsmPrinter.h
  llvm/include/llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h
  llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
  llvm/lib/CodeGen/AsmPrinter/AsmPrinterDwarf.cpp
  llvm/lib/CodeGen/SanitizerBinaryMetadata.cpp
  llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
  llvm/test/CodeGen/X86/pcsections.ll
  llvm/test/Instrumentation/SanitizerBinaryMetadata/atomics.ll

Index: llvm/test/Instrumentation/SanitizerBinaryMetadata/atomics.ll
===
--- llvm/test/Instrumentation/SanitizerBinaryMetadata/atomics.ll
+++ llvm/test/Instrumentation/SanitizerBinaryMetadata/atomics.ll
@@ -2071,6 +2071,6 @@
 ; CHECK-DAG: ret:
 ; CHECK-NEXT:  ret void
 
-; CHECK: !0 = !{!"sanmd_covered", !1}
-; CHECK: !1 = !{i8 1}
-; CHECK: !2 = !{!"sanmd_atomics"}
+; CHECK: !0 = !{!"sanmd_covered!C", !1}
+; CHECK: !1 = !{i64 1}
+; CHECK: !2 = !{!"sanmd_atomics!C"}
Index: llvm/test/CodeGen/X86/pcsections.ll
===
--- llvm/test/CodeGen/X86/pcsections.ll
+++ llvm/test/CodeGen/X86/pcsections.ll
@@ -137,9 +137,32 @@
   ret void
 }
 
+define void @multiple_uleb128() !pcsections !6 {
+; CHECK-LABEL: multiple_uleb128:
+; CHECK:   .section	section_aux,"awo",@progbits,.text
+; CHECK-NEXT:  .Lpcsection_base8:
+; DEFCM-NEXT:  .long	.Lfunc_begin3-.Lpcsection_base8
+; LARGE-NEXT:  .quad	.Lfunc_begin3-.Lpcsection_base8
+; CHECK-NEXT:  .uleb128	.Lfunc_end6-.Lfunc_begin3
+; CHECK-NEXT:  .byte	42
+; CHECK-NEXT:  .ascii	"\345\216&"
+; CHECK-NEXT:  .byte	255
+; CHECK-NEXT:  .section	section_aux_21264,"awo",@progbits,.text
+; CHECK-NEXT:  .Lpcsection_base9:
+; DEFCM-NEXT:  .long	.Lfunc_begin3-.Lpcsection_base9
+; LARGE-NEXT:  .quad	.Lfunc_begin3-.Lpcsection_base9
+; CHECK-NEXT:  .long	.Lfunc_end6-.Lfunc_begin3
+; CHECK-NEXT:  .long	21264
+; CHECK-NEXT:  .text
+entry:
+  ret void
+}
+
 !0 = !{!"section_no_aux"}
 !1 = !{!"section_aux", !3}
 !2 = !{!"section_aux_42", !4, !"section_aux_21264", !5}
 !3 = !{i32 10, i32 20, i32 30}
 !4 = !{i32 42}
 !5 = !{i32 21264}
+!6 = !{!"section_aux!C", !7, !"section_aux_21264", !5}
+!7 = !{i64 42, i32 624485, i8 255}
Index: llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
===
--- llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
+++ llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
@@ -36,14 +36,15 @@
 #include "llvm/InitializePasses.h"
 #include "llvm/Pass.h"
 #include "llvm/ProfileData/InstrProf.h"
+#include "llvm/Support/Allocator.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/StringSaver.h"
 #include "llvm/Transforms/Instrumentation.h"
 #include "llvm/Transforms/Utils/ModuleUtils.h"
 
 #include 
 #include 
-#include 
 
 using namespace llvm;
 
@@ -148,7 +149,7 @@
   // to determine if a memory operation is atomic or not in modules compiled
   // with SanitizerBinaryMetadata.
   bool runOn(Instruction &I, MetadataInfoSet &MIS, MDBuilder &MDB,
- uint32_t &FeatureMask);
+ uint64_t &FeatureMask);
 
   // Get start/end section marker pointer.
   GlobalVariable *getSectionMarker(const Twine &MarkerName, Type *Ty);
@@ -169,6 +170,8 @@
   const SanitizerBinaryMetadataOptions Options;
   const Triple TargetTriple;
   IRBuilder<> IRB;
+  BumpPtrAllocator Alloc;
+  UniqueStringSaver StringPool{Alloc};
 };
 
 bool SanitizerBinaryMetadata::run() {
@@ -242,7 +245,7 @@
 
   // The metadata features enabled for this function, stored along covered
   // metadata (if enabled).
-  uint32_t FeatureMask = 0;
+  uint64_t FeatureMask = 0;
   // Don't emit unnecessary covered metadata for all functions to save space.
   bool RequiresCovered = false;
 
@@ -267,10 +270,8 @@
 const auto *MI = &MetadataInfo::Covered;
 MIS.insert(MI);
 const StringRef Section = getSectionName(MI->SectionSuffix);
-// The feature mask will be placed after the size of the function.
-assert(FeatureMask <= std::numeric_limits::max() &&
-   "Increase feature mask bytes and bump version");
-Constant *CFM = IRB.getInt8(FeatureMask);
+// The feature mask will be placed after the function size.
+Constant *CFM = IRB.getInt64(FeatureMask);
 F.setMetadata(LLVMContext::MD_pcsections,
   MDB.createPCSections({{Section, {CFM}}}));
   }
@@ -377,7 +378,7 @@
 }
 
 bool SanitizerBinaryMetadata::runOn(Instruction &I, MetadataInfoSet &MIS,
-MDBuilder &M

[clang] 27aeb58 - [NFC][TargetParser] Remove llvm/Support/ARMTargetParser.h

2023-02-07 Thread Archibald Elliott via cfe-commits

Author: Archibald Elliott
Date: 2023-02-07T11:05:58Z
New Revision: 27aeb58ce4d12e15b966dba86738eb65a96703f7

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

LOG: [NFC][TargetParser] Remove llvm/Support/ARMTargetParser.h

Added: 


Modified: 
clang/lib/Basic/Targets/ARM.h
clang/lib/Driver/ToolChains/Arch/ARM.cpp
clang/lib/Driver/ToolChains/Arch/ARM.h
lldb/source/Utility/ArchSpec.cpp
llvm/include/llvm/MC/MCStreamer.h
llvm/lib/BinaryFormat/MachO.cpp
llvm/lib/Target/ARM/ARMSubtarget.cpp
llvm/lib/Target/ARM/ARMTargetMachine.cpp

Removed: 
llvm/include/llvm/Support/ARMTargetParser.h



diff  --git a/clang/lib/Basic/Targets/ARM.h b/clang/lib/Basic/Targets/ARM.h
index e662a609017b..fd3966b69d55 100644
--- a/clang/lib/Basic/Targets/ARM.h
+++ b/clang/lib/Basic/Targets/ARM.h
@@ -17,9 +17,9 @@
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
 #include "llvm/ADT/Triple.h"
-#include "llvm/Support/ARMTargetParser.h"
 #include "llvm/Support/ARMTargetParserCommon.h"
 #include "llvm/Support/Compiler.h"
+#include "llvm/TargetParser/ARMTargetParser.h"
 
 namespace clang {
 namespace targets {

diff  --git a/clang/lib/Driver/ToolChains/Arch/ARM.cpp 
b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
index b6a9df28500a..13a9c485ac9b 100644
--- a/clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -12,9 +12,9 @@
 #include "clang/Driver/Options.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Option/ArgList.h"
-#include "llvm/Support/ARMTargetParser.h"
-#include "llvm/Support/TargetParser.h"
 #include "llvm/Support/Host.h"
+#include "llvm/Support/TargetParser.h"
+#include "llvm/TargetParser/ARMTargetParser.h"
 
 using namespace clang::driver;
 using namespace clang::driver::tools;

diff  --git a/clang/lib/Driver/ToolChains/Arch/ARM.h 
b/clang/lib/Driver/ToolChains/Arch/ARM.h
index 782bdf3d0202..a9a4ca1eb05a 100644
--- a/clang/lib/Driver/ToolChains/Arch/ARM.h
+++ b/clang/lib/Driver/ToolChains/Arch/ARM.h
@@ -13,8 +13,8 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/Option/Option.h"
-#include "llvm/Support/ARMTargetParser.h"
 #include "llvm/Support/TargetParser.h"
+#include "llvm/TargetParser/ARMTargetParser.h"
 #include 
 #include 
 

diff  --git a/lldb/source/Utility/ArchSpec.cpp 
b/lldb/source/Utility/ArchSpec.cpp
index e1d7ee3ee276..c82097a9e6cd 100644
--- a/lldb/source/Utility/ArchSpec.cpp
+++ b/lldb/source/Utility/ArchSpec.cpp
@@ -16,8 +16,8 @@
 #include "llvm/BinaryFormat/COFF.h"
 #include "llvm/BinaryFormat/ELF.h"
 #include "llvm/BinaryFormat/MachO.h"
-#include "llvm/Support/ARMTargetParser.h"
 #include "llvm/Support/Compiler.h"
+#include "llvm/TargetParser/ARMTargetParser.h"
 
 using namespace lldb;
 using namespace lldb_private;

diff  --git a/llvm/include/llvm/MC/MCStreamer.h 
b/llvm/include/llvm/MC/MCStreamer.h
index 898fbc8c0fab..5331d9bd3cc4 100644
--- a/llvm/include/llvm/MC/MCStreamer.h
+++ b/llvm/include/llvm/MC/MCStreamer.h
@@ -22,11 +22,11 @@
 #include "llvm/MC/MCLinkerOptimizationHint.h"
 #include "llvm/MC/MCPseudoProbe.h"
 #include "llvm/MC/MCWinEH.h"
-#include "llvm/Support/ARMTargetParser.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/MD5.h"
 #include "llvm/Support/SMLoc.h"
 #include "llvm/Support/VersionTuple.h"
+#include "llvm/TargetParser/ARMTargetParser.h"
 #include 
 #include 
 #include 

diff  --git a/llvm/include/llvm/Support/ARMTargetParser.h 
b/llvm/include/llvm/Support/ARMTargetParser.h
deleted file mode 100644
index a0c0edd6d0f1..
--- a/llvm/include/llvm/Support/ARMTargetParser.h
+++ /dev/null
@@ -1,15 +0,0 @@
-//===-- llvm/Support/ARMTargetParser.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
-//
-//===--===//
-///
-/// \file
-/// This header is deprecated in favour of
-/// `llvm/TargetParser/ARMTargetParser.h`.
-///
-//===--===//
-
-#include "llvm/TargetParser/ARMTargetParser.h"

diff  --git a/llvm/lib/BinaryFormat/MachO.cpp b/llvm/lib/BinaryFormat/MachO.cpp
index 02a515c94399..c4cc8d6152d1 100644
--- a/llvm/lib/BinaryFormat/MachO.cpp
+++ b/llvm/lib/BinaryFormat/MachO.cpp
@@ -8,7 +8,7 @@
 
 #include "llvm/BinaryFormat/MachO.h"
 #include "llvm/ADT/Triple.h"
-#include "llvm/Support/ARMTargetParser.h"
+#include "llvm/TargetParser/ARMTargetParser.h"
 
 using namespace llvm;
 

diff  --git a/llvm/lib/Target/ARM/ARMSubtarget.cpp 
b/llvm/lib/Target/ARM/ARMSubtarget.cpp
index 79244f634ce3..

[clang] 4ae5400 - [NFC][TargetParser] Remove llvm/Support/ARMTargetParserCommon.h

2023-02-07 Thread Archibald Elliott via cfe-commits

Author: Archibald Elliott
Date: 2023-02-07T11:05:59Z
New Revision: 4ae540001a58d56659e3594ebbe9d1d1c57862fb

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

LOG: [NFC][TargetParser] Remove llvm/Support/ARMTargetParserCommon.h

Added: 


Modified: 
clang/lib/Basic/Targets/AArch64.cpp
clang/lib/Basic/Targets/ARM.h
clang/lib/Driver/ToolChains/Clang.cpp

Removed: 
llvm/include/llvm/Support/ARMTargetParserCommon.h



diff  --git a/clang/lib/Basic/Targets/AArch64.cpp 
b/clang/lib/Basic/Targets/AArch64.cpp
index 00387ab173b3..a0eae3177e3a 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -17,8 +17,8 @@
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringSwitch.h"
-#include "llvm/Support/ARMTargetParserCommon.h"
 #include "llvm/TargetParser/AArch64TargetParser.h"
+#include "llvm/TargetParser/ARMTargetParserCommon.h"
 #include 
 
 using namespace clang;

diff  --git a/clang/lib/Basic/Targets/ARM.h b/clang/lib/Basic/Targets/ARM.h
index fd3966b69d55..90db3dc8da19 100644
--- a/clang/lib/Basic/Targets/ARM.h
+++ b/clang/lib/Basic/Targets/ARM.h
@@ -17,9 +17,9 @@
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
 #include "llvm/ADT/Triple.h"
-#include "llvm/Support/ARMTargetParserCommon.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/TargetParser/ARMTargetParser.h"
+#include "llvm/TargetParser/ARMTargetParserCommon.h"
 
 namespace clang {
 namespace targets {

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index c316de65d89a..e7ba912403d8 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -45,7 +45,6 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Config/llvm-config.h"
 #include "llvm/Option/ArgList.h"
-#include "llvm/Support/ARMTargetParserCommon.h"
 #include "llvm/Support/CodeGen.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/Compression.h"
@@ -56,6 +55,7 @@
 #include "llvm/Support/Process.h"
 #include "llvm/Support/RISCVISAInfo.h"
 #include "llvm/Support/YAMLParser.h"
+#include "llvm/TargetParser/ARMTargetParserCommon.h"
 #include "llvm/TargetParser/RISCVTargetParser.h"
 #include 
 

diff  --git a/llvm/include/llvm/Support/ARMTargetParserCommon.h 
b/llvm/include/llvm/Support/ARMTargetParserCommon.h
deleted file mode 100644
index 27522f9802d2..
--- a/llvm/include/llvm/Support/ARMTargetParserCommon.h
+++ /dev/null
@@ -1,15 +0,0 @@
-//===-- llvm/Support/ARMTargetParserCommon.def --*- 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
-//
-//===--===//
-///
-/// \file
-/// This header is deprecated in favour of
-/// `llvm/TargetParser/ARMTargetParserCommon.h`.
-///
-//===--===//
-
-#include "llvm/TargetParser/ARMTargetParserCommon.h"



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


[clang] b9a1c4d - [NFC][TargetParser] Remove llvm/Support/CSKYTargetParser.h

2023-02-07 Thread Archibald Elliott via cfe-commits

Author: Archibald Elliott
Date: 2023-02-07T11:05:59Z
New Revision: b9a1c4d5e13ce3129d957675fc966577da310f58

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

LOG: [NFC][TargetParser] Remove llvm/Support/CSKYTargetParser.h

Added: 


Modified: 
clang/lib/Basic/Targets/CSKY.h
clang/lib/Driver/ToolChains/Arch/CSKY.cpp
llvm/lib/Target/CSKY/AsmParser/CSKYAsmParser.cpp
llvm/lib/Target/CSKY/MCTargetDesc/CSKYELFStreamer.cpp

Removed: 
llvm/include/llvm/Support/CSKYTargetParser.h



diff  --git a/clang/lib/Basic/Targets/CSKY.h b/clang/lib/Basic/Targets/CSKY.h
index 6edd035d9eb8..2346408f0f94 100644
--- a/clang/lib/Basic/Targets/CSKY.h
+++ b/clang/lib/Basic/Targets/CSKY.h
@@ -15,7 +15,7 @@
 
 #include "clang/Basic/MacroBuilder.h"
 #include "clang/Basic/TargetInfo.h"
-#include "llvm/Support/CSKYTargetParser.h"
+#include "llvm/TargetParser/CSKYTargetParser.h"
 
 namespace clang {
 namespace targets {

diff  --git a/clang/lib/Driver/ToolChains/Arch/CSKY.cpp 
b/clang/lib/Driver/ToolChains/Arch/CSKY.cpp
index ed8128d829e9..09baff68e6df 100644
--- a/clang/lib/Driver/ToolChains/Arch/CSKY.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/CSKY.cpp
@@ -14,10 +14,10 @@
 #include "clang/Driver/Options.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Option/ArgList.h"
-#include "llvm/Support/CSKYTargetParser.h"
 #include "llvm/Support/Host.h"
 #include "llvm/Support/TargetParser.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/TargetParser/CSKYTargetParser.h"
 
 using namespace clang::driver;
 using namespace clang::driver::tools;

diff  --git a/llvm/include/llvm/Support/CSKYTargetParser.h 
b/llvm/include/llvm/Support/CSKYTargetParser.h
deleted file mode 100644
index d3080ccd8970..
--- a/llvm/include/llvm/Support/CSKYTargetParser.h
+++ /dev/null
@@ -1,15 +0,0 @@
-//===-- llvm/Support/CSKYTargetParser.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
-//
-//===--===//
-///
-/// \file
-/// This header is deprecated in favour of
-/// `llvm/TargetParser/CSKYTargetParser.h`.
-///
-//===--===//
-
-#include "llvm/TargetParser/CSKYTargetParser.h"

diff  --git a/llvm/lib/Target/CSKY/AsmParser/CSKYAsmParser.cpp 
b/llvm/lib/Target/CSKY/AsmParser/CSKYAsmParser.cpp
index 11ed3dda1c91..cad1625ca215 100644
--- a/llvm/lib/Target/CSKY/AsmParser/CSKYAsmParser.cpp
+++ b/llvm/lib/Target/CSKY/AsmParser/CSKYAsmParser.cpp
@@ -29,10 +29,10 @@
 #include "llvm/MC/MCSubtargetInfo.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Support/CSKYAttributes.h"
-#include "llvm/Support/CSKYTargetParser.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/TargetParser/CSKYTargetParser.h"
 
 using namespace llvm;
 

diff  --git a/llvm/lib/Target/CSKY/MCTargetDesc/CSKYELFStreamer.cpp 
b/llvm/lib/Target/CSKY/MCTargetDesc/CSKYELFStreamer.cpp
index 90775c1b70f2..059c3c143c31 100644
--- a/llvm/lib/Target/CSKY/MCTargetDesc/CSKYELFStreamer.cpp
+++ b/llvm/lib/Target/CSKY/MCTargetDesc/CSKYELFStreamer.cpp
@@ -21,9 +21,9 @@
 #include "llvm/MC/MCSubtargetInfo.h"
 #include "llvm/MC/MCSymbolELF.h"
 #include "llvm/Support/CSKYAttributes.h"
-#include "llvm/Support/CSKYTargetParser.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/LEB128.h"
+#include "llvm/TargetParser/CSKYTargetParser.h"
 
 using namespace llvm;
 



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


[clang] a4c623e - [NFC][TargetParser] Remove llvm/Support/LoongArchTargetParser.h

2023-02-07 Thread Archibald Elliott via cfe-commits

Author: Archibald Elliott
Date: 2023-02-07T11:05:59Z
New Revision: a4c623e563ca46070284bc09d06f49d1f2426bc1

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

LOG: [NFC][TargetParser] Remove llvm/Support/LoongArchTargetParser.h

Added: 


Modified: 
clang/lib/Driver/ToolChains/Arch/LoongArch.cpp

Removed: 
llvm/include/llvm/Support/LoongArchTargetParser.h



diff  --git a/clang/lib/Driver/ToolChains/Arch/LoongArch.cpp 
b/clang/lib/Driver/ToolChains/Arch/LoongArch.cpp
index 576677a5f38e..c1c220633b6b 100644
--- a/clang/lib/Driver/ToolChains/Arch/LoongArch.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/LoongArch.cpp
@@ -11,7 +11,7 @@
 #include "clang/Driver/Driver.h"
 #include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Driver/Options.h"
-#include "llvm/Support/LoongArchTargetParser.h"
+#include "llvm/TargetParser/LoongArchTargetParser.h"
 
 using namespace clang::driver;
 using namespace clang::driver::tools;

diff  --git a/llvm/include/llvm/Support/LoongArchTargetParser.h 
b/llvm/include/llvm/Support/LoongArchTargetParser.h
deleted file mode 100644
index 4e735c893f82..
--- a/llvm/include/llvm/Support/LoongArchTargetParser.h
+++ /dev/null
@@ -1,15 +0,0 @@
-//===-- llvm/Support/LoongArchTargetParser.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
-//
-//===--===//
-///
-/// \file
-/// This header is deprecated in favour of
-/// `llvm/TargetParser/LoongArchTargetParser.h`.
-///
-//===--===//
-
-#include "llvm/TargetParser/LoongArchTargetParser.h"



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


[clang] b590f99 - [NFC][TargetParser] Remove llvm/Support/X86TargetParser.h

2023-02-07 Thread Archibald Elliott via cfe-commits

Author: Archibald Elliott
Date: 2023-02-07T11:06:00Z
New Revision: b590f997127fd565c93676bd5187d9fa5ec80389

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

LOG: [NFC][TargetParser] Remove llvm/Support/X86TargetParser.h

Added: 


Modified: 
clang/lib/Basic/Targets/X86.cpp
clang/lib/Basic/Targets/X86.h
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/CodeGen/CodeGenModule.cpp

Removed: 
llvm/include/llvm/Support/X86TargetParser.h



diff  --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp
index 490e20ce4514..ee854f1cfdcd 100644
--- a/clang/lib/Basic/Targets/X86.cpp
+++ b/clang/lib/Basic/Targets/X86.cpp
@@ -17,7 +17,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSwitch.h"
-#include "llvm/Support/X86TargetParser.h"
+#include "llvm/TargetParser/X86TargetParser.h"
 #include 
 
 namespace clang {

diff  --git a/clang/lib/Basic/Targets/X86.h b/clang/lib/Basic/Targets/X86.h
index 5fcc97e95c2b..c17a03571b10 100644
--- a/clang/lib/Basic/Targets/X86.h
+++ b/clang/lib/Basic/Targets/X86.h
@@ -19,7 +19,7 @@
 #include "clang/Basic/TargetOptions.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/Support/Compiler.h"
-#include "llvm/Support/X86TargetParser.h"
+#include "llvm/TargetParser/X86TargetParser.h"
 #include 
 
 namespace clang {

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index ba592b42391d..53dde119abce 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -54,8 +54,8 @@
 #include "llvm/IR/MatrixBuilder.h"
 #include "llvm/Support/ConvertUTF.h"
 #include "llvm/Support/ScopedPrinter.h"
-#include "llvm/Support/X86TargetParser.h"
 #include "llvm/TargetParser/AArch64TargetParser.h"
+#include "llvm/TargetParser/X86TargetParser.h"
 #include 
 #include 
 

diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 24b63372500b..c9362d30554c 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -67,8 +67,8 @@
 #include "llvm/Support/ConvertUTF.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/TimeProfiler.h"
-#include "llvm/Support/X86TargetParser.h"
 #include "llvm/Support/xxhash.h"
+#include "llvm/TargetParser/X86TargetParser.h"
 #include 
 
 using namespace clang;

diff  --git a/llvm/include/llvm/Support/X86TargetParser.h 
b/llvm/include/llvm/Support/X86TargetParser.h
deleted file mode 100644
index 351fb89d4601..
--- a/llvm/include/llvm/Support/X86TargetParser.h
+++ /dev/null
@@ -1,15 +0,0 @@
-//===-- llvm/Support/X86TargetParser.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
-//
-//===--===//
-///
-/// \file
-/// This header is deprecated in favour of
-/// `llvm/TargetParser/X86TargetParser.h`.
-///
-//===--===//
-
-#include "llvm/TargetParser/X86TargetParser.h"



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


[clang] 8e3d7cf - [NFC][TargetParser] Remove llvm/Support/TargetParser.h

2023-02-07 Thread Archibald Elliott via cfe-commits

Author: Archibald Elliott
Date: 2023-02-07T11:08:21Z
New Revision: 8e3d7cf5dee8d80dce1004a66c8a375b9d3b5dca

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

LOG: [NFC][TargetParser] Remove llvm/Support/TargetParser.h

Added: 


Modified: 
clang/lib/Basic/TargetID.cpp
clang/lib/Basic/TargetInfo.cpp
clang/lib/Basic/Targets/AMDGPU.h
clang/lib/Basic/Targets/LoongArch.cpp
clang/lib/Basic/Targets/M68k.cpp
clang/lib/Driver/SanitizerArgs.cpp
clang/lib/Driver/ToolChain.cpp
clang/lib/Driver/ToolChains/AMDGPU.h
clang/lib/Driver/ToolChains/Arch/AArch64.cpp
clang/lib/Driver/ToolChains/Arch/ARM.cpp
clang/lib/Driver/ToolChains/Arch/ARM.h
clang/lib/Driver/ToolChains/Arch/CSKY.cpp
clang/lib/Driver/ToolChains/CommonArgs.cpp
clang/lib/Driver/ToolChains/Cuda.cpp
clang/lib/Driver/ToolChains/Darwin.cpp
clang/lib/Driver/ToolChains/Gnu.cpp
clang/lib/Driver/ToolChains/HIPAMD.cpp
llvm/lib/Target/AArch64/AArch64Subtarget.cpp
llvm/lib/Target/AArch64/AsmParser/AArch64AsmParser.cpp
llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp
llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp
llvm/lib/Target/AMDGPU/GCNHazardRecognizer.cpp
llvm/lib/Target/AMDGPU/MCA/AMDGPUCustomBehaviour.h
llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUAsmBackend.cpp
llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUInstPrinter.cpp
llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUTargetStreamer.cpp
llvm/lib/Target/AMDGPU/SIInsertWaitcnts.cpp
llvm/lib/Target/AMDGPU/SIMemoryLegalizer.cpp
llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp
llvm/lib/Target/ARM/ARMAsmPrinter.cpp
llvm/lib/Target/ARM/ARMSubtarget.cpp
llvm/lib/Target/ARM/ARMTargetMachine.cpp
llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp
llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp
llvm/lib/Target/ARM/MCTargetDesc/ARMELFStreamer.cpp
llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp
llvm/lib/Target/ARM/MCTargetDesc/ARMTargetStreamer.cpp
llvm/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.cpp
llvm/lib/Target/X86/MCA/X86CustomBehaviour.h
llvm/unittests/Target/AMDGPU/AMDGPUUnitTests.cpp

Removed: 
llvm/include/llvm/Support/TargetParser.h



diff  --git a/clang/lib/Basic/TargetID.cpp b/clang/lib/Basic/TargetID.cpp
index 7cc4d67e3a52..a0cc9a2e2664 100644
--- a/clang/lib/Basic/TargetID.cpp
+++ b/clang/lib/Basic/TargetID.cpp
@@ -9,8 +9,8 @@
 #include "clang/Basic/TargetID.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/Triple.h"
-#include "llvm/Support/TargetParser.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/TargetParser/TargetParser.h"
 #include 
 #include 
 

diff  --git a/clang/lib/Basic/TargetInfo.cpp b/clang/lib/Basic/TargetInfo.cpp
index 8ee43261fc1d..70a15eb68f4e 100644
--- a/clang/lib/Basic/TargetInfo.cpp
+++ b/clang/lib/Basic/TargetInfo.cpp
@@ -19,7 +19,7 @@
 #include "llvm/ADT/APFloat.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/ErrorHandling.h"
-#include "llvm/Support/TargetParser.h"
+#include "llvm/TargetParser/TargetParser.h"
 #include 
 using namespace clang;
 

diff  --git a/clang/lib/Basic/Targets/AMDGPU.h 
b/clang/lib/Basic/Targets/AMDGPU.h
index 576bcf9d5401..5a41188b39ee 100644
--- a/clang/lib/Basic/Targets/AMDGPU.h
+++ b/clang/lib/Basic/Targets/AMDGPU.h
@@ -19,7 +19,7 @@
 #include "llvm/ADT/StringSet.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/Support/Compiler.h"
-#include "llvm/Support/TargetParser.h"
+#include "llvm/TargetParser/TargetParser.h"
 #include 
 
 namespace clang {

diff  --git a/clang/lib/Basic/Targets/LoongArch.cpp 
b/clang/lib/Basic/Targets/LoongArch.cpp
index 2079c89e3e15..513da77ba08a 100644
--- a/clang/lib/Basic/Targets/LoongArch.cpp
+++ b/clang/lib/Basic/Targets/LoongArch.cpp
@@ -14,8 +14,8 @@
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/MacroBuilder.h"
 #include "clang/Basic/TargetBuiltins.h"
-#include "llvm/Support/TargetParser.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/TargetParser/TargetParser.h"
 
 using namespace clang;
 using namespace clang::targets;

diff  --git a/clang/lib/Basic/Targets/M68k.cpp 
b/clang/lib/Basic/Targets/M68k.cpp
index 6c2d77444f13..cbc7c7983779 100644
--- a/clang/lib/Basic/Targets/M68k.cpp
+++ b/clang/lib/Basic/Targets/M68k.cpp
@@ -17,7 +17,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSwitch.h"
-#include "llvm/Support/TargetParser.h"
+#include "llvm/TargetParser/TargetParser.h"
 #include 
 #include 
 #include 

diff  --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index 49ae5cc6d88c..4f74093d7d24 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -16,10 +16,10 @@
 #include "llvm/ADT/String

[PATCH] D142327: [clang][RISCV] Fix ABI handling of empty structs with hard FP calling conventions in C++

2023-02-07 Thread Alex Bradbury via Phabricator via cfe-commits
asb added a comment.
Herald added a subscriber: jobnoorman.

Friendly ping on this (I think mostly directed at @kito-cheng who was hoping to 
find time to review the linked abi issue 
).


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

https://reviews.llvm.org/D142327

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


[clang-tools-extra] ce6de98 - [clang-tidy] Fix `cppcoreguidelines-init-variables` for invalid vardecl

2023-02-07 Thread via cfe-commits

Author: Sockke
Date: 2023-02-07T19:34:54+08:00
New Revision: ce6de98b80ada8efbff93766b5303db5ab052efc

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

LOG: [clang-tidy] Fix `cppcoreguidelines-init-variables` for invalid vardecl

https://godbolt.org/z/n4cK4fo3o
The checker missed a check for invalid vardecl and this could cause a false 
positive.

Reviewed By: carlosgalvezp

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp

clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
index b4543e0d2ae42..bdba2314c7056 100644
--- a/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
@@ -59,6 +59,10 @@ void InitVariablesCheck::check(const 
MatchFinder::MatchResult &Result) {
   const ASTContext &Context = *Result.Context;
   const SourceManager &Source = Context.getSourceManager();
 
+  // Clang diagnostic error may cause the variable to be an invalid int vardecl
+  if (MatchedDecl->isInvalidDecl())
+return;
+
   // We want to warn about cases where the type name
   // comes from a macro like this:
   //

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp
index 479e5f62eb8b5..e3d50946d1cb8 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s cppcoreguidelines-init-variables %t -- -- 
-fno-delayed-template-parsing -fexceptions
+// RUN: %check_clang_tidy %s cppcoreguidelines-init-variables -fix-errors %t 
-- -- -fno-delayed-template-parsing -fexceptions
 // CHECK-FIXES: {{^}}#include 
 
 // Ensure that function declarations are not changed.
@@ -124,3 +124,13 @@ void uninitialized_enum() {
   Fruit fruit;
   // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: variable 'fruit' is not 
initialized [cppcoreguidelines-init-variables]
 }
+
+void test_clang_diagnostic_error() {
+  int a;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: variable 'a' is not initialized 
[cppcoreguidelines-init-variables]
+  // CHECK-FIXES: {{^}}  int a = 0;{{$}}
+
+  UnknownType b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: error: unknown type name 'UnknownType' 
[clang-diagnostic-error]
+  // CHECK-FIXES-NOT: {{^}}  UnknownType b = 0;{{$}}
+}



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


[PATCH] D138655: [clang-tidy] Fix `cppcoreguidelines-init-variables` for invalid vardecl

2023-02-07 Thread gehry via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGce6de98b80ad: [clang-tidy] Fix 
`cppcoreguidelines-init-variables` for invalid vardecl (authored by Sockke).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138655

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s cppcoreguidelines-init-variables %t -- -- 
-fno-delayed-template-parsing -fexceptions
+// RUN: %check_clang_tidy %s cppcoreguidelines-init-variables -fix-errors %t 
-- -- -fno-delayed-template-parsing -fexceptions
 // CHECK-FIXES: {{^}}#include 
 
 // Ensure that function declarations are not changed.
@@ -124,3 +124,13 @@
   Fruit fruit;
   // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: variable 'fruit' is not 
initialized [cppcoreguidelines-init-variables]
 }
+
+void test_clang_diagnostic_error() {
+  int a;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: variable 'a' is not initialized 
[cppcoreguidelines-init-variables]
+  // CHECK-FIXES: {{^}}  int a = 0;{{$}}
+
+  UnknownType b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: error: unknown type name 'UnknownType' 
[clang-diagnostic-error]
+  // CHECK-FIXES-NOT: {{^}}  UnknownType b = 0;{{$}}
+}
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
@@ -59,6 +59,10 @@
   const ASTContext &Context = *Result.Context;
   const SourceManager &Source = Context.getSourceManager();
 
+  // Clang diagnostic error may cause the variable to be an invalid int vardecl
+  if (MatchedDecl->isInvalidDecl())
+return;
+
   // We want to warn about cases where the type name
   // comes from a macro like this:
   //


Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/init-variables.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s cppcoreguidelines-init-variables %t -- -- -fno-delayed-template-parsing -fexceptions
+// RUN: %check_clang_tidy %s cppcoreguidelines-init-variables -fix-errors %t -- -- -fno-delayed-template-parsing -fexceptions
 // CHECK-FIXES: {{^}}#include 
 
 // Ensure that function declarations are not changed.
@@ -124,3 +124,13 @@
   Fruit fruit;
   // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: variable 'fruit' is not initialized [cppcoreguidelines-init-variables]
 }
+
+void test_clang_diagnostic_error() {
+  int a;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: variable 'a' is not initialized [cppcoreguidelines-init-variables]
+  // CHECK-FIXES: {{^}}  int a = 0;{{$}}
+
+  UnknownType b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: error: unknown type name 'UnknownType' [clang-diagnostic-error]
+  // CHECK-FIXES-NOT: {{^}}  UnknownType b = 0;{{$}}
+}
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
@@ -59,6 +59,10 @@
   const ASTContext &Context = *Result.Context;
   const SourceManager &Source = Context.getSourceManager();
 
+  // Clang diagnostic error may cause the variable to be an invalid int vardecl
+  if (MatchedDecl->isInvalidDecl())
+return;
+
   // We want to warn about cases where the type name
   // comes from a macro like this:
   //
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D138655: [clang-tidy] Fix `cppcoreguidelines-init-variables` for invalid vardecl

2023-02-07 Thread gehry via Phabricator via cfe-commits
Sockke added a comment.

@carlosgalvezp Thanks for your review! I committed it myself.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138655

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


[PATCH] D143486: [clangd] Fix a crash in semantic highlighting.

2023-02-07 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: kadircet.
Herald added a subscriber: arphaman.
Herald added a project: All.
hokein requested review of this revision.
Herald added subscribers: MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

We encounter a few internal reports that we're dereference a nullptr.
Unfortunately, no small reproduce testcase for this crash yet, but it makes the
clangd more robost on broken code.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D143486

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp


Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -521,8 +521,8 @@
   return std::nullopt;
 
 const auto *Tok = TB.spelledTokenAt(Loc);
-assert(Tok);
-
+if (!Tok)
+  return std::nullopt;
 return halfOpenToRange(SourceMgr,
Tok->range(SourceMgr).toCharRange(SourceMgr));
   }


Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -521,8 +521,8 @@
   return std::nullopt;
 
 const auto *Tok = TB.spelledTokenAt(Loc);
-assert(Tok);
-
+if (!Tok)
+  return std::nullopt;
 return halfOpenToRange(SourceMgr,
Tok->range(SourceMgr).toCharRange(SourceMgr));
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D142893: [NFC] Class for building MultilibSet

2023-02-07 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings updated this revision to Diff 495460.
michaelplatings marked 6 inline comments as done.
michaelplatings added a comment.

Apply improvements suggested by @peter.smith


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142893

Files:
  clang/include/clang/Driver/Multilib.h
  clang/include/clang/Driver/MultilibBuilder.h
  clang/lib/Driver/CMakeLists.txt
  clang/lib/Driver/Multilib.cpp
  clang/lib/Driver/MultilibBuilder.cpp
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/lib/Driver/ToolChains/Fuchsia.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/unittests/Driver/CMakeLists.txt
  clang/unittests/Driver/MultilibBuilderTest.cpp
  clang/unittests/Driver/MultilibTest.cpp

Index: clang/unittests/Driver/MultilibTest.cpp
===
--- clang/unittests/Driver/MultilibTest.cpp
+++ clang/unittests/Driver/MultilibTest.cpp
@@ -11,34 +11,17 @@
 //===--===//
 
 #include "clang/Driver/Multilib.h"
+#include "../../lib/Driver/ToolChains/CommonArgs.h"
 #include "clang/Basic/LLVM.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSwitch.h"
+#include "llvm/Support/SourceMgr.h"
 #include "gtest/gtest.h"
 
 using namespace clang::driver;
 using namespace clang;
 
-TEST(MultilibTest, MultilibValidity) {
-
-  ASSERT_TRUE(Multilib().isValid()) << "Empty multilib is not valid";
-
-  ASSERT_TRUE(Multilib().flag("+foo").isValid())
-  << "Single indicative flag is not valid";
-
-  ASSERT_TRUE(Multilib().flag("-foo").isValid())
-  << "Single contraindicative flag is not valid";
-
-  ASSERT_FALSE(Multilib().flag("+foo").flag("-foo").isValid())
-  << "Conflicting flags should invalidate the Multilib";
-
-  ASSERT_TRUE(Multilib().flag("+foo").flag("+foo").isValid())
-  << "Multilib should be valid even if it has the same flag twice";
-
-  ASSERT_TRUE(Multilib().flag("+foo").flag("-foobar").isValid())
-  << "Seemingly conflicting prefixes shouldn't actually conflict";
-}
-
 TEST(MultilibTest, OpEqReflexivity1) {
   Multilib M;
   ASSERT_TRUE(M == M) << "Multilib::operator==() is not reflexive";
@@ -50,40 +33,28 @@
 }
 
 TEST(MultilibTest, OpEqReflexivity3) {
-  Multilib M1, M2;
-  M1.flag("+foo");
-  M2.flag("+foo");
+  Multilib M1({}, {}, {}, 0, {"+foo"});
+  Multilib M2({}, {}, {}, 0, {"+foo"});
   ASSERT_TRUE(M1 == M2) << "Multilibs with the same flag should be the same";
 }
 
 TEST(MultilibTest, OpEqInequivalence1) {
-  Multilib M1, M2;
-  M1.flag("+foo");
-  M2.flag("-foo");
+  Multilib M1({}, {}, {}, 0, {"+foo"});
+  Multilib M2({}, {}, {}, 0, {"-foo"});
   ASSERT_FALSE(M1 == M2) << "Multilibs with conflicting flags are not the same";
   ASSERT_FALSE(M2 == M1)
   << "Multilibs with conflicting flags are not the same (commuted)";
 }
 
 TEST(MultilibTest, OpEqInequivalence2) {
-  Multilib M1, M2;
-  M2.flag("+foo");
+  Multilib M1;
+  Multilib M2({}, {}, {}, 0, {"+foo"});
   ASSERT_FALSE(M1 == M2) << "Flags make Multilibs different";
 }
 
-TEST(MultilibTest, OpEqEquivalence1) {
-  Multilib M1, M2;
-  M1.flag("+foo");
-  M2.flag("+foo").flag("+foo");
-  ASSERT_TRUE(M1 == M2) << "Flag duplication shouldn't affect equivalence";
-  ASSERT_TRUE(M2 == M1)
-  << "Flag duplication shouldn't affect equivalence (commuted)";
-}
-
 TEST(MultilibTest, OpEqEquivalence2) {
-  Multilib M1("64");
-  Multilib M2;
-  M2.gccSuffix("/64");
+  Multilib M1("/64");
+  Multilib M2("/64");
   ASSERT_TRUE(M1 == M2)
   << "Constructor argument must match Multilib::gccSuffix()";
   ASSERT_TRUE(M2 == M1)
@@ -91,9 +62,8 @@
 }
 
 TEST(MultilibTest, OpEqEquivalence3) {
-  Multilib M1("", "32");
-  Multilib M2;
-  M2.osSuffix("/32");
+  Multilib M1("", "/32");
+  Multilib M2("", "/32");
   ASSERT_TRUE(M1 == M2)
   << "Constructor argument must match Multilib::osSuffix()";
   ASSERT_TRUE(M2 == M1)
@@ -101,9 +71,8 @@
 }
 
 TEST(MultilibTest, OpEqEquivalence4) {
-  Multilib M1("", "", "16");
-  Multilib M2;
-  M2.includeSuffix("/16");
+  Multilib M1("", "", "/16");
+  Multilib M2("", "", "/16");
   ASSERT_TRUE(M1 == M2)
   << "Constructor argument must match Multilib::includeSuffix()";
   ASSERT_TRUE(M2 == M1)
@@ -111,31 +80,31 @@
 }
 
 TEST(MultilibTest, OpEqInequivalence3) {
-  Multilib M1("foo");
-  Multilib M2("bar");
+  Multilib M1("/foo");
+  Multilib M2("/bar");
   ASSERT_FALSE(M1 == M2) << "Differing gccSuffixes should be different";
   ASSERT_FALSE(M2 == M1)
   << "Differing gccSuffixes should be different (commuted)";
 }
 
 TEST(MultilibTest, OpEqInequivalence4) {
-  Multilib M1("", "foo");
-  Multilib M2("", "bar");
+  Multilib M1("", "/foo");
+  Multilib M2("", "/bar");
   ASSERT_FALSE(M1 == M2) << "Differing osSuffixes should be different";
   ASSERT_FALSE(M2 == M1)
   << "Differing osSuffixes should be different (commuted)";
 }
 
 TEST(MultilibT

[PATCH] D142893: [NFC] Class for building MultilibSet

2023-02-07 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings added inline comments.



Comment at: clang/include/clang/Driver/Multilib.h:25
 namespace driver {
 
 /// This corresponds to a single GCC Multilib, or a segment of one controlled

peter.smith wrote:
> It took a bit of reading to work out what the relationship between Multilib, 
> MultilibVariant, MultilibSet and MultilibVariantBuilder are and how they are 
> expected to be used.
> 
> IIUC MultilibVariant and MultilibVariantBuilder are used to construct 
> Multilib and MultilibSet, which are expected to be immutable post 
> construction.
> 
> Will be worth either a comment describing the relation ship or potentially 
> write up the design in the clang docs and reference it from here. 
Yeah the naming was not intuitive, a hangover from one of the previous forms of 
this change. I've changed it so that `MultilibBuilder` creates `Multilib` and 
`MultilibSetBuilder` creates `MultilibSet`. That should make the comments less 
necessary, but I've added those too.



Comment at: clang/lib/Driver/ToolChains/BareMetal.cpp:32
 
-static Multilib makeMultilib(StringRef commonSuffix) {
-  return Multilib(commonSuffix, commonSuffix, commonSuffix);
+static MultilibBuilderVariant makeMultilib(StringRef commonSuffix) {
+  return MultilibBuilderVariant(commonSuffix, commonSuffix, commonSuffix);

peter.smith wrote:
> Worth making this a lambda in findRISCVMultilibs? Purely subjective opinion 
> here as there could be an attempt to limit changes.
> there could be an attempt to limit changes.
Indeed. I'd rather leave this in place for that reason.



Comment at: clang/lib/Driver/ToolChains/BareMetal.cpp:44
   if (TargetTriple.isRISCV64()) {
-Multilib Imac = 
makeMultilib("").flag("+march=rv64imac").flag("+mabi=lp64");
-Multilib Imafdc = makeMultilib("/rv64imafdc/lp64d")
-  .flag("+march=rv64imafdc")
-  .flag("+mabi=lp64d");
+auto Imac = makeMultilib("").flag("+march=rv64imac").flag("+mabi=lp64");
+auto Imafdc = makeMultilib("/rv64imafdc/lp64d")

peter.smith wrote:
> Wondering if we've lost information here by going to auto. We're really 
> making a MultilibVariant here. Perhaps worth renaming makeMultilib to 
> makeMultilibVariant?
I've gone back to declaring the type explicitly and renamed the function to 
`makeMultilibBuilder` since `MultilibBuilder` is the return type now.



Comment at: clang/lib/Driver/ToolChains/Gnu.cpp:1049
 
-static Multilib makeMultilib(StringRef commonSuffix) {
-  return Multilib(commonSuffix, commonSuffix, commonSuffix);
+static MultilibBuilderVariant makeMultilib(StringRef commonSuffix) {
+  return MultilibBuilderVariant(commonSuffix, commonSuffix, commonSuffix);

peter.smith wrote:
> Similar comment to BareMetal, is it worth renaming to makeMultilibVariant
Renamed to `makeMultilibBuilder` since `MultilibBuilder` is the return type now.



Comment at: clang/lib/Driver/ToolChains/Gnu.cpp:1737
   });
 
   Multilib::flags_list Flags;

peter.smith wrote:
> Although I'm not too bothered myself, some people prefer to keep changes in 
> whitespace to a separate NFC patch for the benefit of git annotate.
git-clang-format insists on changing it. A removed line won't show up in git 
annotate/blame (unless you're doing some extreme reverse-blaming activity, 
which mostly people don't) so I think it's best to let git-clang-format do its 
thing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142893

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


[PATCH] D143347: [lldb][DWARF] Infer no_unique_address attribute

2023-02-07 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added inline comments.



Comment at: clang/lib/AST/ASTImporter.cpp:3896
+  if (D->hasAttrs())
+ToField->setAttrs(D->getAttrs());
   ToField->setAccess(D->getAccess());

The import of attributes is handled in function `ASTImporter::Import(Decl*)`. 
This new line will probably copy all attributes, that may not work in all cases 
dependent on the attribute types. This may interfere with the later import of 
attributes, probably these will be duplicated. What was the need for this line? 
(Simple attributes that do not have references to other nodes could be copied 
at this place.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143347

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


[PATCH] D142905: Change multilib selection algorithm

2023-02-07 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings updated this revision to Diff 495463.
michaelplatings added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142905

Files:
  clang/include/clang/Driver/Multilib.h
  clang/include/clang/Driver/MultilibBuilder.h
  clang/lib/Driver/Multilib.cpp
  clang/lib/Driver/MultilibBuilder.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/Fuchsia.cpp
  clang/unittests/Driver/MultilibBuilderTest.cpp
  clang/unittests/Driver/MultilibTest.cpp

Index: clang/unittests/Driver/MultilibTest.cpp
===
--- clang/unittests/Driver/MultilibTest.cpp
+++ clang/unittests/Driver/MultilibTest.cpp
@@ -33,14 +33,14 @@
 }
 
 TEST(MultilibTest, OpEqReflexivity3) {
-  Multilib M1({}, {}, {}, 0, {"+foo"});
-  Multilib M2({}, {}, {}, 0, {"+foo"});
+  Multilib M1({}, {}, {}, {"+foo"});
+  Multilib M2({}, {}, {}, {"+foo"});
   ASSERT_TRUE(M1 == M2) << "Multilibs with the same flag should be the same";
 }
 
 TEST(MultilibTest, OpEqInequivalence1) {
-  Multilib M1({}, {}, {}, 0, {"+foo"});
-  Multilib M2({}, {}, {}, 0, {"-foo"});
+  Multilib M1({}, {}, {}, {"+foo"});
+  Multilib M2({}, {}, {}, {"-foo"});
   ASSERT_FALSE(M1 == M2) << "Multilibs with conflicting flags are not the same";
   ASSERT_FALSE(M2 == M1)
   << "Multilibs with conflicting flags are not the same (commuted)";
@@ -48,7 +48,7 @@
 
 TEST(MultilibTest, OpEqInequivalence2) {
   Multilib M1;
-  Multilib M2({}, {}, {}, 0, {"+foo"});
+  Multilib M2({}, {}, {}, {"+foo"});
   ASSERT_FALSE(M1 == M2) << "Flags make Multilibs different";
 }
 
@@ -124,7 +124,7 @@
 }
 
 TEST(MultilibTest, Construction3) {
-  Multilib M({}, {}, {}, 0, {"+f1", "+f2", "-f3"});
+  Multilib M({}, {}, {}, {"+f1", "+f2", "-f3"});
   for (Multilib::flags_list::const_iterator I = M.flags().begin(),
 E = M.flags().end();
I != E; ++I) {
@@ -149,8 +149,8 @@
 
 TEST(MultilibTest, SetPriority) {
   MultilibSet MS({
-  Multilib("/foo", {}, {}, 1, {"+foo"}),
-  Multilib("/bar", {}, {}, 2, {"+bar"}),
+  Multilib("/foo", {}, {}, {"+foo"}),
+  Multilib("/bar", {}, {}, {"+bar"}),
   });
   Multilib::flags_list Flags1 = {"+foo", "-bar"};
   Multilib Selection1;
@@ -166,3 +166,24 @@
   ASSERT_TRUE(Selection2.gccSuffix() == "/bar")
   << "Selection picked " << Selection2 << " which was not expected";
 }
+
+TEST(MultilibTest, SelectMultiple) {
+  MultilibSet MS({
+  Multilib("/a", {}, {}, {"x"}),
+  Multilib("/b", {}, {}, {"y"}),
+  });
+  std::vector Selection;
+
+  Selection = MS.select({"x"});
+  ASSERT_EQ(1u, Selection.size());
+  EXPECT_EQ("/a", Selection[0].gccSuffix());
+
+  Selection = MS.select({"y"});
+  ASSERT_EQ(1u, Selection.size());
+  EXPECT_EQ("/b", Selection[0].gccSuffix());
+
+  Selection = MS.select({"y", "x"});
+  ASSERT_EQ(2u, Selection.size());
+  EXPECT_EQ("/a", Selection[0].gccSuffix());
+  EXPECT_EQ("/b", Selection[1].gccSuffix());
+}
Index: clang/unittests/Driver/MultilibBuilderTest.cpp
===
--- clang/unittests/Driver/MultilibBuilderTest.cpp
+++ clang/unittests/Driver/MultilibBuilderTest.cpp
@@ -183,14 +183,14 @@
 bool IsSF = I & 0x2;
 Multilib::flags_list Flags;
 if (IsEL)
-  Flags.push_back("+EL");
+  Flags.insert("+EL");
 else
-  Flags.push_back("-EL");
+  Flags.insert("-EL");
 
 if (IsSF)
-  Flags.push_back("+SF");
+  Flags.insert("+SF");
 else
-  Flags.push_back("-SF");
+  Flags.insert("-SF");
 
 Multilib Selection;
 ASSERT_TRUE(MS2.select(Flags, Selection))
@@ -207,3 +207,14 @@
 << "Selection picked " << Selection << " which was not expected ";
   }
 }
+
+TEST(MultilibBuilderTest, PrintArgs) {
+  Multilib M = MultilibBuilder()
+   .flag("+x")
+   .flag("-y")
+   .flag("+a")
+   .flag("-b")
+   .flag("+c")
+   .makeMultilib();
+  ASSERT_EQ(Multilib::arg_list({"-x", "-a", "-c"}), M.getPrintArgs());
+}
Index: clang/lib/Driver/ToolChains/Fuchsia.cpp
===
--- clang/lib/Driver/ToolChains/Fuchsia.cpp
+++ clang/lib/Driver/ToolChains/Fuchsia.cpp
@@ -263,33 +263,33 @@
 
   Multilibs.push_back(Multilib());
   // Use the noexcept variant with -fno-exceptions to avoid the extra overhead.
-  Multilibs.push_back(MultilibBuilder("noexcept", {}, {}, 1)
+  Multilibs.push_back(MultilibBuilder("noexcept", {}, {})
   .flag("-fexceptions")
   .flag("+fno-exceptions")
   .makeMultilib());
   // ASan has higher priority because we always want the instrumentated version.
-  Multilibs.push_back(MultilibBuilder("asan", {}, {}, 2)
+  Multilibs.push_back(MultilibBuilder("asan", {},

[PATCH] D143059: [NFC] Enable selecting multiple multilibs

2023-02-07 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings updated this revision to Diff 495464.
michaelplatings added a comment.
Herald added a subscriber: jobnoorman.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143059

Files:
  clang/include/clang/Driver/Multilib.h
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/Multilib.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/lib/Driver/ToolChains/CSKYToolChain.cpp
  clang/lib/Driver/ToolChains/Fuchsia.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Driver/ToolChains/Gnu.h
  clang/lib/Driver/ToolChains/Hexagon.cpp
  clang/lib/Driver/ToolChains/Hurd.cpp
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/lib/Driver/ToolChains/MipsLinux.cpp
  clang/lib/Driver/ToolChains/RISCVToolchain.cpp
  clang/test/Driver/fuchsia.cpp
  clang/unittests/Driver/MultilibBuilderTest.cpp
  clang/unittests/Driver/MultilibTest.cpp

Index: clang/unittests/Driver/MultilibTest.cpp
===
--- clang/unittests/Driver/MultilibTest.cpp
+++ clang/unittests/Driver/MultilibTest.cpp
@@ -153,18 +153,18 @@
   Multilib("/bar", {}, {}, {"+bar"}),
   });
   Multilib::flags_list Flags1 = {"+foo", "-bar"};
-  Multilib Selection1;
+  llvm::SmallVector Selection1;
   ASSERT_TRUE(MS.select(Flags1, Selection1))
   << "Flag set was {\"+foo\"}, but selection not found";
-  ASSERT_TRUE(Selection1.gccSuffix() == "/foo")
-  << "Selection picked " << Selection1 << " which was not expected";
+  ASSERT_TRUE(Selection1.back().gccSuffix() == "/foo")
+  << "Selection picked " << Selection1.back() << " which was not expected";
 
   Multilib::flags_list Flags2 = {"+foo", "+bar"};
-  Multilib Selection2;
+  llvm::SmallVector Selection2;
   ASSERT_TRUE(MS.select(Flags2, Selection2))
   << "Flag set was {\"+bar\"}, but selection not found";
-  ASSERT_TRUE(Selection2.gccSuffix() == "/bar")
-  << "Selection picked " << Selection2 << " which was not expected";
+  ASSERT_TRUE(Selection2.back().gccSuffix() == "/bar")
+  << "Selection picked " << Selection2.back() << " which was not expected";
 }
 
 TEST(MultilibTest, SelectMultiple) {
@@ -172,17 +172,17 @@
   Multilib("/a", {}, {}, {"x"}),
   Multilib("/b", {}, {}, {"y"}),
   });
-  std::vector Selection;
+  llvm::SmallVector Selection;
 
-  Selection = MS.select({"x"});
+  ASSERT_TRUE(MS.select({"x"}, Selection));
   ASSERT_EQ(1u, Selection.size());
   EXPECT_EQ("/a", Selection[0].gccSuffix());
 
-  Selection = MS.select({"y"});
+  ASSERT_TRUE(MS.select({"y"}, Selection));
   ASSERT_EQ(1u, Selection.size());
   EXPECT_EQ("/b", Selection[0].gccSuffix());
 
-  Selection = MS.select({"y", "x"});
+  ASSERT_TRUE(MS.select({"y", "x"}, Selection));
   ASSERT_EQ(2u, Selection.size());
   EXPECT_EQ("/a", Selection[0].gccSuffix());
   EXPECT_EQ("/b", Selection[1].gccSuffix());
@@ -314,7 +314,7 @@
 
 TEST(MultilibTest, SelectSoft) {
   MultilibSet MS;
-  Multilib Selected;
+  llvm::SmallVector Selected;
   ASSERT_TRUE(parse(MS, R"(
 variants:
 - dir: s
@@ -333,7 +333,7 @@
 
 TEST(MultilibTest, SelectSoftFP) {
   MultilibSet MS;
-  Multilib Selected;
+  llvm::SmallVector Selected;
   ASSERT_TRUE(parse(MS, R"(
 variants:
 - dir: f
@@ -349,7 +349,7 @@
   // If hard float is all that's available then select that only if compiling
   // with hard float.
   MultilibSet MS;
-  Multilib Selected;
+  llvm::SmallVector Selected;
   ASSERT_TRUE(parse(MS, R"(
 variants:
 - dir: h
@@ -363,7 +363,7 @@
 
 TEST(MultilibTest, SelectFloatABI) {
   MultilibSet MS;
-  Multilib Selected;
+  llvm::SmallVector Selected;
   ASSERT_TRUE(parse(MS, R"(
 variants:
 - dir: s
@@ -384,18 +384,18 @@
   noMatchFlags: [hasfp]
 )"));
   MS.select({"mfloat-abi=soft"}, Selected);
-  EXPECT_EQ("/s", Selected.gccSuffix());
+  EXPECT_EQ("/s", Selected.back().gccSuffix());
   MS.select({"mfloat-abi=softfp"}, Selected);
-  EXPECT_EQ("/f", Selected.gccSuffix());
+  EXPECT_EQ("/f", Selected.back().gccSuffix());
   MS.select({"mfloat-abi=hard"}, Selected);
-  EXPECT_EQ("/h", Selected.gccSuffix());
+  EXPECT_EQ("/h", Selected.back().gccSuffix());
 }
 
 TEST(MultilibTest, SelectFloatABIReversed) {
   // If soft is specified after softfp then softfp will never be
   // selected because soft is compatible with softfp and last wins.
   MultilibSet MS;
-  Multilib Selected;
+  llvm::SmallVector Selected;
   ASSERT_TRUE(parse(MS, R"(
 variants:
 - dir: h
@@ -416,11 +416,11 @@
   noMatchFlags: [hasfp]
 )"));
   MS.select({"mfloat-abi=soft"}, Selected);
-  EXPECT_EQ("/s", Selected.gccSuffix());
+  EXPECT_EQ("/s", Selected.back().gccSuffix());
   MS.select({"mfloat-abi=softfp"}, Selected);
-  EXPECT_EQ("/s", Selected.gccSuffix());
+  EXPECT_EQ("/s", Selected.back().gccSuffix());
   MS.select({"mfloat-abi=hard"}, Selected);
-  EXPECT_EQ("/h", Selected.gccSuffix());
+  EXPECT_EQ("/h", Selected.back().gccSuffix()

[PATCH] D142092: [include-mapping] Allow multiple headers for the same symbol. Choose the first header of available ones.

2023-02-07 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

Thanks, it looks mostly good. This needs some work on rebase (as we have landed 
a few patches that change `StandardLibrary.cpp` file). I will rebase it and 
land it for you.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142092

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


[PATCH] D142092: [include-mapping] Allow multiple headers for the same symbol. Choose the first header of available ones.

2023-02-07 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 495477.
hokein added a comment.

- Rebase to main, and some small tweaks
- unittest will be added when landing the https://reviews.llvm.org/D143280


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142092

Files:
  clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp


Index: clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
===
--- clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
+++ clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
@@ -9,6 +9,9 @@
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "clang/AST/Decl.h"
 #include "clang/Basic/LangOptions.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 
@@ -41,7 +44,7 @@
   // Symbol name -> Symbol::ID, within a namespace.
   llvm::DenseMap *NamespaceSymbols = nullptr;
   // Symbol::ID => Header::ID
-  unsigned *SymbolHeaderIDs = nullptr;
+  llvm::SmallVector *SymbolHeaderIDs = nullptr;
 };
 } // namespace
 static SymbolHeaderMapping
@@ -51,8 +54,8 @@
 }
 
 static int countSymbols(Lang Language) {
-  unsigned SymCount = 0;
-#define SYMBOL(Name, NS, Header) ++SymCount;
+  llvm::DenseSet Set;
+#define SYMBOL(Name, NS, Header) Set.insert(#NS #Name);
   switch (Language) {
   case Lang::C:
 #include "CSymbolMap.inc"
@@ -62,7 +65,7 @@
 break;
   }
 #undef SYMBOL
-  return SymCount;
+  return Set.size();
 }
 
 static int initialize(Lang Language) {
@@ -91,8 +94,8 @@
 .first->second;
   };
 
-  auto Add = [&, SymIndex(0)](llvm::StringRef QName, unsigned NSLen,
-  llvm::StringRef HeaderName) mutable {
+  auto Add = [&, SymIndex(-1)](llvm::StringRef QName, unsigned NSLen,
+   llvm::StringRef HeaderName) mutable {
 // Correct "Nonefoo" => foo.
 // FIXME: get rid of "None" from the generated mapping files.
 if (QName.take_front(NSLen) == "None") {
@@ -100,14 +103,25 @@
   NSLen = 0;
 }
 
+if (SymIndex >= 0 &&
+Mapping->SymbolNames[SymIndex].qualifiedName() == QName) {
+  // Not a new symbol, use the same index.
+  assert(llvm::none_of(llvm::ArrayRef(Mapping->SymbolNames, SymIndex),
+   [&QName](const SymbolHeaderMapping::SymbolName &S) {
+ return S.qualifiedName() == QName;
+   }) &&
+ "The symbol has been added before, make sure entries in the .inc "
+ "file are grouped by symbol name!");
+} else {
+  // First symbol or new symbol, increment next available index.
+  ++SymIndex;
+}
 Mapping->SymbolNames[SymIndex] = {
 QName.data(), NSLen, static_cast(QName.size() - NSLen)};
-Mapping->SymbolHeaderIDs[SymIndex] = AddHeader(HeaderName);
+Mapping->SymbolHeaderIDs[SymIndex].push_back(AddHeader(HeaderName));
 
 NSSymbolMap &NSSymbols = AddNS(QName.take_front(NSLen));
 NSSymbols.try_emplace(QName.drop_front(NSLen), SymIndex);
-
-++SymIndex;
   };
 #define SYMBOL(Name, NS, Header) Add(#NS #Name, strlen(#NS), #Header);
   switch (Language) {
@@ -188,10 +202,13 @@
   return std::nullopt;
 }
 Header Symbol::header() const {
-  return Header(getMappingPerLang(Language)->SymbolHeaderIDs[ID], Language);
+  return Header(getMappingPerLang(Language)->SymbolHeaderIDs[ID][0], Language);
 }
 llvm::SmallVector Symbol::headers() const {
-  return {header()}; // FIXME: multiple in case of ambiguity
+  llvm::SmallVector Results;
+  for (auto HeaderID : getMappingPerLang(Language)->SymbolHeaderIDs[ID])
+Results.emplace_back(Header(HeaderID, Language));
+  return Results;
 }
 
 Recognizer::Recognizer() { ensureInitialized(); }


Index: clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
===
--- clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
+++ clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
@@ -9,6 +9,9 @@
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "clang/AST/Decl.h"
 #include "clang/Basic/LangOptions.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 
@@ -41,7 +44,7 @@
   // Symbol name -> Symbol::ID, within a namespace.
   llvm::DenseMap *NamespaceSymbols = nullptr;
   // Symbol::ID => Header::ID
-  unsigned *SymbolHeaderIDs = nullptr;
+  llvm::SmallVector *SymbolHeaderIDs = nullptr;
 };
 } // namespace
 static SymbolHeaderMapping
@@ -51,8 +54,8 @@
 }
 
 static int countSymbols(Lang Language) {
-  unsigned SymCount = 0;
-#define SYMBOL(Name, NS, Header) ++SymCount;
+  llvm::DenseSet Set;
+#define SYMBOL(Name, NS, Header) Set.insert(#NS #Name);
   switch (Language) {
   case Lang::

[PATCH] D143280: [include-mapping] Better #includes support for std input/output symbols

2023-02-07 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 495479.
hokein added a comment.

add a unittest


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143280

Files:
  clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
  clang/tools/include-mapping/gen_std.py
  clang/unittests/Tooling/StandardLibraryTest.cpp

Index: clang/unittests/Tooling/StandardLibraryTest.cpp
===
--- clang/unittests/Tooling/StandardLibraryTest.cpp
+++ clang/unittests/Tooling/StandardLibraryTest.cpp
@@ -58,6 +58,11 @@
   EXPECT_EQ(Vector->header(), *VectorH);
   EXPECT_THAT(Vector->headers(), ElementsAre(*VectorH));
 
+  EXPECT_THAT(stdlib::Symbol::named("std::", "basic_iostream")->headers(),
+  ElementsAre(stdlib::Header::named(""),
+  stdlib::Header::named(""),
+  stdlib::Header::named("")));
+
   EXPECT_THAT(stdlib::Header::all(), Contains(*VectorH));
   EXPECT_THAT(stdlib::Symbol::all(), Contains(*Vector));
   EXPECT_FALSE(stdlib::Header::named(""));
Index: clang/tools/include-mapping/gen_std.py
===
--- clang/tools/include-mapping/gen_std.py
+++ clang/tools/include-mapping/gen_std.py
@@ -42,6 +42,7 @@
 import os
 import sys
 
+
 CODE_PREFIX = """\
 //===-- gen_std.py generated file ---*- C++ -*-===//
 //
@@ -68,6 +69,108 @@
   required=True) 
   return parser.parse_args()
 
+def AdditionalHeadersForIOSymbols(symbol):
+  # IO-related symbols declared in the  header, per C++
+  # [iosfwd.syn 31.3.1]:
+  iosfwd_symbols = [
+  'basic_ios',
+  'basic_streambuf',
+  'basic_istream',
+  'basic_ostream',
+  'basic_iostream',
+
+  'basic_stringbuf',
+  'basic_istringstream',
+  'basic_ostringstream',
+  'basic_stringstream',
+
+  'basic_spanbuf',
+  'basic_ispanstream',
+  'basic_ospanstream',
+  'basic_spanstream',
+
+  'basic_filebuf',
+  'basic_ifstream',
+  'basic_ofstream',
+  'basic_fstream',
+
+  'basic_syncbuf',
+  'basic_osyncstream',
+
+  'istreambuf_iterator',
+  'ostreambuf_iterator',
+
+  'ios',
+  'wios',
+
+  'streambuf',
+  'istream',
+  'ostream',
+  'iostream',
+
+  'stringbuf',
+  'istringstream',
+  'ostringstream',
+  'stringstream',
+
+  'spanbuf',
+  'ispanstream',
+  'ospanstream',
+  'spanstream',
+
+  'filebuf',
+  'ifstream',
+  'ofstream',
+  'fstream',
+
+  'syncbuf',
+  'osyncstream',
+
+  'wstreambuf',
+  'wistream',
+  'wostream',
+  'wiostream',
+
+  'wstringbuf',
+  'wistringstream',
+  'wostringstream',
+  'wstringstream',
+
+  'wspanbuf',
+  'wispanstream',
+  'wospanstream',
+  'wspanstream',
+
+  'wfilebuf',
+  'wifstream',
+  'wofstream',
+  'wfstream',
+
+  'wsyncbuf',
+  'wosyncstream',
+
+  'fpos',
+  'streampos',
+  'wstreampos',
+  'u8streampos',
+  'u16streampos',
+  'u32streampos',
+  ]
+  assert(len(symbol.headers) == 1)
+  sym_header = symbol.headers[0]
+  headers = []
+  #  is preferred than 
+
+  #  is an alternative of , , , .
+  # per C++ [iostream.syn 31.4.1]
+  if sym_header in ["", "", "", ""]:
+headers.append("")
+
+  if symbol.name in iosfwd_symbols:
+headers.append("")
+
+  return headers
+
 
 def main():
   args = ParseArg()
@@ -112,8 +215,10 @@
   for symbol in symbols:
 if len(symbol.headers) == 1:
   # SYMBOL(unqualified_name, namespace, header)
-  print("SYMBOL(%s, %s, %s)" % (symbol.name, symbol.namespace,
-symbol.headers[0]))
+  symbol.headers.extend(AdditionalHeadersForIOSymbols(symbol))
+  for header in symbol.headers:
+print("SYMBOL(%s, %s, %s)" % (symbol.name, symbol.namespace,
+  header))
 elif len(symbol.headers) == 0:
   sys.stderr.write("No header found for symbol %s\n" % symbol.name)
 else:
Index: clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
===
--- clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
+++ clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
@@ -143,23 +143,43 @@
 SYMBOL(bad_weak_ptr, std::, )
 SYMBOL(basic_common_reference, std::, )
 SYMBOL(basic_filebuf, std::, )
+SYMBOL(basic_filebuf, std::, )
 SYMBOL(basic_fstream, std::, )
+SYMBOL(basic_fstream, std::, )
 SYMBOL(basic_ifstream, std::, )
+SYMBOL(basic_ifstream, std::, )
 SYMBOL(basic_ios, std::, )
+SYMBOL(basic_ios, std::, )
+SYMBOL(basic_ios, std::, )
 SYMBOL(basic_iostream, std::, )
+SYMBOL(basic_iostream, std::, )
+SYMBOL(basic_iostream, std::, )
 SYMBOL(basic_istream, std::, )
+SYMBOL(basic_istream, std::, )
+SYMBOL(basic_istream, std::, )
 SYMBOL(basi

[PATCH] D143207: Add codegen for llvm log2/log10 elementwise builtins

2023-02-07 Thread Florian Hahn via Phabricator via cfe-commits
fhahn accepted this revision.
fhahn added a comment.
This revision is now accepted and ready to land.
Herald added a subscriber: jobnoorman.

LGTM, thanks! Looks like a straight-forward extension of the existing builtins.




Comment at: clang/test/Sema/aarch64-sve-vector-log-ops.c:17
+  return __builtin_elementwise_log10(v);
+  // expected-error@-1 {{1st argument must be a vector, integer or floating 
point type}}
+}

We should ideally not mention `integer type` here. Not directly related to the 
patch, but would be great to see this fixed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143207

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


[clang] 1ab62d9 - [Tooling/Inclusion] Support multiple headers in the stdlib APIs.

2023-02-07 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2023-02-07T14:18:13+01:00
New Revision: 1ab62d9d8e964d41da9afa04fa226d300693a261

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

LOG: [Tooling/Inclusion] Support multiple headers in the stdlib APIs.

Unittest will be added in https://reviews.llvm.org/D143280

Patch by Viktoriia Bakalova.

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

Added: 


Modified: 
clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp

Removed: 




diff  --git a/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp 
b/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
index 373f77f44a393..55d87b98eb653 100644
--- a/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
+++ b/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
@@ -9,6 +9,9 @@
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "clang/AST/Decl.h"
 #include "clang/Basic/LangOptions.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 
@@ -41,7 +44,7 @@ struct SymbolHeaderMapping {
   // Symbol name -> Symbol::ID, within a namespace.
   llvm::DenseMap *NamespaceSymbols = nullptr;
   // Symbol::ID => Header::ID
-  unsigned *SymbolHeaderIDs = nullptr;
+  llvm::SmallVector *SymbolHeaderIDs = nullptr;
 };
 } // namespace
 static SymbolHeaderMapping
@@ -51,8 +54,8 @@ static const SymbolHeaderMapping *getMappingPerLang(Lang L) {
 }
 
 static int countSymbols(Lang Language) {
-  unsigned SymCount = 0;
-#define SYMBOL(Name, NS, Header) ++SymCount;
+  llvm::DenseSet Set;
+#define SYMBOL(Name, NS, Header) Set.insert(#NS #Name);
   switch (Language) {
   case Lang::C:
 #include "CSymbolMap.inc"
@@ -62,7 +65,7 @@ static int countSymbols(Lang Language) {
 break;
   }
 #undef SYMBOL
-  return SymCount;
+  return Set.size();
 }
 
 static int initialize(Lang Language) {
@@ -91,8 +94,8 @@ static int initialize(Lang Language) {
 .first->second;
   };
 
-  auto Add = [&, SymIndex(0)](llvm::StringRef QName, unsigned NSLen,
-  llvm::StringRef HeaderName) mutable {
+  auto Add = [&, SymIndex(-1)](llvm::StringRef QName, unsigned NSLen,
+   llvm::StringRef HeaderName) mutable {
 // Correct "Nonefoo" => foo.
 // FIXME: get rid of "None" from the generated mapping files.
 if (QName.take_front(NSLen) == "None") {
@@ -100,14 +103,25 @@ static int initialize(Lang Language) {
   NSLen = 0;
 }
 
+if (SymIndex >= 0 &&
+Mapping->SymbolNames[SymIndex].qualifiedName() == QName) {
+  // Not a new symbol, use the same index.
+  assert(llvm::none_of(llvm::ArrayRef(Mapping->SymbolNames, SymIndex),
+   [&QName](const SymbolHeaderMapping::SymbolName &S) {
+ return S.qualifiedName() == QName;
+   }) &&
+ "The symbol has been added before, make sure entries in the .inc "
+ "file are grouped by symbol name!");
+} else {
+  // First symbol or new symbol, increment next available index.
+  ++SymIndex;
+}
 Mapping->SymbolNames[SymIndex] = {
 QName.data(), NSLen, static_cast(QName.size() - NSLen)};
-Mapping->SymbolHeaderIDs[SymIndex] = AddHeader(HeaderName);
+Mapping->SymbolHeaderIDs[SymIndex].push_back(AddHeader(HeaderName));
 
 NSSymbolMap &NSSymbols = AddNS(QName.take_front(NSLen));
 NSSymbols.try_emplace(QName.drop_front(NSLen), SymIndex);
-
-++SymIndex;
   };
 #define SYMBOL(Name, NS, Header) Add(#NS #Name, strlen(#NS), #Header);
   switch (Language) {
@@ -188,10 +202,13 @@ std::optional Symbol::named(llvm::StringRef 
Scope, llvm::StringRef Name,
   return std::nullopt;
 }
 Header Symbol::header() const {
-  return Header(getMappingPerLang(Language)->SymbolHeaderIDs[ID], Language);
+  return Header(getMappingPerLang(Language)->SymbolHeaderIDs[ID][0], Language);
 }
 llvm::SmallVector Symbol::headers() const {
-  return {header()}; // FIXME: multiple in case of ambiguity
+  llvm::SmallVector Results;
+  for (auto HeaderID : getMappingPerLang(Language)->SymbolHeaderIDs[ID])
+Results.emplace_back(Header(HeaderID, Language));
+  return Results;
 }
 
 Recognizer::Recognizer() { ensureInitialized(); }



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


[PATCH] D142092: [include-mapping] Allow multiple headers for the same symbol. Choose the first header of available ones.

2023-02-07 Thread Haojian Wu via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1ab62d9d8e96: [Tooling/Inclusion] Support multiple headers 
in the stdlib APIs. (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142092

Files:
  clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp


Index: clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
===
--- clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
+++ clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
@@ -9,6 +9,9 @@
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "clang/AST/Decl.h"
 #include "clang/Basic/LangOptions.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 
@@ -41,7 +44,7 @@
   // Symbol name -> Symbol::ID, within a namespace.
   llvm::DenseMap *NamespaceSymbols = nullptr;
   // Symbol::ID => Header::ID
-  unsigned *SymbolHeaderIDs = nullptr;
+  llvm::SmallVector *SymbolHeaderIDs = nullptr;
 };
 } // namespace
 static SymbolHeaderMapping
@@ -51,8 +54,8 @@
 }
 
 static int countSymbols(Lang Language) {
-  unsigned SymCount = 0;
-#define SYMBOL(Name, NS, Header) ++SymCount;
+  llvm::DenseSet Set;
+#define SYMBOL(Name, NS, Header) Set.insert(#NS #Name);
   switch (Language) {
   case Lang::C:
 #include "CSymbolMap.inc"
@@ -62,7 +65,7 @@
 break;
   }
 #undef SYMBOL
-  return SymCount;
+  return Set.size();
 }
 
 static int initialize(Lang Language) {
@@ -91,8 +94,8 @@
 .first->second;
   };
 
-  auto Add = [&, SymIndex(0)](llvm::StringRef QName, unsigned NSLen,
-  llvm::StringRef HeaderName) mutable {
+  auto Add = [&, SymIndex(-1)](llvm::StringRef QName, unsigned NSLen,
+   llvm::StringRef HeaderName) mutable {
 // Correct "Nonefoo" => foo.
 // FIXME: get rid of "None" from the generated mapping files.
 if (QName.take_front(NSLen) == "None") {
@@ -100,14 +103,25 @@
   NSLen = 0;
 }
 
+if (SymIndex >= 0 &&
+Mapping->SymbolNames[SymIndex].qualifiedName() == QName) {
+  // Not a new symbol, use the same index.
+  assert(llvm::none_of(llvm::ArrayRef(Mapping->SymbolNames, SymIndex),
+   [&QName](const SymbolHeaderMapping::SymbolName &S) {
+ return S.qualifiedName() == QName;
+   }) &&
+ "The symbol has been added before, make sure entries in the .inc "
+ "file are grouped by symbol name!");
+} else {
+  // First symbol or new symbol, increment next available index.
+  ++SymIndex;
+}
 Mapping->SymbolNames[SymIndex] = {
 QName.data(), NSLen, static_cast(QName.size() - NSLen)};
-Mapping->SymbolHeaderIDs[SymIndex] = AddHeader(HeaderName);
+Mapping->SymbolHeaderIDs[SymIndex].push_back(AddHeader(HeaderName));
 
 NSSymbolMap &NSSymbols = AddNS(QName.take_front(NSLen));
 NSSymbols.try_emplace(QName.drop_front(NSLen), SymIndex);
-
-++SymIndex;
   };
 #define SYMBOL(Name, NS, Header) Add(#NS #Name, strlen(#NS), #Header);
   switch (Language) {
@@ -188,10 +202,13 @@
   return std::nullopt;
 }
 Header Symbol::header() const {
-  return Header(getMappingPerLang(Language)->SymbolHeaderIDs[ID], Language);
+  return Header(getMappingPerLang(Language)->SymbolHeaderIDs[ID][0], Language);
 }
 llvm::SmallVector Symbol::headers() const {
-  return {header()}; // FIXME: multiple in case of ambiguity
+  llvm::SmallVector Results;
+  for (auto HeaderID : getMappingPerLang(Language)->SymbolHeaderIDs[ID])
+Results.emplace_back(Header(HeaderID, Language));
+  return Results;
 }
 
 Recognizer::Recognizer() { ensureInitialized(); }


Index: clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
===
--- clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
+++ clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
@@ -9,6 +9,9 @@
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "clang/AST/Decl.h"
 #include "clang/Basic/LangOptions.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 
@@ -41,7 +44,7 @@
   // Symbol name -> Symbol::ID, within a namespace.
   llvm::DenseMap *NamespaceSymbols = nullptr;
   // Symbol::ID => Header::ID
-  unsigned *SymbolHeaderIDs = nullptr;
+  llvm::SmallVector *SymbolHeaderIDs = nullptr;
 };
 } // namespace
 static SymbolHeaderMapping
@@ -51,8 +54,8 @@
 }
 
 static int countSymbols(Lang Language) {
-  unsigned SymCount = 0;
-#define SYMBOL

[clang] 3599cbd - [include-mapping] Better #includes support for std input/output symbols

2023-02-07 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2023-02-07T14:19:32+01:00
New Revision: 3599cbd3f6db94e7358dcc901f41c7e357716c77

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

LOG: [include-mapping] Better #includes support for std input/output symbols

Reviewed By: kadircet

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

Added: 


Modified: 
clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
clang/tools/include-mapping/gen_std.py
clang/unittests/Tooling/StandardLibraryTest.cpp

Removed: 




diff  --git a/clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc 
b/clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
index e5e9065731e94..15ca4cf8d43ac 100644
--- a/clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
+++ b/clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
@@ -143,23 +143,43 @@ SYMBOL(bad_variant_access, std::, )
 SYMBOL(bad_weak_ptr, std::, )
 SYMBOL(basic_common_reference, std::, )
 SYMBOL(basic_filebuf, std::, )
+SYMBOL(basic_filebuf, std::, )
 SYMBOL(basic_fstream, std::, )
+SYMBOL(basic_fstream, std::, )
 SYMBOL(basic_ifstream, std::, )
+SYMBOL(basic_ifstream, std::, )
 SYMBOL(basic_ios, std::, )
+SYMBOL(basic_ios, std::, )
+SYMBOL(basic_ios, std::, )
 SYMBOL(basic_iostream, std::, )
+SYMBOL(basic_iostream, std::, )
+SYMBOL(basic_iostream, std::, )
 SYMBOL(basic_istream, std::, )
+SYMBOL(basic_istream, std::, )
+SYMBOL(basic_istream, std::, )
 SYMBOL(basic_istringstream, std::, )
+SYMBOL(basic_istringstream, std::, )
 SYMBOL(basic_ofstream, std::, )
+SYMBOL(basic_ofstream, std::, )
 SYMBOL(basic_ostream, std::, )
+SYMBOL(basic_ostream, std::, )
+SYMBOL(basic_ostream, std::, )
 SYMBOL(basic_ostringstream, std::, )
+SYMBOL(basic_ostringstream, std::, )
 SYMBOL(basic_osyncstream, std::, )
+SYMBOL(basic_osyncstream, std::, )
 SYMBOL(basic_regex, std::, )
 SYMBOL(basic_streambuf, std::, )
+SYMBOL(basic_streambuf, std::, )
+SYMBOL(basic_streambuf, std::, )
 SYMBOL(basic_string, std::, )
 SYMBOL(basic_string_view, std::, )
 SYMBOL(basic_stringbuf, std::, )
+SYMBOL(basic_stringbuf, std::, )
 SYMBOL(basic_stringstream, std::, )
+SYMBOL(basic_stringstream, std::, )
 SYMBOL(basic_syncbuf, std::, )
+SYMBOL(basic_syncbuf, std::, )
 SYMBOL(begin, std::, )
 SYMBOL(bernoulli_distribution, std::, )
 SYMBOL(bidirectional_iterator_tag, std::, )
@@ -174,6 +194,7 @@ SYMBOL(bit_xor, std::, )
 SYMBOL(bitset, std::, )
 SYMBOL(bool_constant, std::, )
 SYMBOL(boolalpha, std::, )
+SYMBOL(boolalpha, std::, )
 SYMBOL(boyer_moore_horspool_searcher, std::, )
 SYMBOL(boyer_moore_searcher, std::, )
 SYMBOL(bsearch, std::, )
@@ -251,6 +272,7 @@ SYMBOL(current_exception, std::, )
 SYMBOL(cv_status, std::, )
 SYMBOL(data, std::, )
 SYMBOL(dec, std::, )
+SYMBOL(dec, std::, )
 SYMBOL(deca, std::, )
 SYMBOL(decay, std::, )
 SYMBOL(decay_t, std::, )
@@ -262,6 +284,7 @@ SYMBOL(default_delete, std::, )
 SYMBOL(default_random_engine, std::, )
 SYMBOL(default_searcher, std::, )
 SYMBOL(defaultfloat, std::, )
+SYMBOL(defaultfloat, std::, )
 SYMBOL(defer_lock, std::, )
 SYMBOL(defer_lock_t, std::, )
 SYMBOL(denorm_absent, std::, )
@@ -286,6 +309,7 @@ SYMBOL(double_t, std::, )
 SYMBOL(dynamic_extent, std::, )
 SYMBOL(dynamic_pointer_cast, std::, )
 SYMBOL(emit_on_flush, std::, )
+SYMBOL(emit_on_flush, std::, )
 SYMBOL(empty, std::, )
 SYMBOL(enable_if, std::, )
 SYMBOL(enable_if_t, std::, )
@@ -293,7 +317,9 @@ SYMBOL(enable_shared_from_this, std::, )
 SYMBOL(end, std::, )
 SYMBOL(endian, std::, )
 SYMBOL(endl, std::, )
+SYMBOL(endl, std::, )
 SYMBOL(ends, std::, )
+SYMBOL(ends, std::, )
 SYMBOL(equal, std::, )
 SYMBOL(equal_range, std::, )
 SYMBOL(equal_to, std::, )
@@ -342,6 +368,8 @@ SYMBOL(fgets, std::, )
 SYMBOL(fgetwc, std::, )
 SYMBOL(fgetws, std::, )
 SYMBOL(filebuf, std::, )
+SYMBOL(filebuf, std::, )
+SYMBOL(filebuf, std::, )
 SYMBOL(fill, std::, )
 SYMBOL(fill_n, std::, )
 SYMBOL(find, std::, )
@@ -351,13 +379,16 @@ SYMBOL(find_if, std::, )
 SYMBOL(find_if_not, std::, )
 SYMBOL(fisher_f_distribution, std::, )
 SYMBOL(fixed, std::, )
+SYMBOL(fixed, std::, )
 SYMBOL(float_denorm_style, std::, )
 SYMBOL(float_round_style, std::, )
 SYMBOL(float_t, std::, )
 SYMBOL(floor, std::, )
 SYMBOL(floor2, std::, )
 SYMBOL(flush, std::, )
+SYMBOL(flush, std::, )
 SYMBOL(flush_emit, std::, )
+SYMBOL(flush_emit, std::, )
 SYMBOL(fma, std::, )
 SYMBOL(fmax, std::, )
 SYMBOL(fmin, std::, )
@@ -371,6 +402,8 @@ SYMBOL(forward_iterator_tag, std::, )
 SYMBOL(forward_list, std::, )
 SYMBOL(fpclassify, std::, )
 SYMBOL(fpos, std::, )
+SYMBOL(fpos, std::, )
+SYMBOL(fpos, std::, )
 SYMBOL(fpos_t, std::, )
 SYMBOL(fprintf, std::, )
 SYMBOL(fputc, std::, )
@@ -388,6 +421,7 @@ SYMBOL(fscanf, std::, )
 SYMBOL(fseek, std::, )
 SYMBOL(fsetpos, std::, )
 SYMBOL(fstream, std::, )
+SYMBOL(fstream, std::, )
 SYMBOL(ftell, std::, )

[PATCH] D143280: [include-mapping] Better #includes support for std input/output symbols

2023-02-07 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3599cbd3f6db: [include-mapping] Better #includes support for 
std input/output symbols (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143280

Files:
  clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
  clang/tools/include-mapping/gen_std.py
  clang/unittests/Tooling/StandardLibraryTest.cpp

Index: clang/unittests/Tooling/StandardLibraryTest.cpp
===
--- clang/unittests/Tooling/StandardLibraryTest.cpp
+++ clang/unittests/Tooling/StandardLibraryTest.cpp
@@ -58,6 +58,11 @@
   EXPECT_EQ(Vector->header(), *VectorH);
   EXPECT_THAT(Vector->headers(), ElementsAre(*VectorH));
 
+  EXPECT_THAT(stdlib::Symbol::named("std::", "basic_iostream")->headers(),
+  ElementsAre(stdlib::Header::named(""),
+  stdlib::Header::named(""),
+  stdlib::Header::named("")));
+
   EXPECT_THAT(stdlib::Header::all(), Contains(*VectorH));
   EXPECT_THAT(stdlib::Symbol::all(), Contains(*Vector));
   EXPECT_FALSE(stdlib::Header::named(""));
Index: clang/tools/include-mapping/gen_std.py
===
--- clang/tools/include-mapping/gen_std.py
+++ clang/tools/include-mapping/gen_std.py
@@ -42,6 +42,7 @@
 import os
 import sys
 
+
 CODE_PREFIX = """\
 //===-- gen_std.py generated file ---*- C++ -*-===//
 //
@@ -68,6 +69,108 @@
   required=True) 
   return parser.parse_args()
 
+def AdditionalHeadersForIOSymbols(symbol):
+  # IO-related symbols declared in the  header, per C++
+  # [iosfwd.syn 31.3.1]:
+  iosfwd_symbols = [
+  'basic_ios',
+  'basic_streambuf',
+  'basic_istream',
+  'basic_ostream',
+  'basic_iostream',
+
+  'basic_stringbuf',
+  'basic_istringstream',
+  'basic_ostringstream',
+  'basic_stringstream',
+
+  'basic_spanbuf',
+  'basic_ispanstream',
+  'basic_ospanstream',
+  'basic_spanstream',
+
+  'basic_filebuf',
+  'basic_ifstream',
+  'basic_ofstream',
+  'basic_fstream',
+
+  'basic_syncbuf',
+  'basic_osyncstream',
+
+  'istreambuf_iterator',
+  'ostreambuf_iterator',
+
+  'ios',
+  'wios',
+
+  'streambuf',
+  'istream',
+  'ostream',
+  'iostream',
+
+  'stringbuf',
+  'istringstream',
+  'ostringstream',
+  'stringstream',
+
+  'spanbuf',
+  'ispanstream',
+  'ospanstream',
+  'spanstream',
+
+  'filebuf',
+  'ifstream',
+  'ofstream',
+  'fstream',
+
+  'syncbuf',
+  'osyncstream',
+
+  'wstreambuf',
+  'wistream',
+  'wostream',
+  'wiostream',
+
+  'wstringbuf',
+  'wistringstream',
+  'wostringstream',
+  'wstringstream',
+
+  'wspanbuf',
+  'wispanstream',
+  'wospanstream',
+  'wspanstream',
+
+  'wfilebuf',
+  'wifstream',
+  'wofstream',
+  'wfstream',
+
+  'wsyncbuf',
+  'wosyncstream',
+
+  'fpos',
+  'streampos',
+  'wstreampos',
+  'u8streampos',
+  'u16streampos',
+  'u32streampos',
+  ]
+  assert(len(symbol.headers) == 1)
+  sym_header = symbol.headers[0]
+  headers = []
+  #  is preferred than 
+
+  #  is an alternative of , , , .
+  # per C++ [iostream.syn 31.4.1]
+  if sym_header in ["", "", "", ""]:
+headers.append("")
+
+  if symbol.name in iosfwd_symbols:
+headers.append("")
+
+  return headers
+
 
 def main():
   args = ParseArg()
@@ -112,8 +215,10 @@
   for symbol in symbols:
 if len(symbol.headers) == 1:
   # SYMBOL(unqualified_name, namespace, header)
-  print("SYMBOL(%s, %s, %s)" % (symbol.name, symbol.namespace,
-symbol.headers[0]))
+  symbol.headers.extend(AdditionalHeadersForIOSymbols(symbol))
+  for header in symbol.headers:
+print("SYMBOL(%s, %s, %s)" % (symbol.name, symbol.namespace,
+  header))
 elif len(symbol.headers) == 0:
   sys.stderr.write("No header found for symbol %s\n" % symbol.name)
 else:
Index: clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
===
--- clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
+++ clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
@@ -143,23 +143,43 @@
 SYMBOL(bad_weak_ptr, std::, )
 SYMBOL(basic_common_reference, std::, )
 SYMBOL(basic_filebuf, std::, )
+SYMBOL(basic_filebuf, std::, )
 SYMBOL(basic_fstream, std::, )
+SYMBOL(basic_fstream, std::, )
 SYMBOL(basic_ifstream, std::, )
+SYMBOL(basic_ifstream, std::, )
 SYMBOL(basic_ios, std::, )
+SYMBOL(basic_ios, std::, )
+SYMBOL(basic_ios, std::, )
 SYMBOL(basic_iostream, std::, )
+S

[PATCH] D142914: [MLIR][OpenMP] Added OMPIRBuilder support for Target Data directives.

2023-02-07 Thread Akash Banerjee via Phabricator via cfe-commits
TIFitis updated this revision to Diff 495493.
TIFitis marked 4 inline comments as done.
TIFitis added a comment.

Changed namespace to mlir::LLVM for common files. Addressed reviewer comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142914

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPConstants.h
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
  llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
  mlir/include/mlir/Target/LLVMIR/Dialect/Utils.h
  mlir/lib/Target/LLVMIR/Dialect/OpenACC/OpenACCToLLVMIRTranslation.cpp
  mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp

Index: mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
===
--- mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -15,10 +15,12 @@
 #include "mlir/IR/IRMapping.h"
 #include "mlir/IR/Operation.h"
 #include "mlir/Support/LLVM.h"
+#include "mlir/Target/LLVMIR/Dialect/Utils.h"
 #include "mlir/Target/LLVMIR/ModuleTranslation.h"
 
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/TypeSwitch.h"
+#include "llvm/Frontend/OpenMP/OMPConstants.h"
 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
 #include "llvm/IR/DebugInfoMetadata.h"
 #include "llvm/IR/IRBuilder.h"
@@ -1338,6 +1340,187 @@
   return success();
 }
 
+/// Process MapOperands for Target Data directives.
+static LogicalResult processMapOperand(
+llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation,
+const SmallVector &mapOperands, const ArrayAttr &mapTypes,
+SmallVector &mapTypeFlags,
+SmallVectorImpl &mapNames,
+struct llvm::OpenMPIRBuilder::MapperAllocas &mapperAllocas) {
+  auto numMapOperands = mapOperands.size();
+  llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
+  llvm::PointerType *i8PtrTy = builder.getInt8PtrTy();
+  llvm::ArrayType *arrI8PtrTy = llvm::ArrayType::get(i8PtrTy, numMapOperands);
+  llvm::IntegerType *i64Ty = builder.getInt64Ty();
+  llvm::ArrayType *arrI64Ty = llvm::ArrayType::get(i64Ty, numMapOperands);
+
+  unsigned index = 0;
+  for (const auto &mapOp : mapOperands) {
+const auto &mapTypeOp = mapTypes[index];
+
+llvm::Value *mapOpValue = moduleTranslation.lookupValue(mapOp);
+llvm::Value *mapOpPtrBase;
+llvm::Value *mapOpPtr;
+llvm::Value *mapOpSize;
+
+if (mapOp.getType().isa()) {
+  mapOpPtrBase = mapOpValue;
+  mapOpPtr = mapOpValue;
+  mapOpSize = ompBuilder->getSizeInBytes(mapOpValue);
+} else {
+  return failure();
+}
+
+// Store base pointer extracted from operand into the i-th position of
+// argBase.
+llvm::Value *ptrBaseGEP = builder.CreateInBoundsGEP(
+arrI8PtrTy, mapperAllocas.ArgsBase,
+{builder.getInt32(0), builder.getInt32(index)});
+llvm::Value *ptrBaseCast = builder.CreateBitCast(
+ptrBaseGEP, mapOpPtrBase->getType()->getPointerTo());
+builder.CreateStore(mapOpPtrBase, ptrBaseCast);
+
+// Store pointer extracted from operand into the i-th position of args.
+llvm::Value *ptrGEP = builder.CreateInBoundsGEP(
+arrI8PtrTy, mapperAllocas.Args,
+{builder.getInt32(0), builder.getInt32(index)});
+llvm::Value *ptrCast =
+builder.CreateBitCast(ptrGEP, mapOpPtr->getType()->getPointerTo());
+builder.CreateStore(mapOpPtr, ptrCast);
+
+// Store size extracted from operand into the i-th position of argSizes.
+llvm::Value *sizeGEP = builder.CreateInBoundsGEP(
+arrI64Ty, mapperAllocas.ArgSizes,
+{builder.getInt32(0), builder.getInt32(index)});
+builder.CreateStore(mapOpSize, sizeGEP);
+
+mapTypeFlags.push_back(mapTypeOp.dyn_cast().getInt());
+llvm::Constant *mapName =
+mlir::LLVM::createMappingInformation(mapOp.getLoc(), *ompBuilder);
+mapNames.push_back(mapName);
+++index;
+  }
+
+  return success();
+}
+
+static LogicalResult
+convertOmpTargetData(Operation *op, llvm::IRBuilderBase &builder,
+ LLVM::ModuleTranslation &moduleTranslation) {
+  unsigned numMapOperands;
+  llvm::Function *mapperFunc;
+  llvm::Value *ifCond = nullptr;
+  int64_t deviceID = llvm::omp::OMP_DEVICEID_UNDEF;
+  SmallVector mapOperands;
+  ArrayAttr mapTypes;
+
+  llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
+
+  LogicalResult result =
+  llvm::TypeSwitch(op)
+  .Case([&](omp::DataOp dataOp) {
+if (auto ifExprVar = dataOp.getIfExpr())
+  ifCond = moduleTranslation.lookupValue(ifExprVar);
+
+if (auto devId = dataOp.getDevice())
+  if (auto constOp = mlir::dyn_cast(
+  devId.getDefiningOp()))
+if (auto intAttr =
+cons

[PATCH] D143486: [clangd] Fix a crash in semantic highlighting.

2023-02-07 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:524
 const auto *Tok = TB.spelledTokenAt(Loc);
-assert(Tok);
-
+if (!Tok)
+  return std::nullopt;

can you add a comment here "We might have offsets in the main file that don't 
correspond to any spelled tokens." i think we should fix that in token buffer 
spelled token mappings going forward. we're relying on other places around 
`spelledTokenAt` returning a valid Token whenever we pass it a main file source 
location.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143486

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


[PATCH] D143054: [include-mapping] Regenerate the mappings from the 20220730 html book.

2023-02-07 Thread Haojian Wu via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4da283872ad9: [include-mapping] Regenerate the 
StdSymbolMap.inc from the 20220730 html book. (authored by VitaNuo, committed 
by hokein).

Changed prior to commit:
  https://reviews.llvm.org/D143054?vs=495108&id=495494#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143054

Files:
  clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
  clang/tools/include-mapping/cppreference_parser.py
  clang/tools/include-mapping/gen_std.py

Index: clang/tools/include-mapping/gen_std.py
===
--- clang/tools/include-mapping/gen_std.py
+++ clang/tools/include-mapping/gen_std.py
@@ -22,15 +22,13 @@
 Usage:
   1. Install BeautifulSoup dependency, see instruction:
https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-beautiful-soup
-  2. Download cppreference offline HTML files (e.g. html_book_20181028.zip) at
+  2. Download cppreference offline HTML files (html_book_20220730.zip in Unofficial Release) at
https://en.cppreference.com/w/Cppreference:Archives
   3. Unzip the zip file from step 2 (e.g., to a "cppreference" directory). You should
  get a "cppreference/reference" directory.
   4. Run the command:
// Generate C++ symbols
python3 gen_std.py -cppreference cppreference/reference -symbols=cpp > StdSymbolMap.inc
-   // Generate C++ removed symbols
-   python3 gen_std.py -cppreference cppreference/reference -symbols=cpp_removed > RemovedSymbolMap.inc
// Generate C symbols
python3 gen_std.py -cppreference cppreference/reference -symbols=c > CSymbolMap.inc
 """
@@ -191,11 +189,10 @@
   (symbol_index_root, "pmr.html", "std::pmr::"),
   (symbol_index_root, "regex_constants.html", "std::regex_constants::"),
   (symbol_index_root, "this_thread.html", "std::this_thread::"),
+  # Zombie symbols that were available from the Standard Library, but are
+  # removed in the following standards.
+  (symbol_index_root, "zombie_names.html", "std::"),
 ]
-  elif args.symbols == 'cpp_removed':
-page_root = os.path.join(args.cppreference, "en", "cpp")
-symbol_index_root = os.path.join(page_root, "symbol_index")
-parse_pages = [(symbol_index_root, "zombie_names.html", "std::")]
   elif args.symbols == 'c':
 page_root = os.path.join(args.cppreference, "en", "c")
 symbol_index_root = page_root
Index: clang/tools/include-mapping/cppreference_parser.py
===
--- clang/tools/include-mapping/cppreference_parser.py
+++ clang/tools/include-mapping/cppreference_parser.py
@@ -28,6 +28,11 @@
 # a list of corresponding headers
 self.headers = headers
 
+  def __lt__(self, other):
+if self.namespace != other.namespace:
+  return self.namespace < other.namespace
+return self.name < other.name
+
 
 def _HasClass(tag, *classes):
   for c in tag.get('class', []):
@@ -147,7 +152,7 @@
   pool.apply_async(_ReadSymbolPage, (path, symbol_name
   else:
 sys.stderr.write("Discarding information for symbol: %s. Page %s does not exist.\n" 
-  % (symbol_name, path))
+  % (symbol_name, path))
 
 # Build map from symbol name to a set of headers.
 symbol_headers = collections.defaultdict(set)
@@ -185,4 +190,4 @@
   finally:
 pool.terminate()
 pool.join()
-  return symbols
+  return sorted(symbols)
Index: clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
===
--- clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
+++ clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
@@ -6,45 +6,18 @@
 // This file was generated automatically by
 // clang/tools/include-mapping/gen_std.py, DO NOT EDIT!
 //
-// Generated from cppreference offline HTML book (modified on 2018-10-28).
+// Generated from cppreference offline HTML book (modified on 2022-07-30).
 //===--===//
 
-SYMBOL(Assignable, std::, )
-SYMBOL(Boolean, std::, )
-SYMBOL(Common, std::, )
-SYMBOL(CommonReference, std::, )
-SYMBOL(Constructible, std::, )
-SYMBOL(ConvertibleTo, std::, )
-SYMBOL(CopyConstructible, std::, )
-SYMBOL(Copyable, std::, )
-SYMBOL(DefaultConstructible, std::, )
-SYMBOL(DerivedFrom, std::, )
-SYMBOL(Destructible, std::, )
-SYMBOL(EqualityComparable, std::, )
-SYMBOL(EqualityComparableWith, std::, )
 SYMBOL(FILE, std::, )
-SYMBOL(Integral, std::, )
-SYMBOL(Invocable, std::, )
-SYMBOL(Movable, std::, )
-SYMBOL(MoveConstructible, std::, )
-SYMBOL(Predicate, std::, )
-SYMBOL(Regular, std::, )
-SYMBOL(RegularInvocable, std::, )
-SYMBOL(Relation, std::, )
-SYMBOL(Same, std:

[clang] 4da2838 - [include-mapping] Regenerate the StdSymbolMap.inc from the 20220730 html book.

2023-02-07 Thread Haojian Wu via cfe-commits

Author: Viktoriia Bakalova
Date: 2023-02-07T14:52:18+01:00
New Revision: 4da283872ad925cbffca94f74800a987cc9ba85f

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

LOG: [include-mapping] Regenerate the StdSymbolMap.inc from the 20220730 html 
book.

Merge the zoombie names into the StdSymbols as well.

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

Added: 


Modified: 
clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
clang/tools/include-mapping/cppreference_parser.py
clang/tools/include-mapping/gen_std.py

Removed: 




diff  --git a/clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc 
b/clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
index 15ca4cf8d43a..8e0162a64850 100644
--- a/clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
+++ b/clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
@@ -6,45 +6,18 @@
 // This file was generated automatically by
 // clang/tools/include-mapping/gen_std.py, DO NOT EDIT!
 //
-// Generated from cppreference offline HTML book (modified on 2018-10-28).
+// Generated from cppreference offline HTML book (modified on 2022-07-30).
 
//===--===//
 
-SYMBOL(Assignable, std::, )
-SYMBOL(Boolean, std::, )
-SYMBOL(Common, std::, )
-SYMBOL(CommonReference, std::, )
-SYMBOL(Constructible, std::, )
-SYMBOL(ConvertibleTo, std::, )
-SYMBOL(CopyConstructible, std::, )
-SYMBOL(Copyable, std::, )
-SYMBOL(DefaultConstructible, std::, )
-SYMBOL(DerivedFrom, std::, )
-SYMBOL(Destructible, std::, )
-SYMBOL(EqualityComparable, std::, )
-SYMBOL(EqualityComparableWith, std::, )
 SYMBOL(FILE, std::, )
-SYMBOL(Integral, std::, )
-SYMBOL(Invocable, std::, )
-SYMBOL(Movable, std::, )
-SYMBOL(MoveConstructible, std::, )
-SYMBOL(Predicate, std::, )
-SYMBOL(Regular, std::, )
-SYMBOL(RegularInvocable, std::, )
-SYMBOL(Relation, std::, )
-SYMBOL(Same, std::, )
-SYMBOL(Semiregular, std::, )
-SYMBOL(SignedIntegral, std::, )
-SYMBOL(StrictTotallyOrdered, std::, )
-SYMBOL(StrictTotallyOrderedWith, std::, )
-SYMBOL(StrictWeakOrder, std::, )
-SYMBOL(Swappable, std::, )
-SYMBOL(SwappableWith, std::, )
-SYMBOL(UniformRandomBitGenerator, std::, )
-SYMBOL(UnsignedIntegral, std::, )
 SYMBOL(_Exit, std::, )
 SYMBOL(accumulate, std::, )
 SYMBOL(acos, std::, )
+SYMBOL(acosf, std::, )
 SYMBOL(acosh, std::, )
+SYMBOL(acoshf, std::, )
+SYMBOL(acoshl, std::, )
+SYMBOL(acosl, std::, )
 SYMBOL(add_const, std::, )
 SYMBOL(add_const_t, std::, )
 SYMBOL(add_cv, std::, )
@@ -73,7 +46,10 @@ SYMBOL(aligned_union_t, std::, )
 SYMBOL(alignment_of, std::, )
 SYMBOL(alignment_of_v, std::, )
 SYMBOL(all_of, std::, )
+SYMBOL(allocate_at_least, std::, )
 SYMBOL(allocate_shared, std::, )
+SYMBOL(allocate_shared_for_overwrite, std::, )
+SYMBOL(allocation_result, std::, )
 SYMBOL(allocator, std::, )
 SYMBOL(allocator_arg, std::, )
 SYMBOL(allocator_arg_t, std::, )
@@ -83,15 +59,35 @@ SYMBOL(any_of, std::, )
 SYMBOL(apply, std::, )
 SYMBOL(arg, std::, )
 SYMBOL(array, std::, )
+SYMBOL(as_bytes, std::, )
 SYMBOL(as_const, std::, )
+SYMBOL(as_writable_bytes, std::, )
 SYMBOL(asctime, std::, )
 SYMBOL(asin, std::, )
+SYMBOL(asinf, std::, )
 SYMBOL(asinh, std::, )
+SYMBOL(asinhf, std::, )
+SYMBOL(asinhl, std::, )
+SYMBOL(asinl, std::, )
+SYMBOL(assignable_from, std::, )
+SYMBOL(assoc_laguerre, std::, )
+SYMBOL(assoc_laguerref, std::, )
+SYMBOL(assoc_laguerrel, std::, )
+SYMBOL(assoc_legendre, std::, )
+SYMBOL(assoc_legendref, std::, )
+SYMBOL(assoc_legendrel, std::, )
+SYMBOL(assume_aligned, std::, )
 SYMBOL(async, std::, )
 SYMBOL(at_quick_exit, std::, )
 SYMBOL(atan, std::, )
 SYMBOL(atan2, std::, )
+SYMBOL(atan2f, std::, )
+SYMBOL(atan2l, std::, )
+SYMBOL(atanf, std::, )
 SYMBOL(atanh, std::, )
+SYMBOL(atanhf, std::, )
+SYMBOL(atanhl, std::, )
+SYMBOL(atanl, std::, )
 SYMBOL(atexit, std::, )
 SYMBOL(atof, std::, )
 SYMBOL(atoi, std::, )
@@ -116,17 +112,27 @@ SYMBOL(atomic_fetch_xor_explicit, std::, )
 SYMBOL(atomic_flag, std::, )
 SYMBOL(atomic_flag_clear, std::, )
 SYMBOL(atomic_flag_clear_explicit, std::, )
+SYMBOL(atomic_flag_notify_all, std::, )
+SYMBOL(atomic_flag_notify_one, std::, )
+SYMBOL(atomic_flag_test, std::, )
 SYMBOL(atomic_flag_test_and_set, std::, )
 SYMBOL(atomic_flag_test_and_set_explicit, std::, )
+SYMBOL(atomic_flag_test_explicit, std::, )
+SYMBOL(atomic_flag_wait, std::, )
+SYMBOL(atomic_flag_wait_explicit, std::, )
 SYMBOL(atomic_init, std::, )
-SYMBOL(atomic_is_lockfree, std::, )
+SYMBOL(atomic_is_lock_free, std::, )
 SYMBOL(atomic_load, std::, )
 SYMBOL(atomic_load_explicit, std::, )
+SYMBOL(atomic_notify_all, std::, )
+SYMBOL(atomic_notify_one, std::, )
 SYMBOL(atomic_ref, std::, )
 SYMBOL(atomic_signal_fence, std::, )
 SYMBOL(atomic_store, std::, )
 SYMBOL(atomic_store_explicit, std::, )
 SYMB

[PATCH] D143493: [flang][driver] Add support for -include flag in flang -fc1

2023-02-07 Thread Sergio Afonso via Phabricator via cfe-commits
skatrak created this revision.
skatrak added reviewers: dpalermo, jsjodin, domada, raghavendhra.
Herald added a reviewer: sscalpone.
Herald added a reviewer: awarzynski.
Herald added a subscriber: sunshaoce.
Herald added projects: Flang, All.
skatrak requested review of this revision.
Herald added subscribers: cfe-commits, jdoerfert.
Herald added a project: clang.

This patch adds support for the -include flag to include header files before
parsing the input. It should implement the same behavior as the flag with the
same name in clang.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D143493

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/PreprocessorOptions.h
  flang/include/flang/Parser/parsing.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Parser/parsing.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/include-file.f90

Index: flang/test/Driver/include-file.f90
===
--- /dev/null
+++ flang/test/Driver/include-file.f90
@@ -0,0 +1,13 @@
+! Ensure argument -include works as expected with an included header file.
+
+! RUN: %flang_fc1 -E -include "%S/Inputs/basic-header-one.h" %s  2>&1 | FileCheck %s --check-prefix=INCLUDED
+! RUN: not %flang_fc1 -E -include does-not-exist.h %s  2>&1 | FileCheck %s --check-prefix=MISSING
+
+! INCLUDED: program MainDirectoryOne
+! INCLUDED-NOT: program X
+
+! MISSING: error: Source file 'does-not-exist.h' was not found
+! MISSING-NOT: program
+
+program X
+end
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -144,6 +144,7 @@
 ! HELP-FC1-NEXT: -fsyntax-only  Run the preprocessor, parser and semantic analysis stages
 ! HELP-FC1-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
 ! HELP-FC1-NEXT: -help  Display available options
+! HELP-FC1-NEXT: -include Include file before parsing
 ! HELP-FC1-NEXT: -init-only Only execute frontend initialization
 ! HELP-FC1-NEXT: -IAdd directory to the end of the list of include search paths
 ! HELP-FC1-NEXT: -load Load the named plugin (dynamic shared object)
Index: flang/lib/Parser/parsing.cpp
===
--- flang/lib/Parser/parsing.cpp
+++ flang/lib/Parser/parsing.cpp
@@ -84,6 +84,24 @@
 prescanner.AddCompilerDirectiveSentinel("$omp");
 prescanner.AddCompilerDirectiveSentinel("$"); // OMP conditional line
   }
+
+  // Prescan -include's
+  for (auto include : options.includes) {
+const SourceFile *includeFile =
+allSources.Open(include, fileError, "."s /*prepend to search path*/);
+
+if (!fileError.str().empty()) {
+  ProvenanceRange range{allSources.AddCompilerInsertion(include)};
+  messages_.Say(range, "%s"_err_en_US, fileError.str());
+  return sourceFile;
+}
+CHECK(includeFile);
+
+ProvenanceRange range{
+allSources.AddIncludedFile(*includeFile, ProvenanceRange{})};
+prescanner.Prescan(range);
+  }
+
   ProvenanceRange range{allSources.AddIncludedFile(
   *sourceFile, ProvenanceRange{}, options.isModuleFile)};
   prescanner.Prescan(range);
Index: flang/lib/Frontend/CompilerInvocation.cpp
===
--- flang/lib/Frontend/CompilerInvocation.cpp
+++ flang/lib/Frontend/CompilerInvocation.cpp
@@ -543,6 +543,11 @@
args.filtered(clang::driver::options::OPT_fintrinsic_modules_path))
 opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue());
 
+  // Add the ordered list of -include's
+  for (const auto *currentArg :
+   args.filtered(clang::driver::options::OPT_include))
+opts.includes.emplace_back(currentArg->getValue());
+
   // -cpp/-nocpp
   if (const auto *currentArg = args.getLastArg(
   clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp))
@@ -914,6 +919,11 @@
   preprocessorOptions.searchDirectoriesFromIntrModPath.begin(),
   preprocessorOptions.searchDirectoriesFromIntrModPath.end());
 
+  // Adding includes specified by -include
+  fortranOptions.includes.insert(fortranOptions.includes.end(),
+ preprocessorOptions.includes.begin(),
+ preprocessorOptions.includes.end());
+
   //  Add the default intrinsic module directory
   fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir());
 
Index: flang/include/flang/Parser/parsing.h
===
--- flang/include/flang/Parser/parsing.h
+++ flang/include/flang/Parser/parsing.h
@@ -34,6 +34,7 @@
   std::vector searchDirectories;
   std::vector intrinsicModuleDirectories;
   std::vector predefinitions;
+  std::vector includes;
   bool instrumentedParse{false};
   bool i

[PATCH] D143486: [clangd] Fix a crash in semantic highlighting.

2023-02-07 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 495496.
hokein marked an inline comment as done.
hokein added a comment.

add a comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143486

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp


Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -519,10 +519,11 @@
 Loc = getHighlightableSpellingToken(Loc, SourceMgr);
 if (Loc.isInvalid())
   return std::nullopt;
-
+// We might have offsets in the main file that don't correspond to any
+// spelled tokens.
 const auto *Tok = TB.spelledTokenAt(Loc);
-assert(Tok);
-
+if (!Tok)
+  return std::nullopt;
 return halfOpenToRange(SourceMgr,
Tok->range(SourceMgr).toCharRange(SourceMgr));
   }


Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -519,10 +519,11 @@
 Loc = getHighlightableSpellingToken(Loc, SourceMgr);
 if (Loc.isInvalid())
   return std::nullopt;
-
+// We might have offsets in the main file that don't correspond to any
+// spelled tokens.
 const auto *Tok = TB.spelledTokenAt(Loc);
-assert(Tok);
-
+if (!Tok)
+  return std::nullopt;
 return halfOpenToRange(SourceMgr,
Tok->range(SourceMgr).toCharRange(SourceMgr));
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] 41a6085 - [clangd] Fix a crash in semantic highlighting.

2023-02-07 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2023-02-07T14:54:39+01:00
New Revision: 41a6085252efe4c2b806e03d923c0b0b35fc3baa

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

LOG: [clangd] Fix a crash in semantic highlighting.

We encounter a few internal reports that we're dereference a nullptr.
Unfortunately, no small reproduce testcase for this crash yet, but it makes the
clangd more robost on broken code.

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

Added: 


Modified: 
clang-tools-extra/clangd/SemanticHighlighting.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp 
b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index e3022ad131ff2..19f79f793420d 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -519,10 +519,11 @@ class HighlightingsBuilder {
 Loc = getHighlightableSpellingToken(Loc, SourceMgr);
 if (Loc.isInvalid())
   return std::nullopt;
-
+// We might have offsets in the main file that don't correspond to any
+// spelled tokens.
 const auto *Tok = TB.spelledTokenAt(Loc);
-assert(Tok);
-
+if (!Tok)
+  return std::nullopt;
 return halfOpenToRange(SourceMgr,
Tok->range(SourceMgr).toCharRange(SourceMgr));
   }



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


[PATCH] D143486: [clangd] Fix a crash in semantic highlighting.

2023-02-07 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG41a6085252ef: [clangd] Fix a crash in semantic highlighting. 
(authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143486

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp


Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -519,10 +519,11 @@
 Loc = getHighlightableSpellingToken(Loc, SourceMgr);
 if (Loc.isInvalid())
   return std::nullopt;
-
+// We might have offsets in the main file that don't correspond to any
+// spelled tokens.
 const auto *Tok = TB.spelledTokenAt(Loc);
-assert(Tok);
-
+if (!Tok)
+  return std::nullopt;
 return halfOpenToRange(SourceMgr,
Tok->range(SourceMgr).toCharRange(SourceMgr));
   }


Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -519,10 +519,11 @@
 Loc = getHighlightableSpellingToken(Loc, SourceMgr);
 if (Loc.isInvalid())
   return std::nullopt;
-
+// We might have offsets in the main file that don't correspond to any
+// spelled tokens.
 const auto *Tok = TB.spelledTokenAt(Loc);
-assert(Tok);
-
+if (!Tok)
+  return std::nullopt;
 return halfOpenToRange(SourceMgr,
Tok->range(SourceMgr).toCharRange(SourceMgr));
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D143214: [include-mapping] Add C-compatibility symbol entries.

2023-02-07 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 495502.
hokein added a comment.

rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143214

Files:
  clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
  clang/tools/include-mapping/cppreference_parser.py
  clang/tools/include-mapping/gen_std.py

Index: clang/tools/include-mapping/gen_std.py
===
--- clang/tools/include-mapping/gen_std.py
+++ clang/tools/include-mapping/gen_std.py
@@ -39,6 +39,7 @@
 import datetime
 import os
 import sys
+import re
 
 
 CODE_PREFIX = """\
@@ -170,6 +171,69 @@
   return headers
 
 
+def GetCCompatibilitySymbols(symbol):
+   # C++ form of the C standard headers.
+  c_compat_headers = {
+"",
+"",
+"",
+"",
+"",
+"",
+"",
+"",
+"",
+"",
+"",
+"",
+"",
+"",
+"",
+"",
+"",
+"",
+"",
+"",
+"",
+  }
+  # C++ [support.c.headers.other] 17.14.7
+  #..., behaves as if each name placed in the standard library namespace by
+  #the corresponding  header is placed within the global namespace
+  #scope, except for the functions described in [sf.cmath], the
+  #std​::​lerp function overloads ([c.math.lerp]), the declaration of
+  #std​::​byte ([cstddef.syn]), and the functions and function templates
+  #described in [support.types.byteops].
+  exception_symbols = {
+"(assoc_)?laguerre[f|l]?",
+"(assoc_|sph_)?legendre[f|l]?",
+"beta[f|l]?",
+"(comp_)?ellint_[1-3][f|l]?",
+"(cyl_|sph_)?bessel_[i-k][f|l]?",
+"(cyl_|sph_)?neumann[f|l]?",
+"expint[f|l]?",
+"hermite[f|l]?",
+"riemann_zeta[f|l]?",
+"lerp",
+"byte",
+  }
+  assert(len(symbol.headers) == 1)
+  header = symbol.headers[0]
+  if header not in c_compat_headers:
+return []
+  if any(re.fullmatch(x, symbol.name) for x in exception_symbols):
+return []
+
+  # Introduce two more entries, both in the global namespace, one using the
+  # C++-compat header and another using the C header.
+  results = []
+  if symbol.namespace != None:
+# avoid printing duplicated entries, for C macros!
+results.append(cppreference_parser.Symbol(symbol.name, None, [header]))
+  c_header = "<" + header[2:-1] +  ".h>" #  => 
+  results.append(cppreference_parser.Symbol(symbol.name, None, [c_header]))
+  return results
+
+
 def main():
   args = ParseArg()
   if args.symbols == 'cpp':
@@ -192,6 +256,7 @@
   # Zombie symbols that were available from the Standard Library, but are
   # removed in the following standards.
   (symbol_index_root, "zombie_names.html", "std::"),
+  (symbol_index_root, "macro.html", None),
 ]
   elif args.symbols == 'c':
 page_root = os.path.join(args.cppreference, "en", "c")
@@ -211,11 +276,14 @@
   print(CODE_PREFIX % (args.symbols.upper(), cppreference_modified_date))
   for symbol in symbols:
 if len(symbol.headers) == 1:
-  # SYMBOL(unqualified_name, namespace, header)
-  symbol.headers.extend(AdditionalHeadersForIOSymbols(symbol))
-  for header in symbol.headers:
-print("SYMBOL(%s, %s, %s)" % (symbol.name, symbol.namespace,
-  header))
+  augmented_symbols = [symbol]
+  augmented_symbols.extend(GetCCompatibilitySymbols(symbol))
+  for s in augmented_symbols:
+s.headers.extend(AdditionalHeadersForIOSymbols(s))
+for header in s.headers:
+  # SYMBOL(unqualified_name, namespace, header)
+  print("SYMBOL(%s, %s, %s)" % (s.name, s.namespace,
+header))
 elif len(symbol.headers) == 0:
   sys.stderr.write("No header found for symbol %s\n" % symbol.name)
 else:
Index: clang/tools/include-mapping/cppreference_parser.py
===
--- clang/tools/include-mapping/cppreference_parser.py
+++ clang/tools/include-mapping/cppreference_parser.py
@@ -30,7 +30,7 @@
 
   def __lt__(self, other):
 if self.namespace != other.namespace:
-  return self.namespace < other.namespace
+  return str(self.namespace) < str(other.namespace)
 return self.name < other.name
 
 
Index: clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
===
--- clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
+++ clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
@@ -9,15 +9,565 @@
 // Generated from cppreference offline HTML book (modified on 2022-07-30).
 //===--===//
 
+SYMBOL(ATOMIC_BOOL_LOCK_FREE, None, )
+SYMBOL(ATOMIC_CHAR16_T_LOCK_FREE, None, )
+SYMBOL(ATOMIC_CHAR32_T_LOCK_FREE, None, )
+SYMBOL(ATOMIC_CHAR8_T_LOCK_FREE, None, )
+SYMBOL(ATOMIC_CHAR_LOCK_FREE, None, )
+SYMBOL(ATOMIC_FLAG_INIT, None, )
+SYMBOL(ATOMIC_INT_LOCK_FREE, None, 

[PATCH] D143495: [AMDGPU ASAN] Remove reference to asan bitcode library

2023-02-07 Thread praveen velliengiri via Phabricator via cfe-commits
pvellien created this revision.
pvellien added reviewers: yaxunl, b-sumner.
Herald added subscribers: kosarev, kerbowa, tpr, dstuttard, jvesely, kzhuravl.
Herald added a project: All.
pvellien requested review of this revision.
Herald added subscribers: cfe-commits, wdng.
Herald added a project: clang.

The asan functions are now attributed as "used" in the device library, no need 
to keep the declaration of asan device preserve function.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D143495

Files:
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGenCUDA/amdgpu-asan.cu


Index: clang/test/CodeGenCUDA/amdgpu-asan.cu
===
--- clang/test/CodeGenCUDA/amdgpu-asan.cu
+++ /dev/null
@@ -1,31 +0,0 @@
-// Create a sample address sanitizer bitcode library.
-
-// RUN: %clang_cc1 -x ir -fcuda-is-device -triple amdgcn-amd-amdhsa 
-emit-llvm-bc \
-// RUN:   -disable-llvm-passes -o %t.asanrtl.bc %S/Inputs/amdgpu-asanrtl.ll
-
-// Check sanitizer runtime library functions survive
-// optimizations without being removed or parameters altered.
-
-// RUN: %clang_cc1 %s -emit-llvm -o - -triple=amdgcn-amd-amdhsa \
-// RUN:   -fcuda-is-device -target-cpu gfx906 -fsanitize=address \
-// RUN:   -mlink-bitcode-file %t.asanrtl.bc -x hip \
-// RUN:   | FileCheck -check-prefixes=ASAN %s
-
-// RUN: %clang_cc1 %s -emit-llvm -o - -triple=amdgcn-amd-amdhsa \
-// RUN:   -fcuda-is-device -target-cpu gfx906 -fsanitize=address \
-// RUN:   -O3 -mlink-bitcode-file %t.asanrtl.bc -x hip \
-// RUN:   | FileCheck -check-prefixes=ASAN %s
-
-// RUN: %clang_cc1 %s -emit-llvm -o - -triple=amdgcn-amd-amdhsa \
-// RUN:   -fcuda-is-device -target-cpu gfx906 -x hip \
-// RUN:   | FileCheck %s
-
-// REQUIRES: amdgpu-registered-target
-
-// ASAN-DAG: define weak void 
@__amdgpu_device_library_preserve_asan_functions()
-// ASAN-DAG: @__amdgpu_device_library_preserve_asan_functions_ptr = weak 
addrspace(1) constant ptr @__amdgpu_device_library_preserve_asan_functions
-// ASAN-DAG: @llvm.compiler.used = 
{{.*}}@__amdgpu_device_library_preserve_asan_functions_ptr
-// ASAN-DAG: define weak void @__asan_report_load1(i64 %{{.*}})
-
-// CHECK-NOT: @__amdgpu_device_library_preserve_asan_functions
-// CHECK-NOT: @__asan_report_load1
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -580,20 +580,6 @@
 EmitMainVoidAlias();
 
   if (getTriple().isAMDGPU()) {
-// Emit reference of __amdgpu_device_library_preserve_asan_functions to
-// preserve ASAN functions in bitcode libraries.
-if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
-  auto *FT = llvm::FunctionType::get(VoidTy, {});
-  auto *F = llvm::Function::Create(
-  FT, llvm::GlobalValue::ExternalLinkage,
-  "__amdgpu_device_library_preserve_asan_functions", &getModule());
-  auto *Var = new llvm::GlobalVariable(
-  getModule(), FT->getPointerTo(),
-  /*isConstant=*/true, llvm::GlobalValue::WeakAnyLinkage, F,
-  "__amdgpu_device_library_preserve_asan_functions_ptr", nullptr,
-  llvm::GlobalVariable::NotThreadLocal);
-  addCompilerUsedGlobal(Var);
-}
 // Emit amdgpu_code_object_version module flag, which is code object 
version
 // times 100.
 if (getTarget().getTargetOpts().CodeObjectVersion !=


Index: clang/test/CodeGenCUDA/amdgpu-asan.cu
===
--- clang/test/CodeGenCUDA/amdgpu-asan.cu
+++ /dev/null
@@ -1,31 +0,0 @@
-// Create a sample address sanitizer bitcode library.
-
-// RUN: %clang_cc1 -x ir -fcuda-is-device -triple amdgcn-amd-amdhsa -emit-llvm-bc \
-// RUN:   -disable-llvm-passes -o %t.asanrtl.bc %S/Inputs/amdgpu-asanrtl.ll
-
-// Check sanitizer runtime library functions survive
-// optimizations without being removed or parameters altered.
-
-// RUN: %clang_cc1 %s -emit-llvm -o - -triple=amdgcn-amd-amdhsa \
-// RUN:   -fcuda-is-device -target-cpu gfx906 -fsanitize=address \
-// RUN:   -mlink-bitcode-file %t.asanrtl.bc -x hip \
-// RUN:   | FileCheck -check-prefixes=ASAN %s
-
-// RUN: %clang_cc1 %s -emit-llvm -o - -triple=amdgcn-amd-amdhsa \
-// RUN:   -fcuda-is-device -target-cpu gfx906 -fsanitize=address \
-// RUN:   -O3 -mlink-bitcode-file %t.asanrtl.bc -x hip \
-// RUN:   | FileCheck -check-prefixes=ASAN %s
-
-// RUN: %clang_cc1 %s -emit-llvm -o - -triple=amdgcn-amd-amdhsa \
-// RUN:   -fcuda-is-device -target-cpu gfx906 -x hip \
-// RUN:   | FileCheck %s
-
-// REQUIRES: amdgpu-registered-target
-
-// ASAN-DAG: define weak void @__amdgpu_device_library_preserve_asan_functions()
-// ASAN-DAG: @__amdgpu_device_library_preserve_asan_functions_ptr = weak addrspace(1) constant ptr @__amdgpu_device_library_preserve_asan_functions
-// ASAN-DAG: @llvm.compiler.used = {{.*}}@__amdgpu_device_library_preserve_asan_functions_ptr
-

[PATCH] D143414: [clang] refactor FileManager::GetUniqueIDMapping

2023-02-07 Thread Richard Howell via Phabricator via cfe-commits
rmaz updated this revision to Diff 495512.
rmaz edited the summary of this revision.
rmaz added a comment.

Use FileEntryRef, rename method


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143414

Files:
  clang/include/clang/Basic/FileManager.h
  clang/lib/Basic/FileManager.cpp
  clang/lib/Serialization/ASTWriter.cpp

Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -169,17 +169,10 @@
 
   const HeaderSearch &HS = PP.getHeaderSearchInfo();
 
-  SmallVector FilesByUID;
-  HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
-
-  if (FilesByUID.size() > HS.header_file_size())
-FilesByUID.resize(HS.header_file_size());
-
-  for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
-const FileEntry *File = FilesByUID[UID];
-if (!File)
-  continue;
+  SmallVector FileEntries;
+  HS.getFileMgr().getSeenNonVirtualFileEntries(FileEntries);
 
+  for (auto File : FileEntries) {
 const HeaderFileInfo *HFI =
 HS.getExistingFileInfo(File, /*WantExternal*/ false);
 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
@@ -1918,16 +1911,10 @@
 }
   }
 
-  SmallVector FilesByUID;
-  HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
+  SmallVector FileEntries;
+  HS.getFileMgr().getSeenNonVirtualFileEntries(FileEntries);
 
-  if (FilesByUID.size() > HS.header_file_size())
-FilesByUID.resize(HS.header_file_size());
-
-  for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
-const FileEntry *File = FilesByUID[UID];
-if (!File)
-  continue;
+  for (auto File : FileEntries) {
 
 // Get the file info. This will load info from the external source if
 // necessary. Skip emitting this file if we have no information on it
@@ -1941,7 +1928,7 @@
   continue;
 
 // Massage the file path into an appropriate form.
-StringRef Filename = File->getName();
+StringRef Filename = File.getName();
 SmallString<128> FilenameTmp(Filename);
 if (PreparePathForOutput(FilenameTmp)) {
   // If we performed any translation on the file name at all, we need to
@@ -1950,9 +1937,8 @@
   SavedStrings.push_back(Filename.data());
 }
 
-HeaderFileInfoTrait::key_type Key = {
-  Filename, File->getSize(), getTimestampForOutput(File)
-};
+HeaderFileInfoTrait::key_type Key = {Filename, File.getSize(),
+ getTimestampForOutput(File)};
 HeaderFileInfoTrait::data_type Data = {
   *HFI, HS.getModuleMap().findResolvedModulesForHeader(File), {}
 };
Index: clang/lib/Basic/FileManager.cpp
===
--- clang/lib/Basic/FileManager.cpp
+++ clang/lib/Basic/FileManager.cpp
@@ -611,25 +611,26 @@
   return std::error_code();
 }
 
-void FileManager::GetUniqueIDMapping(
-SmallVectorImpl &UIDToFiles) const {
-  UIDToFiles.clear();
-  UIDToFiles.resize(NextFileUID);
-
-  // Map file entries
-  for (llvm::StringMap,
-   llvm::BumpPtrAllocator>::const_iterator
-   FE = SeenFileEntries.begin(),
-   FEEnd = SeenFileEntries.end();
-   FE != FEEnd; ++FE)
-if (llvm::ErrorOr Entry = FE->getValue()) {
-  if (const auto *FE = Entry->V.dyn_cast())
-UIDToFiles[FE->getUID()] = FE;
-}
+void FileManager::getSeenNonVirtualFileEntries(
+SmallVectorImpl &Entries) const {
+  Entries.reserve(SeenFileEntries.size());
+
+  for (const auto &Entry : SeenFileEntries) {
+if (auto Value = Entry.getValue())
+  // Ignore VFS-mapped entries, they will have a separate on-disk
+  // file entry.
+  if (Value->V.is())
+Entries.push_back(FileEntryRef(Entry));
+  }
+
+  // We want the file entries in deterministic order for
+  // module serialization.
+  llvm::sort(Entries, [](FileEntryRef &A, FileEntryRef &B) {
+if (A.getUID() != B.getUID())
+  return A.getUID() < B.getUID();
 
-  // Map virtual file entries
-  for (const auto &VFE : VirtualFileEntries)
-UIDToFiles[VFE->getUID()] = VFE;
+return A.getName() < B.getName();
+  });
 }
 
 StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {
Index: clang/include/clang/Basic/FileManager.h
===
--- clang/include/clang/Basic/FileManager.h
+++ clang/include/clang/Basic/FileManager.h
@@ -310,10 +310,10 @@
   /// \returns true if \c Path changed to absolute.
   bool makeAbsolutePath(SmallVectorImpl &Path) const;
 
-  /// Produce an array mapping from the unique IDs assigned to each
-  /// file to the corresponding FileEntry pointer.
-  void GetUniqueIDMapping(
-SmallVectorImpl &UIDToFiles) const;
+  /// Produce an array of seen FileEntryRef. The entries will be sorted
+  /// b

[PATCH] D143496: [clangd] Add support for missing includes analysis.

2023-02-07 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo created this revision.
Herald added subscribers: kadircet, arphaman.
Herald added a project: All.
VitaNuo requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D143496

Files:
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h

Index: clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
===
--- clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
+++ clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
@@ -73,6 +73,8 @@
 std::string fixIncludes(const AnalysisResults &Results, llvm::StringRef Code,
 const format::FormatStyle &IncludeStyle);
 
+static std::string spellHeader(const Header &H, HeaderSearch &HS,
+   const FileEntry *Main);
 } // namespace include_cleaner
 } // namespace clang
 
Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -385,6 +385,43 @@
Pointee(writtenInclusion("\"dir/unused.h\"";
 }
 
+TEST(IncludeCleaner, GetMissingHeaders) {
+  llvm::StringLiteral MainFile = R"cpp(
+#include "a.h"
+#include "dir/c.h"
+#include 
+
+void foo() {
+  b();
+  d();
+  f();
+})cpp";
+  // Build expected ast with symbols coming from headers.
+  TestTU TU;
+  TU.Filename = "foo.cpp";
+  TU.AdditionalFiles["foo.h"] = guard("void foo();");
+  TU.AdditionalFiles["a.h"] = guard("#include \"b.h\"");
+  TU.AdditionalFiles["b.h"] = guard("void b();");
+
+  TU.AdditionalFiles["dir/c.h"] = guard("#include \"d.h\"");
+  TU.AdditionalFiles["dir/d.h"] = guard("void d();");
+
+  TU.AdditionalFiles["system/e.h"] = guard("#include ");
+  TU.AdditionalFiles["system/f.h"] = guard("void f();");
+  TU.ExtraArgs.push_back("-isystem" + testPath("system"));
+
+  TU.Code = MainFile.str();
+  ParsedAST AST = TU.build();
+
+  std::vector> MissingIncludes =
+  computeMissingIncludes(AST);
+
+  std::pair b{"\"b.h\"", 86};
+  std::pair d{"\"dir/d.h\"", 97};
+  std::pair h{"", 108};
+  EXPECT_THAT(MissingIncludes, UnorderedElementsAre(b, d, h));
+}
+
 TEST(IncludeCleaner, VirtualBuffers) {
   TestTU TU;
   TU.Code = R"cpp(
@@ -628,6 +665,7 @@
 
   Config Cfg;
   Cfg.Diagnostics.UnusedIncludes = Config::Strict;
+  Cfg.Diagnostics.MissingIncludes = Config::MissingIncludesPolicy::Strict;
   WithContextValue Ctx(Config::Key, std::move(Cfg));
   ParsedAST AST = TU.build();
   EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ -691,9 +691,14 @@
   if (Result.Diags) {
 auto UnusedHeadersDiags =
 issueUnusedIncludesDiagnostics(Result, Inputs.Contents);
+auto MissingHeadersDiags =
+issueMissingIncludesDiagnostics(Result, Inputs.Contents);
 Result.Diags->insert(Result.Diags->end(),
  make_move_iterator(UnusedHeadersDiags.begin()),
  make_move_iterator(UnusedHeadersDiags.end()));
+Result.Diags->insert(Result.Diags->end(),
+ make_move_iterator(MissingHeadersDiags.begin()),
+ make_move_iterator(MissingHeadersDiags.end()));
   }
   return std::move(Result);
 }
Index: clang-tools-extra/clangd/IncludeCleaner.h
===
--- clang-tools-extra/clangd/IncludeCleaner.h
+++ clang-tools-extra/clangd/IncludeCleaner.h
@@ -96,12 +96,16 @@
   const llvm::DenseSet &ReferencedFiles,
   const llvm::StringSet<> &ReferencedPublicHeaders);
 
+std::vector>
+computeMissingIncludes(ParsedAST &AST);
 std::vector computeUnusedIncludes(ParsedAST &AST);
 // The same as computeUnusedIncludes, but it is an experimental and
 // include-cleaner-lib-based implementation.
 std::vector
 computeUnusedIncludesExperimental(ParsedAST &AST);
 
+std::vector issueMissingIncludesDiagnostics(ParsedAST &AST,
+  llvm::StringRef Code);
 std::vector issueUnusedIncludesDiagnostics(ParsedAST &AST,
  llvm::St

[PATCH] D143496: [clangd] Add support for missing includes analysis.

2023-02-07 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 495516.
VitaNuo added a comment.

Undo turning spellHeader method public.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143496

Files:
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h

Index: clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
===
--- clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
+++ clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
@@ -72,7 +72,6 @@
 /// The FormatStyle must be C++ or ObjC (to support include ordering).
 std::string fixIncludes(const AnalysisResults &Results, llvm::StringRef Code,
 const format::FormatStyle &IncludeStyle);
-
 } // namespace include_cleaner
 } // namespace clang
 
Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -385,6 +385,43 @@
Pointee(writtenInclusion("\"dir/unused.h\"";
 }
 
+TEST(IncludeCleaner, GetMissingHeaders) {
+  llvm::StringLiteral MainFile = R"cpp(
+#include "a.h"
+#include "dir/c.h"
+#include 
+
+void foo() {
+  b();
+  d();
+  f();
+})cpp";
+  // Build expected ast with symbols coming from headers.
+  TestTU TU;
+  TU.Filename = "foo.cpp";
+  TU.AdditionalFiles["foo.h"] = guard("void foo();");
+  TU.AdditionalFiles["a.h"] = guard("#include \"b.h\"");
+  TU.AdditionalFiles["b.h"] = guard("void b();");
+
+  TU.AdditionalFiles["dir/c.h"] = guard("#include \"d.h\"");
+  TU.AdditionalFiles["dir/d.h"] = guard("void d();");
+
+  TU.AdditionalFiles["system/e.h"] = guard("#include ");
+  TU.AdditionalFiles["system/f.h"] = guard("void f();");
+  TU.ExtraArgs.push_back("-isystem" + testPath("system"));
+
+  TU.Code = MainFile.str();
+  ParsedAST AST = TU.build();
+
+  std::vector> MissingIncludes =
+  computeMissingIncludes(AST);
+
+  std::pair b{"\"b.h\"", 86};
+  std::pair d{"\"dir/d.h\"", 97};
+  std::pair h{"", 108};
+  EXPECT_THAT(MissingIncludes, UnorderedElementsAre(b, d, h));
+}
+
 TEST(IncludeCleaner, VirtualBuffers) {
   TestTU TU;
   TU.Code = R"cpp(
@@ -628,6 +665,7 @@
 
   Config Cfg;
   Cfg.Diagnostics.UnusedIncludes = Config::Strict;
+  Cfg.Diagnostics.MissingIncludes = Config::MissingIncludesPolicy::Strict;
   WithContextValue Ctx(Config::Key, std::move(Cfg));
   ParsedAST AST = TU.build();
   EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ -691,9 +691,14 @@
   if (Result.Diags) {
 auto UnusedHeadersDiags =
 issueUnusedIncludesDiagnostics(Result, Inputs.Contents);
+auto MissingHeadersDiags =
+issueMissingIncludesDiagnostics(Result, Inputs.Contents);
 Result.Diags->insert(Result.Diags->end(),
  make_move_iterator(UnusedHeadersDiags.begin()),
  make_move_iterator(UnusedHeadersDiags.end()));
+Result.Diags->insert(Result.Diags->end(),
+ make_move_iterator(MissingHeadersDiags.begin()),
+ make_move_iterator(MissingHeadersDiags.end()));
   }
   return std::move(Result);
 }
Index: clang-tools-extra/clangd/IncludeCleaner.h
===
--- clang-tools-extra/clangd/IncludeCleaner.h
+++ clang-tools-extra/clangd/IncludeCleaner.h
@@ -96,12 +96,16 @@
   const llvm::DenseSet &ReferencedFiles,
   const llvm::StringSet<> &ReferencedPublicHeaders);
 
+std::vector>
+computeMissingIncludes(ParsedAST &AST);
 std::vector computeUnusedIncludes(ParsedAST &AST);
 // The same as computeUnusedIncludes, but it is an experimental and
 // include-cleaner-lib-based implementation.
 std::vector
 computeUnusedIncludesExperimental(ParsedAST &AST);
 
+std::vector issueMissingIncludesDiagnostics(ParsedAST &AST,
+  llvm::StringRef Code);
 std::vector issueUnusedIncludesDiagnostics(ParsedAST &AST,
  llvm::StringRef Code);
 
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
==

[PATCH] D143496: [clangd] Add support for missing includes analysis.

2023-02-07 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 495517.
VitaNuo added a comment.

Remove extra line.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143496

Files:
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -385,6 +385,43 @@
Pointee(writtenInclusion("\"dir/unused.h\"";
 }
 
+TEST(IncludeCleaner, GetMissingHeaders) {
+  llvm::StringLiteral MainFile = R"cpp(
+#include "a.h"
+#include "dir/c.h"
+#include 
+
+void foo() {
+  b();
+  d();
+  f();
+})cpp";
+  // Build expected ast with symbols coming from headers.
+  TestTU TU;
+  TU.Filename = "foo.cpp";
+  TU.AdditionalFiles["foo.h"] = guard("void foo();");
+  TU.AdditionalFiles["a.h"] = guard("#include \"b.h\"");
+  TU.AdditionalFiles["b.h"] = guard("void b();");
+
+  TU.AdditionalFiles["dir/c.h"] = guard("#include \"d.h\"");
+  TU.AdditionalFiles["dir/d.h"] = guard("void d();");
+
+  TU.AdditionalFiles["system/e.h"] = guard("#include ");
+  TU.AdditionalFiles["system/f.h"] = guard("void f();");
+  TU.ExtraArgs.push_back("-isystem" + testPath("system"));
+
+  TU.Code = MainFile.str();
+  ParsedAST AST = TU.build();
+
+  std::vector> MissingIncludes =
+  computeMissingIncludes(AST);
+
+  std::pair b{"\"b.h\"", 86};
+  std::pair d{"\"dir/d.h\"", 97};
+  std::pair h{"", 108};
+  EXPECT_THAT(MissingIncludes, UnorderedElementsAre(b, d, h));
+}
+
 TEST(IncludeCleaner, VirtualBuffers) {
   TestTU TU;
   TU.Code = R"cpp(
@@ -628,6 +665,7 @@
 
   Config Cfg;
   Cfg.Diagnostics.UnusedIncludes = Config::Strict;
+  Cfg.Diagnostics.MissingIncludes = Config::MissingIncludesPolicy::Strict;
   WithContextValue Ctx(Config::Key, std::move(Cfg));
   ParsedAST AST = TU.build();
   EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ -691,9 +691,14 @@
   if (Result.Diags) {
 auto UnusedHeadersDiags =
 issueUnusedIncludesDiagnostics(Result, Inputs.Contents);
+auto MissingHeadersDiags =
+issueMissingIncludesDiagnostics(Result, Inputs.Contents);
 Result.Diags->insert(Result.Diags->end(),
  make_move_iterator(UnusedHeadersDiags.begin()),
  make_move_iterator(UnusedHeadersDiags.end()));
+Result.Diags->insert(Result.Diags->end(),
+ make_move_iterator(MissingHeadersDiags.begin()),
+ make_move_iterator(MissingHeadersDiags.end()));
   }
   return std::move(Result);
 }
Index: clang-tools-extra/clangd/IncludeCleaner.h
===
--- clang-tools-extra/clangd/IncludeCleaner.h
+++ clang-tools-extra/clangd/IncludeCleaner.h
@@ -96,12 +96,16 @@
   const llvm::DenseSet &ReferencedFiles,
   const llvm::StringSet<> &ReferencedPublicHeaders);
 
+std::vector>
+computeMissingIncludes(ParsedAST &AST);
 std::vector computeUnusedIncludes(ParsedAST &AST);
 // The same as computeUnusedIncludes, but it is an experimental and
 // include-cleaner-lib-based implementation.
 std::vector
 computeUnusedIncludesExperimental(ParsedAST &AST);
 
+std::vector issueMissingIncludesDiagnostics(ParsedAST &AST,
+  llvm::StringRef Code);
 std::vector issueUnusedIncludesDiagnostics(ParsedAST &AST,
  llvm::StringRef Code);
 
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -20,6 +20,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/Basic/FileEntry.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Lex/HeaderSearch.h"
@@ -28,12 +29,14 @@
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/STLFunctionalExtras.h"
 #include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Regex.h"
 #includ

[PATCH] D143478: [RFC][Flang][driver] Try to support `flang -fc1as`

2023-02-07 Thread Shao-Ce SUN via Phabricator via cfe-commits
sunshaoce updated this revision to Diff 495522.
sunshaoce added a comment.

Add a test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143478

Files:
  clang/include/clang/Driver/Options.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Flang.cpp
  clang/lib/Driver/ToolChains/Flang.h
  flang/test/Driver/asm-code-gen-x86.s
  flang/test/lit.cfg.py
  flang/tools/flang-driver/CMakeLists.txt
  flang/tools/flang-driver/driver.cpp
  flang/tools/flang-driver/fc1as_main.cpp

Index: flang/tools/flang-driver/fc1as_main.cpp
===
--- /dev/null
+++ flang/tools/flang-driver/fc1as_main.cpp
@@ -0,0 +1,672 @@
+//===-- fc1as_main.cpp - Flang Assembler  -===//
+//
+// 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 is the entry point to the flang -fc1as functionality, which implements
+// the direct interface to the LLVM MC based assembler.
+//
+//===--===//
+
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Driver/DriverDiagnostic.h"
+#include "clang/Driver/Options.h"
+#include "clang/Frontend/FrontendDiagnostic.h"
+#include "clang/Frontend/TextDiagnosticPrinter.h"
+#include "clang/Frontend/Utils.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringSwitch.h"
+#include "llvm/ADT/Triple.h"
+#include "llvm/IR/DataLayout.h"
+#include "llvm/MC/MCAsmBackend.h"
+#include "llvm/MC/MCAsmInfo.h"
+#include "llvm/MC/MCCodeEmitter.h"
+#include "llvm/MC/MCContext.h"
+#include "llvm/MC/MCInstrInfo.h"
+#include "llvm/MC/MCObjectFileInfo.h"
+#include "llvm/MC/MCObjectWriter.h"
+#include "llvm/MC/MCParser/MCAsmParser.h"
+#include "llvm/MC/MCParser/MCTargetAsmParser.h"
+#include "llvm/MC/MCRegisterInfo.h"
+#include "llvm/MC/MCSectionMachO.h"
+#include "llvm/MC/MCStreamer.h"
+#include "llvm/MC/MCSubtargetInfo.h"
+#include "llvm/MC/MCTargetOptions.h"
+#include "llvm/MC/TargetRegistry.h"
+#include "llvm/Option/Arg.h"
+#include "llvm/Option/ArgList.h"
+#include "llvm/Option/OptTable.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/FormattedStream.h"
+#include "llvm/Support/Host.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Process.h"
+#include "llvm/Support/Signals.h"
+#include "llvm/Support/SourceMgr.h"
+#include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/Timer.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+#include 
+#include 
+using namespace clang;
+using namespace clang::driver;
+using namespace clang::driver::options;
+using namespace llvm;
+using namespace llvm::opt;
+
+namespace {
+
+/// Helper class for representing a single invocation of the assembler.
+struct AssemblerInvocation {
+  /// @name Target Options
+  /// @{
+
+  /// The name of the target triple to assemble for.
+  std::string triple;
+
+  /// If given, the name of the target CPU to determine which instructions
+  /// are legal.
+  std::string cpu;
+
+  /// The list of target specific features to enable or disable -- this should
+  /// be a list of strings starting with '+' or '-'.
+  std::vector features;
+
+  /// The list of symbol definitions.
+  std::vector symbolDefs;
+
+  /// @}
+  /// @name Language Options
+  /// @{
+
+  std::vector includePaths;
+  unsigned noInitialTextSection : 1;
+  unsigned saveTemporaryLabels : 1;
+  unsigned genDwarfForAssembly : 1;
+  unsigned relaxElfRelocations : 1;
+  unsigned dwarf64 : 1;
+  unsigned dwarfVersion;
+  std::string dwarfDebugFlags;
+  std::string dwarfDebugProducer;
+  std::string debugCompilationDir;
+  std::map debugPrefixMap;
+  llvm::DebugCompressionType compressDebugSections =
+  llvm::DebugCompressionType::None;
+  std::string mainFileName;
+  std::string splitDwarfOutput;
+
+  /// @}
+  /// @name Frontend Options
+  /// @{
+
+  std::string inputFile;
+  std::vector llvmArgs;
+  std::string outputPath;
+  enum FileType {
+FT_Asm,  ///< Assembly (.s) output, transliterate mode.
+FT_Null, ///< No output, for timing purposes.
+FT_Obj   ///< Object file output.
+  };
+  FileType outputType;
+  unsigned showHelp : 1;
+  unsigned showVersion : 1;
+
+  /// @}
+  /// @name Transliterate Options
+  /// @{
+
+  unsigned outputAsmVariant;
+  unsigned showEncoding : 1;
+  unsigned showInst : 1;
+
+  /// @}
+  /// @name Assembler Options
+  /// @{
+
+  unsigned relaxAll : 1;
+  unsigned noExecStack : 1;
+  unsig

[PATCH] D142914: [MLIR][OpenMP] Added OMPIRBuilder support for Target Data directives.

2023-02-07 Thread Akash Banerjee via Phabricator via cfe-commits
TIFitis updated this revision to Diff 495530.
TIFitis edited the summary of this revision.
TIFitis added a comment.

Added explicit failure for use_device_ptr and use_device_addr clauses.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142914

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPConstants.h
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
  llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
  mlir/include/mlir/Target/LLVMIR/Dialect/Utils.h
  mlir/lib/Target/LLVMIR/Dialect/OpenACC/OpenACCToLLVMIRTranslation.cpp
  mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp

Index: mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
===
--- mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -15,10 +15,12 @@
 #include "mlir/IR/IRMapping.h"
 #include "mlir/IR/Operation.h"
 #include "mlir/Support/LLVM.h"
+#include "mlir/Target/LLVMIR/Dialect/Utils.h"
 #include "mlir/Target/LLVMIR/ModuleTranslation.h"
 
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/TypeSwitch.h"
+#include "llvm/Frontend/OpenMP/OMPConstants.h"
 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
 #include "llvm/IR/DebugInfoMetadata.h"
 #include "llvm/IR/IRBuilder.h"
@@ -1338,6 +1340,191 @@
   return success();
 }
 
+/// Process MapOperands for Target Data directives.
+static LogicalResult processMapOperand(
+llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation,
+const SmallVector &mapOperands, const ArrayAttr &mapTypes,
+SmallVector &mapTypeFlags,
+SmallVectorImpl &mapNames,
+struct llvm::OpenMPIRBuilder::MapperAllocas &mapperAllocas) {
+  auto numMapOperands = mapOperands.size();
+  llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
+  llvm::PointerType *i8PtrTy = builder.getInt8PtrTy();
+  llvm::ArrayType *arrI8PtrTy = llvm::ArrayType::get(i8PtrTy, numMapOperands);
+  llvm::IntegerType *i64Ty = builder.getInt64Ty();
+  llvm::ArrayType *arrI64Ty = llvm::ArrayType::get(i64Ty, numMapOperands);
+
+  unsigned index = 0;
+  for (const auto &mapOp : mapOperands) {
+const auto &mapTypeOp = mapTypes[index];
+
+llvm::Value *mapOpValue = moduleTranslation.lookupValue(mapOp);
+llvm::Value *mapOpPtrBase;
+llvm::Value *mapOpPtr;
+llvm::Value *mapOpSize;
+
+if (mapOp.getType().isa()) {
+  mapOpPtrBase = mapOpValue;
+  mapOpPtr = mapOpValue;
+  mapOpSize = ompBuilder->getSizeInBytes(mapOpValue);
+} else {
+  return failure();
+}
+
+// Store base pointer extracted from operand into the i-th position of
+// argBase.
+llvm::Value *ptrBaseGEP = builder.CreateInBoundsGEP(
+arrI8PtrTy, mapperAllocas.ArgsBase,
+{builder.getInt32(0), builder.getInt32(index)});
+llvm::Value *ptrBaseCast = builder.CreateBitCast(
+ptrBaseGEP, mapOpPtrBase->getType()->getPointerTo());
+builder.CreateStore(mapOpPtrBase, ptrBaseCast);
+
+// Store pointer extracted from operand into the i-th position of args.
+llvm::Value *ptrGEP = builder.CreateInBoundsGEP(
+arrI8PtrTy, mapperAllocas.Args,
+{builder.getInt32(0), builder.getInt32(index)});
+llvm::Value *ptrCast =
+builder.CreateBitCast(ptrGEP, mapOpPtr->getType()->getPointerTo());
+builder.CreateStore(mapOpPtr, ptrCast);
+
+// Store size extracted from operand into the i-th position of argSizes.
+llvm::Value *sizeGEP = builder.CreateInBoundsGEP(
+arrI64Ty, mapperAllocas.ArgSizes,
+{builder.getInt32(0), builder.getInt32(index)});
+builder.CreateStore(mapOpSize, sizeGEP);
+
+mapTypeFlags.push_back(mapTypeOp.dyn_cast().getInt());
+llvm::Constant *mapName =
+mlir::LLVM::createMappingInformation(mapOp.getLoc(), *ompBuilder);
+mapNames.push_back(mapName);
+++index;
+  }
+
+  return success();
+}
+
+static LogicalResult
+convertOmpTargetData(Operation *op, llvm::IRBuilderBase &builder,
+ LLVM::ModuleTranslation &moduleTranslation) {
+  unsigned numMapOperands;
+  llvm::Function *mapperFunc;
+  llvm::Value *ifCond = nullptr;
+  int64_t deviceID = llvm::omp::OMP_DEVICEID_UNDEF;
+  SmallVector mapOperands;
+  ArrayAttr mapTypes;
+
+  llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
+
+  LogicalResult result =
+  llvm::TypeSwitch(op)
+  .Case([&](omp::DataOp dataOp) {
+if (dataOp.getUseDeviceAddr().size() ||
+dataOp.getUseDevicePtr().size())
+  return failure();
+
+if (auto ifExprVar = dataOp.getIfExpr())
+  ifCond = moduleTranslation.lookupValue(ifExprVar);
+
+if (auto devId = dataOp.getDevice())
+  if (auto const

[PATCH] D142905: Change multilib selection algorithm

2023-02-07 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings updated this revision to Diff 495532.
michaelplatings marked an inline comment as done.
michaelplatings added a comment.

Apply improvements suggested by @peter.smith


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142905

Files:
  clang/include/clang/Driver/Multilib.h
  clang/include/clang/Driver/MultilibBuilder.h
  clang/lib/Driver/Multilib.cpp
  clang/lib/Driver/MultilibBuilder.cpp
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/CommonArgs.h
  clang/lib/Driver/ToolChains/Fuchsia.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/unittests/Driver/MultilibBuilderTest.cpp
  clang/unittests/Driver/MultilibTest.cpp

Index: clang/unittests/Driver/MultilibTest.cpp
===
--- clang/unittests/Driver/MultilibTest.cpp
+++ clang/unittests/Driver/MultilibTest.cpp
@@ -33,14 +33,14 @@
 }
 
 TEST(MultilibTest, OpEqReflexivity3) {
-  Multilib M1({}, {}, {}, 0, {"+foo"});
-  Multilib M2({}, {}, {}, 0, {"+foo"});
+  Multilib M1({}, {}, {}, {"+foo"});
+  Multilib M2({}, {}, {}, {"+foo"});
   ASSERT_TRUE(M1 == M2) << "Multilibs with the same flag should be the same";
 }
 
 TEST(MultilibTest, OpEqInequivalence1) {
-  Multilib M1({}, {}, {}, 0, {"+foo"});
-  Multilib M2({}, {}, {}, 0, {"-foo"});
+  Multilib M1({}, {}, {}, {"+foo"});
+  Multilib M2({}, {}, {}, {"-foo"});
   ASSERT_FALSE(M1 == M2) << "Multilibs with conflicting flags are not the same";
   ASSERT_FALSE(M2 == M1)
   << "Multilibs with conflicting flags are not the same (commuted)";
@@ -48,7 +48,7 @@
 
 TEST(MultilibTest, OpEqInequivalence2) {
   Multilib M1;
-  Multilib M2({}, {}, {}, 0, {"+foo"});
+  Multilib M2({}, {}, {}, {"+foo"});
   ASSERT_FALSE(M1 == M2) << "Flags make Multilibs different";
 }
 
@@ -124,9 +124,9 @@
 }
 
 TEST(MultilibTest, Construction3) {
-  Multilib M({}, {}, {}, 0, {"+f1", "+f2", "-f3"});
-  for (Multilib::flags_list::const_iterator I = M.flags().begin(),
-E = M.flags().end();
+  Multilib M({}, {}, {}, {"+f1", "+f2", "-f3"});
+  for (Multilib::flag_set::const_iterator I = M.flags().begin(),
+  E = M.flags().end();
I != E; ++I) {
 ASSERT_TRUE(llvm::StringSwitch(*I)
 .Cases("+f1", "+f2", "-f3", true)
@@ -149,20 +149,41 @@
 
 TEST(MultilibTest, SetPriority) {
   MultilibSet MS({
-  Multilib("/foo", {}, {}, 1, {"+foo"}),
-  Multilib("/bar", {}, {}, 2, {"+bar"}),
+  Multilib("/foo", {}, {}, {"+foo"}),
+  Multilib("/bar", {}, {}, {"+bar"}),
   });
-  Multilib::flags_list Flags1 = {"+foo", "-bar"};
+  Multilib::flag_set Flags1 = {"+foo", "-bar"};
   Multilib Selection1;
   ASSERT_TRUE(MS.select(Flags1, Selection1))
   << "Flag set was {\"+foo\"}, but selection not found";
   ASSERT_TRUE(Selection1.gccSuffix() == "/foo")
   << "Selection picked " << Selection1 << " which was not expected";
 
-  Multilib::flags_list Flags2 = {"+foo", "+bar"};
+  Multilib::flag_set Flags2 = {"+foo", "+bar"};
   Multilib Selection2;
   ASSERT_TRUE(MS.select(Flags2, Selection2))
   << "Flag set was {\"+bar\"}, but selection not found";
   ASSERT_TRUE(Selection2.gccSuffix() == "/bar")
   << "Selection picked " << Selection2 << " which was not expected";
 }
+
+TEST(MultilibTest, SelectMultiple) {
+  MultilibSet MS({
+  Multilib("/a", {}, {}, {"x"}),
+  Multilib("/b", {}, {}, {"y"}),
+  });
+  std::vector Selection;
+
+  Selection = MS.select({"x"});
+  ASSERT_EQ(1u, Selection.size());
+  EXPECT_EQ("/a", Selection[0].gccSuffix());
+
+  Selection = MS.select({"y"});
+  ASSERT_EQ(1u, Selection.size());
+  EXPECT_EQ("/b", Selection[0].gccSuffix());
+
+  Selection = MS.select({"y", "x"});
+  ASSERT_EQ(2u, Selection.size());
+  EXPECT_EQ("/a", Selection[0].gccSuffix());
+  EXPECT_EQ("/b", Selection[1].gccSuffix());
+}
Index: clang/unittests/Driver/MultilibBuilderTest.cpp
===
--- clang/unittests/Driver/MultilibBuilderTest.cpp
+++ clang/unittests/Driver/MultilibBuilderTest.cpp
@@ -157,14 +157,14 @@
 .Maybe(MultilibBuilder("64").flag("+m64"))
 .makeMultilibSet();
 
-  Multilib::flags_list FlagM64 = {"+m64"};
+  Multilib::flag_set FlagM64 = {"+m64"};
   Multilib SelectionM64;
   ASSERT_TRUE(MS1.select(FlagM64, SelectionM64))
   << "Flag set was {\"+m64\"}, but selection not found";
   ASSERT_TRUE(SelectionM64.gccSuffix() == "/64")
   << "Selection picked " << SelectionM64 << " which was not expected";
 
-  Multilib::flags_list FlagNoM64 = {"-m64"};
+  Multilib::flag_set FlagNoM64 = {"-m64"};
   Multilib SelectionNoM64;
   ASSERT_TRUE(MS1.select(FlagNoM64, SelectionNoM64))
   << "Flag set was {\"-m64\"}, but selection not found";
@@ -181,16 +181,16 @@
   for (unsigned I 

[PATCH] D142905: Change multilib selection algorithm

2023-02-07 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings added inline comments.



Comment at: clang/include/clang/Driver/Multilib.h:31
 public:
-  using flags_list = std::vector;
+  using flags_list = std::set;
+  using arg_list = std::vector;

peter.smith wrote:
> would flags_set be a better name. I'm guessing we're using set as we want 
> uniqueness and ordering? 
> 
> If we don't need ordering then we may be able to use 
> https://llvm.org/docs/ProgrammersManual.html#llvm-adt-stringset-h
Renamed to flag_set.

Yes, we want uniqueness and ordering. I don't think ordering matters in this 
change, but later changes rely on it.



Comment at: clang/include/clang/Driver/Multilib.h:106
+  /// Select compatible variants
+  std::vector select(const Multilib::flags_list &Flags) const;
+

peter.smith wrote:
> Worth using multilib_list for consistency with the rest of the file?
> 
> Is this meant to be an overload for bool select below? I mention it as it has 
> a different return type. Perhaps use selectCompatible? 
Changed to use multilib_list  now, thanks.

The overloading goes away in D143059.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142905

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


[PATCH] D143493: [flang][driver] Add support for -include flag in flang -fc1

2023-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

In what cases would this flag be used in practice? I've scanned Clang and 
couldn't find any answers.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143493

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


[PATCH] D143493: [flang][driver] Add support for -include flag in flang -fc1

2023-02-07 Thread Valentin Clement via Phabricator via cfe-commits
clementval added a comment.

In D143493#4110230 , @awarzynski 
wrote:

> In what cases would this flag be used in practice? I've scanned Clang and 
> couldn't find any answers.

+1


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143493

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


[PATCH] D143493: [flang][driver] Add support for -include flag in flang -fc1

2023-02-07 Thread Sergio Afonso via Phabricator via cfe-commits
skatrak added a comment.

In D143493#4110230 , @awarzynski 
wrote:

> In what cases would this flag be used in practice? I've scanned Clang and 
> couldn't find any answers.

It is introduced to the arguments list in `Clang::AddPreprocessingOptions` in 
certain cases to add the OpenMP wrapper "__clang_openmp_device_functions.h" to 
the list of includes for device offload. It seemed likely that we would need to 
add a similar mechanism eventually to flang as well, although I suppose it 
could also be useful in other situations.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143493

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


[PATCH] D143501: [WIP][clang][DebugInfo] lldb: Use preferred name's type when emitting DW_AT_names

2023-02-07 Thread Michael Buch via Phabricator via cfe-commits
Michael137 created this revision.
Michael137 added reviewers: aprantl, dblaikie.
Herald added a project: All.
Michael137 requested review of this revision.
Herald added projects: clang, LLDB.
Herald added subscribers: lldb-commits, cfe-commits.

**Summary**

This patch makes debug-info generation aware of the
`[[clang::preferred_name]]` attribute. The attribute tells clang
to print the annotated class template as some typedef (e.g., in
diagnostics).

When printing a typename for emission into `DW_AT_name` this patch now
uses the preferred_name (if available). This is behind an LLDB tuning
because by default we try to avoid diverging GCC and Clang typename
format (which is why the `PrintingPolicy::UsePreferredNames` has
previously been disabled by default in `CGDebugInfo`).

**Motivation**

This will reduce noise in type summaries when showing variable
types in LLDB. E.g.,:

  (lldb) v
  (std::vector >) vec = size=0 {}

becomes

  (lldb) v
  (std::vector) vec = size=0 {}

**Testing**

- Added Clang test
- Adjusted LLDB API tests


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D143501

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDebugInfo.h
  clang/test/CodeGen/debug-info-preferred-names.cpp
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/TestDataFormatterLibcxxSharedPtr.py
  
lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py

Index: lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py
+++ lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/unique_ptr/TestDataFormatterLibcxxUniquePtr.py
@@ -22,7 +22,7 @@
 
 def make_expected_basic_string_ptr(self) -> str:
 if self.expectedCompilerVersion(['>', '16.0']):
-return f'std::unique_ptr >'
+return f'std::unique_ptr'
 else:
 return 'std::unique_ptr, std::allocator >, ' \
'std::default_delete, std::allocator > > >'
Index: lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/TestDataFormatterLibcxxSharedPtr.py
===
--- lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/TestDataFormatterLibcxxSharedPtr.py
+++ lldb/test/API/functionalities/data-formatter/data-formatter-stl/libcxx/shared_ptr/TestDataFormatterLibcxxSharedPtr.py
@@ -59,13 +59,13 @@
 self.assertNotEqual(valobj.child[0].unsigned, 0)
 
 if self.expectedCompilerVersion(['>', '16.0']):
-string_type = "std::basic_string"
+string_type = "std::string"
 else:
-string_type = "std::basic_string, std::allocator >"
+string_type = "std::basic_string, std::allocator > "
 
 valobj = self.expect_var_path(
 "sp_str",
-type="std::shared_ptr<" + string_type + " >",
+type="std::shared_ptr<" + string_type + ">",
 children=[ValueCheck(name="__ptr_", summary='"hello"')],
 )
 self.assertRegex(valobj.summary, r'^"hello"( strong=1)? weak=1$')
Index: clang/test/CodeGen/debug-info-preferred-names.cpp
===
--- /dev/null
+++ clang/test/CodeGen/debug-info-preferred-names.cpp
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 -emit-llvm -debug-info-kind=limited %s -o - -debugger-tuning=lldb | FileCheck --check-prefixes=COMMON,LLDB %s
+// RUN: %clang_cc1 -emit-llvm -debug-info-kind=limited %s -o - -debugger-tuning=gdb | FileCheck --check-prefixes=COMMON,GDB %s
+
+template
+class Qux {};
+
+template
+struct Foo;
+
+template
+using Bar = Foo;
+
+template
+struct [[clang::preferred_name(Bar)]] Foo {};
+
+int main() {
+/* Trivial cases */
+
+Bar b;
+// COMMON: !DIDerivedType(tag: DW_TAG_typedef, name: "Bar"
+
+Foo f1;
+// COMMON: !DICompositeType(tag: DW_TAG_structure_type, name: "Foo"
+
+/* Alias template case */
+
+Bar> f2;
+// GDB:!DIDerivedType(tag: DW_TAG_typedef, name: "Bar >"
+// LLDB:   !DIDerivedType(tag: DW_TAG_typedef, name: "Bar >"
+
+/* Nested cases */
+
+Foo> f3; 
+// GDB:!DICompositeType(tag: DW_TAG_structure_type, name: "Foo >"
+// LLDB:   !DICompositeType(tag: DW_TAG_structure_type, name: "Foo >"
+
+Qux> f4;
+// GDB:!DICompositeType(tag: DW_TAG_class_type, name: "Qux >"
+// LLDB:   !DICompositeType(tag: DW_TAG_class_type, name: "Qux >"
+
+return 0;
+}
Index: clang/lib/CodeGen/CGDebugInfo.h
===
--- clang/lib/CodeGen/CGDebugInfo.h
+++ clang/lib/CodeGen/CGDebugInfo.h
@@ -789,6 +789,11 @@
   std::memcpy(Data + A.size(),

[PATCH] D143501: [WIP][clang][DebugInfo] lldb: Use preferred name's type when emitting DW_AT_names

2023-02-07 Thread Michael Buch via Phabricator via cfe-commits
Michael137 added a comment.
Herald added a subscriber: JDevlieghere.

The alternative would be attaching the preferred name as a new attribute or an 
existing attribute like `DW_AT_description`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143501

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


[PATCH] D143496: [clangd] Add support for missing includes analysis.

2023-02-07 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 495545.
VitaNuo added a comment.

Add header spelling to fix suggestion. Fix range to only underline the symbol.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143496

Files:
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
  clang-tools-extra/include-cleaner/lib/Analysis.cpp

Index: clang-tools-extra/include-cleaner/lib/Analysis.cpp
===
--- clang-tools-extra/include-cleaner/lib/Analysis.cpp
+++ clang-tools-extra/include-cleaner/lib/Analysis.cpp
@@ -49,8 +49,8 @@
   }
 }
 
-static std::string spellHeader(const Header &H, HeaderSearch &HS,
-   const FileEntry *Main) {
+std::string spellHeader(const Header &H, HeaderSearch &HS,
+const FileEntry *Main) {
   switch (H.kind()) {
   case Header::Physical: {
 bool IsSystem = false;
Index: clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
===
--- clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
+++ clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h
@@ -73,6 +73,8 @@
 std::string fixIncludes(const AnalysisResults &Results, llvm::StringRef Code,
 const format::FormatStyle &IncludeStyle);
 
+std::string spellHeader(const Header &H, HeaderSearch &HS,
+const FileEntry *Main);
 } // namespace include_cleaner
 } // namespace clang
 
Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -385,6 +385,43 @@
Pointee(writtenInclusion("\"dir/unused.h\"";
 }
 
+TEST(IncludeCleaner, GetMissingHeaders) {
+  llvm::StringLiteral MainFile = R"cpp(
+#include "a.h"
+#include "dir/c.h"
+#include 
+
+void foo() {
+  b();
+  d();
+  f();
+})cpp";
+  // Build expected ast with symbols coming from headers.
+  TestTU TU;
+  TU.Filename = "foo.cpp";
+  TU.AdditionalFiles["foo.h"] = guard("void foo();");
+  TU.AdditionalFiles["a.h"] = guard("#include \"b.h\"");
+  TU.AdditionalFiles["b.h"] = guard("void b();");
+
+  TU.AdditionalFiles["dir/c.h"] = guard("#include \"d.h\"");
+  TU.AdditionalFiles["dir/d.h"] = guard("void d();");
+
+  TU.AdditionalFiles["system/e.h"] = guard("#include ");
+  TU.AdditionalFiles["system/f.h"] = guard("void f();");
+  TU.ExtraArgs.push_back("-isystem" + testPath("system"));
+
+  TU.Code = MainFile.str();
+  ParsedAST AST = TU.build();
+
+  std::vector> MissingIncludes =
+  computeMissingIncludes(AST);
+
+  std::pair b{"\"b.h\"", 86};
+  std::pair d{"\"dir/d.h\"", 97};
+  std::pair h{"", 108};
+  EXPECT_THAT(MissingIncludes, UnorderedElementsAre(b, d, h));
+}
+
 TEST(IncludeCleaner, VirtualBuffers) {
   TestTU TU;
   TU.Code = R"cpp(
@@ -628,6 +665,7 @@
 
   Config Cfg;
   Cfg.Diagnostics.UnusedIncludes = Config::Strict;
+  Cfg.Diagnostics.MissingIncludes = Config::MissingIncludesPolicy::Strict;
   WithContextValue Ctx(Config::Key, std::move(Cfg));
   ParsedAST AST = TU.build();
   EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ -691,9 +691,14 @@
   if (Result.Diags) {
 auto UnusedHeadersDiags =
 issueUnusedIncludesDiagnostics(Result, Inputs.Contents);
+auto MissingHeadersDiags =
+issueMissingIncludesDiagnostics(Result, Inputs.Contents);
 Result.Diags->insert(Result.Diags->end(),
  make_move_iterator(UnusedHeadersDiags.begin()),
  make_move_iterator(UnusedHeadersDiags.end()));
+Result.Diags->insert(Result.Diags->end(),
+ make_move_iterator(MissingHeadersDiags.begin()),
+ make_move_iterator(MissingHeadersDiags.end()));
   }
   return std::move(Result);
 }
Index: clang-tools-extra/clangd/IncludeCleaner.h
===
--- clang-tools-extra/clangd/IncludeCleaner.h
+++ clang-tools-extra/clangd/IncludeCleaner.h
@@ -96,12 +96,16 @@
   const llvm::DenseSet &ReferencedFiles,
   const llvm::Str

[PATCH] D143233: [Clang][CodeGen] Fix this argument type for certain destructors

2023-02-07 Thread Jacob Young via Phabricator via cfe-commits
jacobly updated this revision to Diff 495543.
jacobly added a comment.

Added regression test specific to the issue.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143233

Files:
  clang/lib/CodeGen/CGCXXABI.h
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGExprCXX.cpp
  clang/lib/CodeGen/MicrosoftCXXABI.cpp
  clang/test/CodeGenCXX/constructor-destructor-return-this.cpp
  clang/test/CodeGenCXX/cxx2a-destroying-delete.cpp
  clang/test/CodeGenCXX/microsoft-abi-eh-cleanups.cpp
  clang/test/CodeGenCXX/microsoft-abi-structors.cpp
  clang/test/CodeGenCXX/microsoft-abi-virtual-inheritance.cpp

Index: clang/test/CodeGenCXX/microsoft-abi-virtual-inheritance.cpp
===
--- clang/test/CodeGenCXX/microsoft-abi-virtual-inheritance.cpp
+++ clang/test/CodeGenCXX/microsoft-abi-virtual-inheritance.cpp
@@ -53,6 +53,7 @@
 B::~B() {
   // CHECK-LABEL: define dso_local x86_thiscallcc void @"??1B@@UAE@XZ"
   // Store initial this:
+  // CHECK:   %[[THIS:.*]] = alloca %struct.B*
   // CHECK:   %[[THIS_ADDR:.*]] = alloca %struct.B*
   // CHECK:   store %struct.B* %{{.*}}, %struct.B** %[[THIS_ADDR]], align 4
   // Reload and adjust the this parameter:
@@ -90,8 +91,7 @@
   // CHECK2: %[[THIS:.*]] = load %struct.B*, %struct.B** {{.*}}
   // CHECK2: %[[THIS_i8:.*]] = bitcast %struct.B* %[[THIS]] to i8*
   // CHECK2: %[[B_i8:.*]] = getelementptr i8, i8* %[[THIS_i8]], i32 8
-  // CHECK2: %[[B:.*]] = bitcast i8* %[[B_i8]] to %struct.B*
-  // CHECK2: call x86_thiscallcc void @"??1B@@UAE@XZ"(%struct.B* {{[^,]*}} %[[B]])
+  // CHECK2: call x86_thiscallcc void @"??1B@@UAE@XZ"(i8*{{[^,]*}} %[[B_i8]])
   // CHECK2: %[[THIS_i8:.*]] = bitcast %struct.B* %[[THIS]] to i8*
   // CHECK2: %[[VBASE_i8:.*]] = getelementptr inbounds i8, i8* %[[THIS_i8]], i32 8
   // CHECK2: %[[VBASE:.*]] = bitcast i8* %[[VBASE_i8]] to %struct.VBase*
@@ -99,6 +99,7 @@
   // CHECK2: ret
 
   // CHECK2-LABEL: define linkonce_odr dso_local x86_thiscallcc noundef i8* @"??_GB@@UAEPAXI@Z"
+  // CHECK2:   store %struct.B* %{{.*}}, %struct.B** %[[THIS:.*]], align 4
   // CHECK2:   store %struct.B* %{{.*}}, %struct.B** %[[THIS_ADDR:.*]], align 4
   // CHECK2:   %[[THIS:.*]] = load %struct.B*, %struct.B** %[[THIS_ADDR]]
   // CHECK2:   %[[THIS_PARAM_i8:.*]] = bitcast %struct.B* %[[THIS]] to i8*
@@ -196,7 +197,6 @@
 // CHECK: %[[VBOFFSET32:.*]] = load i32, i32* %[[VBENTRY]]
 // CHECK: %[[VBOFFSET:.*]] = add nsw i32 0, %[[VBOFFSET32]]
 // CHECK: %[[VBASE_i8:.*]] = getelementptr inbounds i8, i8* %[[OBJ_i8]], i32 %[[VBOFFSET]]
-// CHECK: %[[VBASE:.*]] = bitcast i8* %[[VBASE_i8]] to %struct.B*
 //
 // CHECK: %[[OBJ_i8:.*]] = bitcast %struct.B* %[[OBJ]] to i8*
 // CHECK: %[[VBPTR:.*]] = getelementptr inbounds i8, i8* %[[OBJ_i8]], i32 0
@@ -206,12 +206,12 @@
 // CHECK: %[[VBOFFSET32:.*]] = load i32, i32* %[[VBENTRY]]
 // CHECK: %[[VBOFFSET:.*]] = add nsw i32 0, %[[VBOFFSET32]]
 // CHECK: %[[VBASE_i8:.*]] = getelementptr inbounds i8, i8* %[[OBJ_i8]], i32 %[[VBOFFSET]]
-// CHECK: %[[VFPTR:.*]] = bitcast i8* %[[VBASE_i8]] to i8* (%struct.B*, i32)***
-// CHECK: %[[VFTABLE:.*]] = load i8* (%struct.B*, i32)**, i8* (%struct.B*, i32)*** %[[VFPTR]]
-// CHECK: %[[VFUN:.*]] = getelementptr inbounds i8* (%struct.B*, i32)*, i8* (%struct.B*, i32)** %[[VFTABLE]], i64 0
-// CHECK: %[[VFUN_VALUE:.*]] = load i8* (%struct.B*, i32)*, i8* (%struct.B*, i32)** %[[VFUN]]
+// CHECK: %[[VFPTR:.*]] = bitcast i8* %[[VBASE_i8]] to i8* (i8*, i32)***
+// CHECK: %[[VFTABLE:.*]] = load i8* (i8*, i32)**, i8* (i8*, i32)*** %[[VFPTR]]
+// CHECK: %[[VFUN:.*]] = getelementptr inbounds i8* (i8*, i32)*, i8* (i8*, i32)** %[[VFTABLE]], i64 0
+// CHECK: %[[VFUN_VALUE:.*]] = load i8* (i8*, i32)*, i8* (i8*, i32)** %[[VFUN]]
 //
-// CHECK: call x86_thiscallcc noundef i8* %[[VFUN_VALUE]](%struct.B* {{[^,]*}} %[[VBASE]], i32 noundef 1)
+// CHECK: call x86_thiscallcc noundef i8* %[[VFUN_VALUE]](i8* {{[^,]*}} %[[VBASE]], i32 noundef 1)
 // CHECK: ret void
 }
 
@@ -295,8 +295,9 @@
 } d;
 
 D::~D() {
-  // CHECK-LABEL: define dso_local x86_thiscallcc void @"??1D@diamond@@UAE@XZ"(%"struct.diamond::D"*{{.*}})
+  // CHECK-LABEL: define dso_local x86_thiscallcc void @"??1D@diamond@@UAE@XZ"(i8*{{.*}})
   // Store initial this:
+  // CHECK: %[[THIS:.*]] = alloca %"struct.diamond::D"*
   // CHECK: %[[THIS_ADDR:.*]] = alloca %"struct.diamond::D"*
   // CHECK: store %"struct.diamond::D"* %{{.*}}, %"struct.diamond::D"** %[[THIS_ADDR]], align 4
   //
@@ -310,16 +311,13 @@
   // CHECK: %[[C_i8:.*]] = getelementptr inbounds i8, i8* %[[D_i8]], i32 4
   // CHECK: %[[C:.*]] = bitcast i8* %[[C_i8]] to %"struct.diamond::C"*
   // CHECK: %[[C_i8:.*]] = bitcast %"struct.diamond::C"* %[[C]] to i8*
-  // CHECK: %[[ARG_i8:.*]] = getelementptr i8, i8* %{{.*}}, i32 16
-  // FIXME: We might consider changing the dtor this parameter type to i8*.
-  // CHECK: %[[ARG:.*]] = bitcast i8* %[[ARG_i8]] to %"struct.diamon

[PATCH] D143493: [flang][driver] Add support for -include flag in flang -fc1

2023-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

In D143493#4110272 , @skatrak wrote:

> It is introduced to the arguments list in `Clang::AddPreprocessingOptions` in 
> certain cases to add the OpenMP wrapper "__clang_openmp_device_functions.h" 
> to the list of includes for device offload.

This is a use case in Clang ;-)

> It seemed likely that we would need to add a similar mechanism eventually to 
> flang as well

Possibly, but it's not needed yet?

I would rather refrain from adding flags to Flang only because a similar flag 
exists in Clang. I suggest abandoning this until there's a clear need for this 
in Flang.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143493

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


[PATCH] D141389: [DFSAN] Add support for strnlen, strncat, strsep, sscanf and _tolower

2023-02-07 Thread Andrew via Phabricator via cfe-commits
browneee added inline comments.



Comment at: compiler-rt/lib/dfsan/dfsan_custom.cpp:221
+  if (flags().strict_data_dependencies) {
+*ret_label = res ? s_label : 0;
+  } else {

When `res != NULL`, then `res` is derived from `*s`, not from `s`.

e.g.

```
*ret_label = res ? dfsan_get_label(base) : 0;
```



Comment at: compiler-rt/lib/dfsan/dfsan_custom.cpp:224
+size_t s_bytes_read = (res ? strlen(res) : strlen(base)) + 1;
+*ret_label =
+dfsan_union(dfsan_read_label(base, s_bytes_read),

I think `dfsan_get_label(base)` should also be a part of this output.



Comment at: compiler-rt/lib/dfsan/dfsan_custom.cpp:241
+if (res)
+  *ret_origin = s_origin;
+  } else {

As above, when res != NULL, then res is derived from *s, not from s.

```
if (res)
*ret_origin = dfsan_get_origin(base);
```



Comment at: compiler-rt/lib/dfsan/dfsan_custom.cpp:243
+  } else {
+if (*ret_label) {
+  size_t s_bytes_read = (res ? strlen(res) : strlen(base)) + 1;

As above, I think `dfsan_get_origin(base)` should be the first priority, as it 
is the origin with the most direct value flow.

Note that `dfsan_get_origin(base)` gives the origin id for `base` whereas 
`dfsan_read_origin_of_first_taint(base, ...)` gives origin id for `*base`.



Comment at: compiler-rt/test/dfsan/custom.cpp:1659
+
+  rv = strsep(pp_s, p_delim);
+

I think this test can call strsep fewer times. It just needs to set all the 
different labels first.

Different inputs to taint (each one should be a distinct taint label):
* `*p_delim`   (with `dfsan_set_label(..., p_delim, strlen(p_delim));`)
* `p_delim`   (with `dfsan_set_label(..., &p_delim, sizeof(&p_delim));`)
* `*s`   (with `dfsan_set_label(..., s, strlen(s));`)
* `s` aka `p_s`   (with `dfsan_set_label(..., &s, sizeof(&s));` or 
`dfsan_set_label(..., &p_s, sizeof(&p_s));`)
* `pp_s` (with `dfsan_set_label(..., &pp_s, sizeof(&pp_s));`)

This is less than 8, so we can do it all at once (unless you want to test 
different taint labels on different bytes of the input strings).


Repository:
  rCRT Compiler Runtime

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

https://reviews.llvm.org/D141389

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


[PATCH] D142932: [NFC] Multilib YAML parsing

2023-02-07 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings updated this revision to Diff 495554.
michaelplatings added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142932

Files:
  clang/include/clang/Driver/Multilib.h
  clang/lib/Driver/Multilib.cpp
  clang/unittests/Driver/MultilibTest.cpp

Index: clang/unittests/Driver/MultilibTest.cpp
===
--- clang/unittests/Driver/MultilibTest.cpp
+++ clang/unittests/Driver/MultilibTest.cpp
@@ -187,3 +187,340 @@
   EXPECT_EQ("/a", Selection[0].gccSuffix());
   EXPECT_EQ("/b", Selection[1].gccSuffix());
 }
+
+static void diagnosticCallback(const llvm::SMDiagnostic &D, void *Out) {
+  *reinterpret_cast(Out) = D.getMessage();
+}
+
+static bool parse(MultilibSet &MS, std::string &Diagnostic, const char *Data) {
+  return MS.parse(llvm::MemoryBufferRef(Data, "TEST"), diagnosticCallback,
+  &Diagnostic);
+}
+
+static bool parse(MultilibSet &MS, const char *Data) {
+  return MS.parse(llvm::MemoryBufferRef(Data, "TEST"));
+}
+
+TEST(MultilibTest, ParseInvalid) {
+  std::string Diagnostic;
+
+  MultilibSet MS;
+  EXPECT_FALSE(parse(MS, Diagnostic, R"(
+variants:
+- dir: /abc
+  flags: []
+  printArgs: []
+)"));
+  EXPECT_TRUE(StringRef(Diagnostic).contains("paths must be relative"))
+  << Diagnostic;
+
+  EXPECT_FALSE(parse(MS, Diagnostic, R"(
+variants:
+- flags: []
+  printArgs: []
+)"));
+  EXPECT_TRUE(StringRef(Diagnostic).contains("missing required key 'dir'"))
+  << Diagnostic;
+
+  EXPECT_FALSE(parse(MS, Diagnostic, R"(
+variants:
+- dir: .
+  printArgs: []
+)"));
+  EXPECT_TRUE(StringRef(Diagnostic).contains("missing required key 'flags'"))
+  << Diagnostic;
+
+  EXPECT_FALSE(parse(MS, Diagnostic, R"(
+variants:
+- dir: .
+  flags: []
+)"));
+  EXPECT_TRUE(
+  StringRef(Diagnostic).contains("missing required key 'printArgs'"))
+  << Diagnostic;
+
+  EXPECT_FALSE(parse(MS, Diagnostic, R"(
+flagMap:
+- regex: abc
+)"));
+  EXPECT_TRUE(
+  StringRef(Diagnostic)
+  .contains("value required for 'matchFlags' or 'noMatchFlags'"))
+  << Diagnostic;
+
+  EXPECT_FALSE(parse(MS, Diagnostic, R"(
+flagMap:
+- dir: .
+  regex: '('
+  printArgs: []
+
+)"));
+  EXPECT_TRUE(StringRef(Diagnostic).contains("parentheses not balanced"))
+  << Diagnostic;
+}
+
+TEST(MultilibTest, Parse) {
+  MultilibSet MS;
+  EXPECT_TRUE(parse(MS, R"(
+variants:
+- dir: .
+  flags: []
+  printArgs: []
+)"));
+  EXPECT_EQ(1U, MS.size());
+  EXPECT_EQ("", MS.begin()->gccSuffix());
+
+  EXPECT_TRUE(parse(MS, R"(
+variants:
+- dir: abc
+  flags: []
+  printArgs: []
+)"));
+  EXPECT_EQ(1U, MS.size());
+  EXPECT_EQ("/abc", MS.begin()->gccSuffix());
+
+  EXPECT_TRUE(parse(MS, R"(
+variants:
+- dir: pqr
+  flags: []
+  printArgs: [-mfloat-abi=soft]
+)"));
+  EXPECT_EQ(1U, MS.size());
+  EXPECT_EQ("/pqr", MS.begin()->gccSuffix());
+  EXPECT_EQ(std::vector({"-mfloat-abi=soft"}),
+MS.begin()->getPrintArgs());
+
+  EXPECT_TRUE(parse(MS, R"(
+variants:
+- dir: pqr
+  flags: []
+  printArgs: [-mfloat-abi=soft, -fno-exceptions]
+)"));
+  EXPECT_EQ(1U, MS.size());
+  EXPECT_EQ(std::vector({"-mfloat-abi=soft", "-fno-exceptions"}),
+MS.begin()->getPrintArgs());
+
+  EXPECT_TRUE(parse(MS, R"(
+variants:
+- dir: a
+  flags: []
+  printArgs: []
+- dir: b
+  flags: []
+  printArgs: []
+)"));
+  EXPECT_EQ(2U, MS.size());
+}
+
+TEST(MultilibTest, SelectSoft) {
+  MultilibSet MS;
+  Multilib Selected;
+  ASSERT_TRUE(parse(MS, R"(
+variants:
+- dir: s
+  flags: [softabi]
+  printArgs: []
+flagMap:
+- regex: mfloat-abi=soft
+  matchFlags: [softabi]
+- regex: mfloat-abi=softfp
+  matchFlags: [softabi]
+)"));
+  EXPECT_TRUE(MS.select({"mfloat-abi=soft"}, Selected));
+  EXPECT_TRUE(MS.select({"mfloat-abi=softfp"}, Selected));
+  EXPECT_FALSE(MS.select({"mfloat-abi=hard"}, Selected));
+}
+
+TEST(MultilibTest, SelectSoftFP) {
+  MultilibSet MS;
+  Multilib Selected;
+  ASSERT_TRUE(parse(MS, R"(
+variants:
+- dir: f
+  flags: [mfloat-abi=softfp]
+  printArgs: []
+)"));
+  EXPECT_FALSE(MS.select({"mfloat-abi=soft"}, Selected));
+  EXPECT_TRUE(MS.select({"mfloat-abi=softfp"}, Selected));
+  EXPECT_FALSE(MS.select({"mfloat-abi=hard"}, Selected));
+}
+
+TEST(MultilibTest, SelectHard) {
+  // If hard float is all that's available then select that only if compiling
+  // with hard float.
+  MultilibSet MS;
+  Multilib Selected;
+  ASSERT_TRUE(parse(MS, R"(
+variants:
+- dir: h
+  flags: [mfloat-abi=hard]
+  printArgs: []
+)"));
+  EXPECT_FALSE(MS.select({"mfloat-abi=soft"}, Selected));
+  EXPECT_FALSE(MS.select({"mfloat-abi=softfp"}, Selected));
+  EXPECT_TRUE(MS.select({"mfloat-abi=hard"}, Selected));
+}
+
+TEST(MultilibTest, SelectFloatABI) {
+  MultilibSet MS;
+  Multilib Selected;
+  ASSERT_TRUE(parse(MS, R"(
+variants:
+- dir: s
+  flags: [softabi]
+  printArgs: []
+- dir: f
+  flags: [softabi, hasfp]
+  printArgs: []
+- dir: h
+  fl

[PATCH] D142933: Add -print-multi-selection-flags argument

2023-02-07 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings updated this revision to Diff 49.
michaelplatings added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142933

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Arch/ARM.cpp
  clang/lib/Driver/ToolChains/Arch/ARM.h
  clang/test/Driver/print-multi-selection-flags.c

Index: clang/test/Driver/print-multi-selection-flags.c
===
--- /dev/null
+++ clang/test/Driver/print-multi-selection-flags.c
@@ -0,0 +1,44 @@
+// RUN: %clang -print-multi-selection-flags-experimental --target=aarch64-linux -fc++-abi=itanium -fsanitize=address | FileCheck --check-prefix=CHECK-LINUX %s
+// CHECK-LINUX: fc++-abi=itanium
+// CHECK-LINUX-NEXT: fexceptions
+// CHECK-LINUX-NEXT: frtti
+// CHECK-LINUX-NEXT: fsanitize=address
+// CHECK-LINUX-NEXT: target=aarch64-unknown-linux
+
+// RUN: %clang -print-multi-selection-flags-experimental --target=aarch64-fuchsia -fsanitize=hwaddress | FileCheck --check-prefix=CHECK-FUCHSIA %s
+// CHECK-FUCHSIA: fsanitize=hwaddress
+// CHECK-FUCHSIA: target=aarch64-unknown-fuchsia
+
+// RUN: %clang -print-multi-selection-flags-experimental --target=arm-none-eabi -mfloat-abi=soft -fno-exceptions -fno-rtti | FileCheck --check-prefix=CHECK-ARMV4T %s
+// CHECK-ARMV4T: fno-exceptions
+// CHECK-ARMV4T: fno-rtti
+// CHECK-ARMV4T: mfloat-abi=soft
+// CHECK-ARMV4T: mfpu=none
+// CHECK-ARMV4T: target=armv4t-none-unknown-eabi
+
+// RUN: %clang -print-multi-selection-flags-experimental --target=armv7em-none-eabi -mfloat-abi=softfp | FileCheck --check-prefix=CHECK-SOFTFP %s
+// CHECK-SOFTFP: mfloat-abi=softfp
+// CHECK-SOFTFP: mfpu=fpv4-sp-d16
+// CHECK-SOFTFP: target=thumbv7em-none-unknown-eabi
+
+// RUN: %clang -print-multi-selection-flags-experimental --target=arm-none-eabihf -march=armv7em -mfpu=fpv5-d16 | FileCheck --check-prefix=CHECK-HARD %s
+// CHECK-HARD: mfloat-abi=hard
+// CHECK-HARD: mfpu=fpv5-d16
+// CHECK-HARD: target=thumbv7em-none-unknown-eabihf
+
+// RUN: %clang -print-multi-selection-flags-experimental --target=arm-none-eabi -mfloat-abi=soft -march=armv8-m.main+nofp | FileCheck --check-prefix=CHECK-V8MMAIN-NOFP %s
+// CHECK-V8MMAIN-NOFP: mfloat-abi=soft
+// CHECK-V8MMAIN-NOFP: mfpu=none
+// CHECK-V8MMAIN-NOFP: target=thumbv8m.main-none-unknown-eabi
+
+// RUN: %clang -print-multi-selection-flags-experimental --target=arm-none-eabi -mfloat-abi=hard -march=armv8.1m.main+mve.fp | FileCheck --check-prefix=CHECK-MVE %s
+// CHECK-MVE: march=+mve
+// CHECK-MVE: march=+mve.fp
+// CHECK-MVE: mfloat-abi=hard
+// CHECK-MVE: mfpu=fp-armv8-fullfp16-sp-d16
+// CHECK-MVE: target=thumbv8.1m.main-none-unknown-eabihf
+
+// RUN: %clang -print-multi-selection-flags-experimental --target=arm-none-eabi -march=armv8.1m.main+mve+nofp | FileCheck --check-prefix=CHECK-MVENOFP %s
+// CHECK-MVENOFP: march=+mve
+// CHECK-MVENOFP-NOT: march=+mve.fp
+// CHECK-MVENOFP: mfpu=none
Index: clang/lib/Driver/ToolChains/Arch/ARM.h
===
--- clang/lib/Driver/ToolChains/Arch/ARM.h
+++ clang/lib/Driver/ToolChains/Arch/ARM.h
@@ -64,9 +64,11 @@
 void getARMArchCPUFromArgs(const llvm::opt::ArgList &Args,
llvm::StringRef &Arch, llvm::StringRef &CPU,
bool FromAs = false);
+// Optionally returns the FPUKind
 void getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
   const llvm::opt::ArgList &Args,
-  std::vector &Features, bool ForAS);
+  std::vector &Features, bool ForAS,
+  unsigned *OutFPUKind = nullptr);
 int getARMSubArchVersionNumber(const llvm::Triple &Triple);
 bool isARMMProfile(const llvm::Triple &Triple);
 bool isARMAProfile(const llvm::Triple &Triple);
Index: clang/lib/Driver/ToolChains/Arch/ARM.cpp
===
--- clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -438,7 +438,8 @@
 
 void arm::getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
const ArgList &Args,
-   std::vector &Features, bool ForAS) {
+   std::vector &Features, bool ForAS,
+   unsigned *OutFPUKind) {
   bool KernelOrKext =
   Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
   arm::FloatABI ABI = arm::getARMFloatABI(D, Triple, Args);
@@ -632,6 +633,7 @@
 // above call.
 Features.insert(Features.end(), {"-dotprod", "-fp16fml", "-bf16", "-mve",
  "-mve.fp", "-fpregs"});
+FPUID = llvm::ARM::FK_NONE;
   } else if (FPUID == llvm::ARM::FK_NONE ||
 

[PATCH] D143493: [flang][driver] Add support for -include flag in flang -fc1

2023-02-07 Thread Sergio Afonso via Phabricator via cfe-commits
skatrak added a comment.

In D143493#4110323 , @awarzynski 
wrote:

> In D143493#4110272 , @skatrak wrote:
>
>> It is introduced to the arguments list in `Clang::AddPreprocessingOptions` 
>> in certain cases to add the OpenMP wrapper 
>> "__clang_openmp_device_functions.h" to the list of includes for device 
>> offload.
>
> This is a use case in Clang ;-)
>
>> It seemed likely that we would need to add a similar mechanism eventually to 
>> flang as well
>
> Possibly, but it's not needed yet?
>
> I would rather refrain from adding flags to Flang only because a similar flag 
> exists in Clang. I suggest abandoning this until there's a clear need for 
> this in Flang.

Sure, sounds reasonable. I suppose this will most likely come together with the 
rest of changes needed for basic offload then. Thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143493

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


[PATCH] D143386: Add function pointer alignment to DataLayout

2023-02-07 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet added a comment.
Herald added a subscriber: jobnoorman.

In D143386#4107144 , @efriedma wrote:

> Almost all the specifications you're specifying are wrong.  Very few targets 
> should be using "i".  Off the top of my head, 32-bit ARM, MIPS targets with 
> MicroMIPS, and certain PowerPC targets should, but most common targets 
> shouldn't.  ("i" means that either the target mangles the bottom bits of 
> function pointers, or function pointers don't point directly at code.)

Ok so I misunderstood the meaning of "i" then.

> And the x86 doesn't specify 4-byte alignment.

I thought that specifying it in the `DataLayout` would help getting rid of the 
special handling in ConstantFold 
.
 I'm confused now.

> For each target, we should try to handle the LLVM backend at the same time...

I'm not familiar with this part of the codebase as you can tell. Would you have 
any pointers to the backend part that needs to be updated?
Shall we try to do one target at a time then?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143386

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


[PATCH] D142986: Enable multilib.yaml in the BareMetal ToolChain

2023-02-07 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings updated this revision to Diff 495557.
michaelplatings added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142986

Files:
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Arch/ARM.cpp
  clang/lib/Driver/ToolChains/Arch/ARM.h
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/test/Driver/Inputs/baremetal_multilib/multilib.yaml
  clang/test/Driver/baremetal-multilib.cpp
  clang/test/Driver/baremetal.cpp

Index: clang/test/Driver/baremetal.cpp
===
--- clang/test/Driver/baremetal.cpp
+++ clang/test/Driver/baremetal.cpp
@@ -118,9 +118,9 @@
 // Verify that the bare metal driver does not include any host system paths:
 // CHECK-AARCH64-NO-HOST-INC: InstalledDir: [[INSTALLEDDIR:.+]]
 // CHECK-AARCH64-NO-HOST-INC: "-resource-dir" "[[RESOURCE:[^"]+]]"
-// CHECK-AARCH64-NO-HOST-INC-SAME: "-internal-isystem" "[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+}}aarch64-none-elf{{[/\\]+}}include{{[/\\]+}}c++{{[/\\]+}}v1"
+// CHECK-AARCH64-NO-HOST-INC-SAME: "-internal-isystem" "[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+[^"]*}}include{{[/\\]+}}c++{{[/\\]+}}v1"
 // CHECK-AARCH64-NO-HOST-INC-SAME: "-internal-isystem" "[[RESOURCE]]{{[/\\]+}}include"
-// CHECK-AARCH64-NO-HOST-INC-SAME: "-internal-isystem" "[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+}}aarch64-none-elf{{[/\\]+}}include"
+// CHECK-AARCH64-NO-HOST-INC-SAME: "-internal-isystem" "[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+[^"]*}}include"
 
 // RUN: %clang %s -### --target=riscv64-unknown-elf -o %t.out -L some/directory/user/asked/for \
 // RUN: --sysroot=%S/Inputs/basic_riscv64_tree/riscv64-unknown-elf 2>&1 \
Index: clang/test/Driver/baremetal-multilib.cpp
===
--- /dev/null
+++ clang/test/Driver/baremetal-multilib.cpp
@@ -0,0 +1,45 @@
+// REQUIRES: shell
+// UNSUPPORTED: system-windows
+
+// RUN: rm -rf %T/baremetal_multilib
+// RUN: mkdir -p %T/baremetal_multilib/bin
+// RUN: mkdir -p %T/baremetal_multilib/lib/clang-runtimes/arm-none-eabi/thumb/v8-m.main/fp/lib
+// RUN: touch %T/baremetal_multilib/lib/clang-runtimes/arm-none-eabi/thumb/v8-m.main/fp/lib/libclang_rt.builtins.a
+// RUN: ln -s %clang %T/baremetal_multilib/bin/clang
+// RUN: ln -s %S/Inputs/baremetal_multilib/multilib.yaml %T/baremetal_multilib/lib/clang-runtimes/multilib.yaml
+
+// RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN: --target=thumbv8m.main-none-eabihf --sysroot= \
+// RUN:   | FileCheck %s
+// CHECK: "{{.*}}clang{{.*}}" "-cc1" "-triple" "thumbv8m.main-none-unknown-eabihf"
+// CHECK-SAME: "-internal-isystem" "{{.*}}/baremetal_multilib/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8-m.main/fp/include/c++/v1"
+// CHECK-SAME: "-internal-isystem" "{{.*}}/baremetal_multilib/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8-m.main/fp/include"
+// CHECK-SAME: "-x" "c++" "{{.*}}/baremetal-multilib.cpp"
+// CHECK-NEXT: "{{[^"]*}}ld{{(\.(lld|bfd|gold))?}}{{(\.exe)?}}" "{{.*}}.o" "-Bstatic"
+// CHECK-SAME: "-L{{.*}}/baremetal_multilib/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8-m.main/fp/lib"
+// CHECK-SAME: "-lc" "-lm" "-lclang_rt.builtins"
+// CHECK-SAME: "-o" "{{.*}}.o"
+
+// RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -print-multi-directory 2>&1 \
+// RUN: --target=thumbv8m.main-none-eabihf --sysroot= \
+// RUN:   | FileCheck --check-prefix=CHECK-PRINT-MULTI-DIRECTORY %s
+// CHECK-PRINT-MULTI-DIRECTORY: arm-none-eabi/thumb/v8-m.main/fp
+
+// RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -print-multi-lib 2>&1 \
+// RUN: --target=arm-none-eabi --sysroot= \
+// RUN:   | FileCheck --check-prefix=CHECK-PRINT-MULTI-LIB %s
+// CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v6-m/nofp;@-target=thumbv6m-none-eabi@mfloat-abi=soft
+// CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v7-m/nofp;@-target=thumbv7m-none-eabi@mfloat-abi=soft
+// CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v7e-m/nofp;@-target=thumbv7em-none-eabi@mfloat-abi=soft@mfpu=none
+// CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v8-m.main/nofp;@-target=arm-none-eabi@mfloat-abi=soft@march=armv8m.main+nofp
+// CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v8.1-m.main/nofp/nomve;@-target=arm-none-eabi@mfloat-abi=soft@march=armv8.1m.main+nofp+nomve
+// CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v7e-m/fpv4_sp_d16;@-target=thumbv7em-none-eabihf@mfpu=fpv4-sp-d16
+// CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v7e-m/fpv5_d16;@-target=thumbv7em-none-eabihf@mfpu=fpv5-d16
+// CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v8-m.main/fp;@-target=thumbv8m.main-none-eabihf
+// CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v8.1-m.main/fp;@-target=thumbv8.1m.main-none-eabihf
+// CHECK-PRINT-MULTI-LIB: arm-none-eabi/th

[PATCH] D143461: [ClangScanDeps] Fix data race in `clang-scan-deps` tool

2023-02-07 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir added a comment.

Dupe of https://reviews.llvm.org/D143428 ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143461

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


[PATCH] D143059: [NFC] Enable selecting multiple multilibs

2023-02-07 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings updated this revision to Diff 495558.
michaelplatings added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143059

Files:
  clang/include/clang/Driver/Multilib.h
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/Multilib.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/lib/Driver/ToolChains/CSKYToolChain.cpp
  clang/lib/Driver/ToolChains/Fuchsia.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Driver/ToolChains/Gnu.h
  clang/lib/Driver/ToolChains/Hexagon.cpp
  clang/lib/Driver/ToolChains/Hurd.cpp
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/lib/Driver/ToolChains/MipsLinux.cpp
  clang/lib/Driver/ToolChains/RISCVToolchain.cpp
  clang/test/Driver/fuchsia.cpp
  clang/unittests/Driver/MultilibBuilderTest.cpp
  clang/unittests/Driver/MultilibTest.cpp

Index: clang/unittests/Driver/MultilibTest.cpp
===
--- clang/unittests/Driver/MultilibTest.cpp
+++ clang/unittests/Driver/MultilibTest.cpp
@@ -153,18 +153,18 @@
   Multilib("/bar", {}, {}, {"+bar"}),
   });
   Multilib::flag_set Flags1 = {"+foo", "-bar"};
-  Multilib Selection1;
+  llvm::SmallVector Selection1;
   ASSERT_TRUE(MS.select(Flags1, Selection1))
   << "Flag set was {\"+foo\"}, but selection not found";
-  ASSERT_TRUE(Selection1.gccSuffix() == "/foo")
-  << "Selection picked " << Selection1 << " which was not expected";
+  ASSERT_TRUE(Selection1.back().gccSuffix() == "/foo")
+  << "Selection picked " << Selection1.back() << " which was not expected";
 
   Multilib::flag_set Flags2 = {"+foo", "+bar"};
-  Multilib Selection2;
+  llvm::SmallVector Selection2;
   ASSERT_TRUE(MS.select(Flags2, Selection2))
   << "Flag set was {\"+bar\"}, but selection not found";
-  ASSERT_TRUE(Selection2.gccSuffix() == "/bar")
-  << "Selection picked " << Selection2 << " which was not expected";
+  ASSERT_TRUE(Selection2.back().gccSuffix() == "/bar")
+  << "Selection picked " << Selection2.back() << " which was not expected";
 }
 
 TEST(MultilibTest, SelectMultiple) {
@@ -172,17 +172,17 @@
   Multilib("/a", {}, {}, {"x"}),
   Multilib("/b", {}, {}, {"y"}),
   });
-  std::vector Selection;
+  llvm::SmallVector Selection;
 
-  Selection = MS.select({"x"});
+  ASSERT_TRUE(MS.select({"x"}, Selection));
   ASSERT_EQ(1u, Selection.size());
   EXPECT_EQ("/a", Selection[0].gccSuffix());
 
-  Selection = MS.select({"y"});
+  ASSERT_TRUE(MS.select({"y"}, Selection));
   ASSERT_EQ(1u, Selection.size());
   EXPECT_EQ("/b", Selection[0].gccSuffix());
 
-  Selection = MS.select({"y", "x"});
+  ASSERT_TRUE(MS.select({"y", "x"}, Selection));
   ASSERT_EQ(2u, Selection.size());
   EXPECT_EQ("/a", Selection[0].gccSuffix());
   EXPECT_EQ("/b", Selection[1].gccSuffix());
@@ -314,7 +314,7 @@
 
 TEST(MultilibTest, SelectSoft) {
   MultilibSet MS;
-  Multilib Selected;
+  llvm::SmallVector Selected;
   ASSERT_TRUE(parse(MS, R"(
 variants:
 - dir: s
@@ -333,7 +333,7 @@
 
 TEST(MultilibTest, SelectSoftFP) {
   MultilibSet MS;
-  Multilib Selected;
+  llvm::SmallVector Selected;
   ASSERT_TRUE(parse(MS, R"(
 variants:
 - dir: f
@@ -349,7 +349,7 @@
   // If hard float is all that's available then select that only if compiling
   // with hard float.
   MultilibSet MS;
-  Multilib Selected;
+  llvm::SmallVector Selected;
   ASSERT_TRUE(parse(MS, R"(
 variants:
 - dir: h
@@ -363,7 +363,7 @@
 
 TEST(MultilibTest, SelectFloatABI) {
   MultilibSet MS;
-  Multilib Selected;
+  llvm::SmallVector Selected;
   ASSERT_TRUE(parse(MS, R"(
 variants:
 - dir: s
@@ -384,18 +384,18 @@
   noMatchFlags: [hasfp]
 )"));
   MS.select({"mfloat-abi=soft"}, Selected);
-  EXPECT_EQ("/s", Selected.gccSuffix());
+  EXPECT_EQ("/s", Selected.back().gccSuffix());
   MS.select({"mfloat-abi=softfp"}, Selected);
-  EXPECT_EQ("/f", Selected.gccSuffix());
+  EXPECT_EQ("/f", Selected.back().gccSuffix());
   MS.select({"mfloat-abi=hard"}, Selected);
-  EXPECT_EQ("/h", Selected.gccSuffix());
+  EXPECT_EQ("/h", Selected.back().gccSuffix());
 }
 
 TEST(MultilibTest, SelectFloatABIReversed) {
   // If soft is specified after softfp then softfp will never be
   // selected because soft is compatible with softfp and last wins.
   MultilibSet MS;
-  Multilib Selected;
+  llvm::SmallVector Selected;
   ASSERT_TRUE(parse(MS, R"(
 variants:
 - dir: h
@@ -416,11 +416,11 @@
   noMatchFlags: [hasfp]
 )"));
   MS.select({"mfloat-abi=soft"}, Selected);
-  EXPECT_EQ("/s", Selected.gccSuffix());
+  EXPECT_EQ("/s", Selected.back().gccSuffix());
   MS.select({"mfloat-abi=softfp"}, Selected);
-  EXPECT_EQ("/s", Selected.gccSuffix());
+  EXPECT_EQ("/s", Selected.back().gccSuffix());
   MS.select({"mfloat-abi=hard"}, Selected);
-  EXPECT_EQ("/h", Selected.gccSuffix());
+  EXPECT_EQ("/h", Selected.back().gccSuffix());
 }
 
 TEST(MultilibTest, SelectMClass) {

[PATCH] D143075: BareMetal ToolChain multilib layering

2023-02-07 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings updated this revision to Diff 495559.
michaelplatings added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143075

Files:
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/lib/Driver/ToolChains/BareMetal.h
  clang/test/Driver/Inputs/baremetal_multilib/multilib.yaml
  clang/test/Driver/baremetal-multilib.cpp

Index: clang/test/Driver/baremetal-multilib.cpp
===
--- clang/test/Driver/baremetal-multilib.cpp
+++ clang/test/Driver/baremetal-multilib.cpp
@@ -25,6 +25,23 @@
 // RUN:   | FileCheck --check-prefix=CHECK-PRINT-MULTI-DIRECTORY %s
 // CHECK-PRINT-MULTI-DIRECTORY: arm-none-eabi/thumb/v8-m.main/fp
 
+// RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN: --target=thumbv8.1m.main-none-eabihf -fno-exceptions --sysroot= \
+// RUN:   | FileCheck --check-prefix=CHECK-LAYERED-MULTILIB %s
+// CHECK-LAYERED-MULTILIB: "{{.*}}clang{{.*}}" "-cc1" "-triple" "thumbv8.1m.main-none-unknown-eabihf"
+// CHECK-LAYERED-MULTILIB-SAME: "-internal-isystem" "{{.*}}/baremetal_multilib/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8.1-m.main/fp/noexcept/include/c++/v1"
+// CHECK-LAYERED-MULTILIB-SAME: "-internal-isystem" "{{.*}}/baremetal_multilib/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8.1-m.main/fp/include/c++/v1"
+// CHECK-LAYERED-MULTILIB-SAME: "-internal-isystem" "{{.*}}/baremetal_multilib/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8.1-m.main/fp/noexcept/include"
+// CHECK-LAYERED-MULTILIB-SAME: "-internal-isystem" "{{.*}}/baremetal_multilib/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8.1-m.main/fp/include"
+// CHECK-LAYERED-MULTILIB-NEXT: "-L{{.*}}/baremetal_multilib/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8.1-m.main/fp/noexcept/lib"
+// CHECK-LAYERED-MULTILIB-SAME: "-L{{.*}}/baremetal_multilib/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8.1-m.main/fp/lib"
+
+// RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -print-multi-directory 2>&1 \
+// RUN: --target=thumbv8.1m.main-none-eabihf -fno-exceptions --sysroot= \
+// RUN:   | FileCheck --check-prefix=CHECK-LAYERED-PRINT-MULTI-DIRECTORY %s
+// CHECK-LAYERED-PRINT-MULTI-DIRECTORY: arm-none-eabi/thumb/v8.1-m.main/fp
+// CHECK-LAYERED-PRINT-MULTI-DIRECTORY-NEXT: arm-none-eabi/thumb/v8.1-m.main/fp/noexcept
+
 // RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -print-multi-lib 2>&1 \
 // RUN: --target=arm-none-eabi --sysroot= \
 // RUN:   | FileCheck --check-prefix=CHECK-PRINT-MULTI-LIB %s
@@ -38,6 +55,7 @@
 // CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v8-m.main/fp;@-target=thumbv8m.main-none-eabihf
 // CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v8.1-m.main/fp;@-target=thumbv8.1m.main-none-eabihf
 // CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v8.1-m.main/nofp/mve;@-target=arm-none-eabihf@march=armv8.1m.main+nofp+mve
+// CHECK-PRINT-MULTI-LIB: arm-none-eabi/thumb/v8.1-m.main/fp/noexcept;@-target=thumbv8.1m.main-none-eabihf@fno-exceptions
 
 // RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -x assembler -mexecute-only \
 // RUN: --target=arm-none-eabi --sysroot= %s -c -### 2>&1 \
Index: clang/test/Driver/Inputs/baremetal_multilib/multilib.yaml
===
--- clang/test/Driver/Inputs/baremetal_multilib/multilib.yaml
+++ clang/test/Driver/Inputs/baremetal_multilib/multilib.yaml
@@ -65,6 +65,14 @@
   flags: [target=thumbv8.1m.main-none-unknown-eabihf, march=+mve]
   printArgs: [--target=arm-none-eabihf, -march=armv8.1m.main+nofp+mve]
 
+# A specialisation of v8.1-m.main/fp without exceptions.
+# This layers over the top of the regular v8.1-m.main/fp so it doesn't
+# need to have its own include directory or C library, thereby saving
+# disk space.
+- dir: arm-none-eabi/thumb/v8.1-m.main/fp/noexcept
+  flags: [target=thumbv8.1m.main-none-unknown-eabihf, hasfpu, fno-exceptions]
+  printArgs: [--target=thumbv8.1m.main-none-eabihf, -fno-exceptions]
+
 
 # The second section of the file is a map from auto-detected flags
 # to custom flags. The auto-detected flags can be printed out
Index: clang/lib/Driver/ToolChains/BareMetal.h
===
--- clang/lib/Driver/ToolChains/BareMetal.h
+++ clang/lib/Driver/ToolChains/BareMetal.h
@@ -70,6 +70,9 @@
   void AddLinkRuntimeLib(const llvm::opt::ArgList &Args,
  llvm::opt::ArgStringList &CmdArgs) const;
   std::string computeSysRoot() const override;
+
+private:
+  llvm::SmallVector getOrderedMultilibs() const;
 };
 
 } // namespace toolchains
Index: clang/lib/Driver/ToolChains/BareMetal.cpp
===
--- clang/lib/Driver/ToolChains/BareMetal.cpp
+++ clang/lib/Driver/ToolChains/BareMetal.cpp
@@ -107,9 +107,12 @@
   findMultilibs(D, Triple, Args);
   SmallStr

[PATCH] D143414: [clang] refactor FileManager::GetUniqueIDMapping

2023-02-07 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir added a comment.

> This should allow the path serialization of input files to use the paths used 
> when looking up a file entry, instead of the last reference.

Isn't this at odds with not having the VFS-mapped paths?

It's not obvious to me why we want these specific semantics.  Elsewhere we have 
tried to preserve the virtual paths as well as the vfsoverlay files needed to 
interpret them.  Is there a reason the current approach is better? I feel like 
there may be context here I'm lacking


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143414

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


[PATCH] D143507: [RISCV][MC] Mark Zawrs extension as non-experimental

2023-02-07 Thread Alex Bradbury via Phabricator via cfe-commits
asb created this revision.
asb added reviewers: reames, craig.topper.
Herald added subscribers: jobnoorman, luke, wingo, pmatos, VincentWu, vkmr, 
frasercrmck, jdoerfert, evandro, luismarques, apazos, sameer.abuasal, 
s.egerton, Jim, benna, psnobl, jocewei, PkmX, the_o, brucehoult, MartinMosbeck, 
rogfer01, edward-jones, zzheng, jrtc27, shiva0217, kito-cheng, niosHD, 
sabuasal, simoncook, johnrusso, rbar, hiraditya, arichardson.
Herald added a project: All.
asb requested review of this revision.
Herald added subscribers: cfe-commits, pcwang-thead, eopXD, MaskRay.
Herald added projects: clang, LLVM.

Support for the unratified 1.0-rc3 specification was introduced in D133443 
. The specification has since been ratified 
(in November 2022 according to the recently ratified extensions list 
.

  

A review of the diff 
 of the 1.0-rc3 
spec vs the current/ratified document shows no changes to the instruction 
encoding or naming. At one point, a note was added 

 indicating Zawrs depends on the Zalrsc extension (not officially specified, 
but I believe to be just the LR/SC instructions from the A extension). The 
final text ended up as "The instructions in the Zawrs extension are only useful 
in conjunction with the LR instructions, which are provided by the A extension, 
and which we also expect to be provided by a narrower Zalrsc extension in the 
future." I think it's consistent with this phrasing to not require the A 
extension for Zawrs, which matches what was implemented.

  

No intrinsics are implemented for Zawrs currently, meaning we don't need to 
additionally review whether those intrinsics can be considered finalised and 
ready for exposure to end users.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D143507

Files:
  clang/test/Preprocessor/riscv-target-features.c
  llvm/docs/RISCVUsage.rst
  llvm/docs/ReleaseNotes.rst
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/RISCVFeatures.td
  llvm/test/CodeGen/RISCV/attributes.ll
  llvm/test/MC/RISCV/Zawrs-valid.s

Index: llvm/test/MC/RISCV/Zawrs-valid.s
===
--- llvm/test/MC/RISCV/Zawrs-valid.s
+++ llvm/test/MC/RISCV/Zawrs-valid.s
@@ -1,12 +1,12 @@
-# RUN: llvm-mc %s -triple=riscv32 -mattr=+experimental-zawrs -riscv-no-aliases -show-encoding \
+# RUN: llvm-mc %s -triple=riscv32 -mattr=+zawrs -riscv-no-aliases -show-encoding \
 # RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
-# RUN: llvm-mc %s -triple=riscv64 -mattr=+experimental-zawrs -riscv-no-aliases -show-encoding \
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+zawrs -riscv-no-aliases -show-encoding \
 # RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
-# RUN: llvm-mc -filetype=obj -triple=riscv32 -mattr=+experimental-zawrs < %s \
-# RUN: | llvm-objdump --mattr=+experimental-zawrs -M no-aliases -d -r - \
+# RUN: llvm-mc -filetype=obj -triple=riscv32 -mattr=+zawrs < %s \
+# RUN: | llvm-objdump --mattr=+zawrs -M no-aliases -d -r - \
 # RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
-# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+experimental-zawrs < %s \
-# RUN: | llvm-objdump --mattr=+experimental-zawrs -M no-aliases -d -r - \
+# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+zawrs < %s \
+# RUN: | llvm-objdump --mattr=+zawrs -M no-aliases -d -r - \
 # RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
 
 # CHECK-ASM-AND-OBJ: wrs.nto
Index: llvm/test/CodeGen/RISCV/attributes.ll
===
--- llvm/test/CodeGen/RISCV/attributes.ll
+++ llvm/test/CodeGen/RISCV/attributes.ll
@@ -87,7 +87,7 @@
 ; RUN: llc -mtriple=riscv64 -mattr=+svinval %s -o - | FileCheck --check-prefix=RV64SVINVAL %s
 ; RUN: llc -mtriple=riscv64 -mattr=+xventanacondops %s -o - | FileCheck --check-prefix=RV64XVENTANACONDOPS %s
 ; RUN: llc -mtriple=riscv64 -mattr=+xtheadvdot %s -o - | FileCheck --check-prefix=RV64XTHEADVDOT %s
-; RUN: llc -mtriple=riscv64 -mattr=+experimental-zawrs %s -o - | FileCheck --check-prefix=RV64ZAWRS %s
+; RUN: llc -mtriple=riscv64 -mattr=+zawrs %s -o - | FileCheck --check-prefix=RV64ZAWRS %s
 ; RUN: llc -mtriple=riscv64 -mattr=+experimental-ztso %s -o - | FileCheck --check-prefix=RV64ZTSO %s
 ; RUN: llc -mtriple=riscv64 -mattr=+experimental-zca %s -o - | FileCheck --check-prefix=RV64ZCA %s
 ; RUN: llc -mtriple=riscv64 -mattr=+experimental-zcb %s -o - | FileCheck --check-prefix=RV64ZCB %s
Index: llvm/lib/Target/RISCV/RISCVFeatures.td
===
--- llvm/lib/Target/RISCV/RISCVFeatures.td
+++ llvm/lib/Target/RISCV/RISCVFeatures.td
@@ -445,9 +445,8 @@
   A

[PATCH] D143461: [ClangScanDeps] Fix data race in `clang-scan-deps` tool

2023-02-07 Thread Argyrios Kyrtzidis via Phabricator via cfe-commits
akyrtzi abandoned this revision.
akyrtzi added a comment.

In D143461#4110405 , @benlangmuir 
wrote:

> Dupe of https://reviews.llvm.org/D143428 ?

Indeed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143461

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


[PATCH] D143509: Move the BySpelling map to IncludeStructure.

2023-02-07 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo created this revision.
Herald added subscribers: kadircet, arphaman.
Herald added a project: All.
VitaNuo requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D143509

Files:
  clang-tools-extra/clangd/Headers.h
  clang-tools-extra/clangd/IncludeCleaner.cpp

Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -85,7 +85,7 @@
 // Using templateName case is handled by the override TraverseTemplateName.
 if (TST->getTemplateName().getKind() == TemplateName::UsingTemplate)
   return true;
-add(TST->getAsCXXRecordDecl());  // Specialization
+add(TST->getAsCXXRecordDecl()); // Specialization
 return true;
   }
 
@@ -474,22 +474,18 @@
   translateToHeaderIDs(ReferencedFiles, AST.getIncludeStructure(), SM);
   return getUnused(AST, ReferencedHeaders, ReferencedFiles.SpelledUmbrellas);
 }
-std::vector computeUnusedIncludesExperimental(ParsedAST &AST) {
-   const auto &SM = AST.getSourceManager();
-   const auto &Includes = AST.getIncludeStructure();
-   // FIXME: this map should probably be in IncludeStructure.
-   llvm::StringMap> BySpelling;
-   for (const auto &Inc : Includes.MainFileIncludes) {
-if (Inc.HeaderID)
-  BySpelling.try_emplace(Inc.Written)
-  .first->second.push_back(
-  static_cast(*Inc.HeaderID));
-   }
-   // FIXME: !!this is a hacky way to collect macro references.
-   std::vector Macros;
-auto& PP = AST.getPreprocessor();
-   for (const syntax::Token &Tok :
-AST.getTokens().spelledTokens(SM.getMainFileID())) {
+std::vector
+computeUnusedIncludesExperimental(ParsedAST &AST) {
+  const auto &SM = AST.getSourceManager();
+  const auto &Includes = AST.getIncludeStructure();
+  llvm::StringMap> BySpelling =
+  Includes.buildMainFileIncludesBySpelling();
+
+  // FIXME: !!this is a hacky way to collect macro references.
+  std::vector Macros;
+  auto &PP = AST.getPreprocessor();
+  for (const syntax::Token &Tok :
+   AST.getTokens().spelledTokens(SM.getMainFileID())) {
 auto Macro = locateMacroAt(Tok, PP);
 if (!Macro)
   continue;
@@ -499,31 +495,31 @@
include_cleaner::Macro{/*Name=*/PP.getIdentifierInfo(Tok.text(SM)),
   DefLoc},
include_cleaner::RefType::Explicit});
-   }
-   llvm::DenseSet Used;
-   include_cleaner::walkUsed(
-   AST.getLocalTopLevelDecls(), /*MacroRefs=*/Macros,
-   AST.getPragmaIncludes(), SM,
-   [&](const include_cleaner::SymbolReference &Ref,
-   llvm::ArrayRef Providers) {
- for (const auto &H : Providers) {
-   switch (H.kind()) {
-   case include_cleaner::Header::Physical:
- if (auto HeaderID = Includes.getID(H.physical()))
-   Used.insert(*HeaderID);
- break;
-   case include_cleaner::Header::Standard:
- for (auto HeaderID : Includes.StdlibHeaders.lookup(H.standard()))
-   Used.insert(HeaderID);
- break;
-   case include_cleaner::Header::Verbatim:
- for (auto HeaderID : BySpelling.lookup(H.verbatim()))
-   Used.insert(HeaderID);
- break;
-   }
- }
-   });
-   return getUnused(AST, Used, /*ReferencedPublicHeaders*/{});
+  }
+  llvm::DenseSet Used;
+  include_cleaner::walkUsed(
+  AST.getLocalTopLevelDecls(), /*MacroRefs=*/Macros,
+  AST.getPragmaIncludes(), SM,
+  [&](const include_cleaner::SymbolReference &Ref,
+  llvm::ArrayRef Providers) {
+for (const auto &H : Providers) {
+  switch (H.kind()) {
+  case include_cleaner::Header::Physical:
+if (auto HeaderID = Includes.getID(H.physical()))
+  Used.insert(*HeaderID);
+break;
+  case include_cleaner::Header::Standard:
+for (auto HeaderID : Includes.StdlibHeaders.lookup(H.standard()))
+  Used.insert(HeaderID);
+break;
+  case include_cleaner::Header::Verbatim:
+for (auto HeaderID : BySpelling.lookup(H.verbatim()))
+  Used.insert(HeaderID);
+break;
+  }
+}
+  });
+  return getUnused(AST, Used, /*ReferencedPublicHeaders*/ {});
 }
 
 std::vector issueUnusedIncludesDiagnostics(ParsedAST &AST,
Index: clang-tools-extra/clangd/Headers.h
===
--- clang-tools-extra/clangd/Headers.h
+++ clang-tools-extra/clangd/Headers.h
@@ -155,13 +155,23 @@
 return !NonSelfContained.contains(ID);
   }
 
-  bool hasIWYUExport(HeaderID ID) const {
-return HasIWYUExport.contains(ID);
-  }
+  bool hasIWYUExport(HeaderID ID) const { return HasIWYUExport.contain

[PATCH] D142914: [MLIR][OpenMP] Added OMPIRBuilder support for Target Data directives.

2023-02-07 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

Please avoid the MLIR style in any other subproject. I know some of the OpenMP 
Builder stuff already uses `llvm::` and MLIR style names, but that is in itself 
bad, not something we should extend.




Comment at: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h:1092
+  /// Computes the size of type in bytes.
+  llvm::Value *getSizeInBytes(llvm::Value *basePtr);
+

Nit: Style, no llvm::



Comment at: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h:1573
+   llvm::Value *ifCond, BodyGenCallbackTy processMapOpCB,
+   BodyGenCallbackTy BodyGenCB);
+

Style, see above.



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:4093
+  return Builder.saveIP();
+}
+

Style, see above. 



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:4152
+  return sizePtrToInt;
+}
+

Style, see above. 



Comment at: llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp:4991
+  EXPECT_TRUE(targetDataCall->getOperand(8)->getType()->isPointerTy());
+}
+

Style, see above. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142914

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


[PATCH] D137756: [z/OS][pg] Throw error when using -pg on z/OS

2023-02-07 Thread Michael Francis via Phabricator via cfe-commits
francii updated this revision to Diff 495570.
francii added a comment.

Update test case verbosity


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137756

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/zos-profiling-error.c


Index: clang/test/Driver/zos-profiling-error.c
===
--- /dev/null
+++ clang/test/Driver/zos-profiling-error.c
@@ -0,0 +1,2 @@
+// RUN: %clang 2>&1 -### --target=s390x-none-zos -pg -S %s | FileCheck 
-check-prefix=FAIL-PG-NAME %s
+// FAIL-PG-NAME: error: unsupported option '-pg' for target 's390x-none-zos'
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6336,6 +6336,12 @@
   << A->getAsString(Args) << TripleStr;
 }
   }
+  if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
+if (TC.getTriple().isOSzOS()) {
+  D.Diag(diag::err_drv_unsupported_opt_for_target)
+  << A->getAsString(Args) << TripleStr;
+}
+  }
 
   if (Args.getLastArg(options::OPT_fapple_kext) ||
   (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))


Index: clang/test/Driver/zos-profiling-error.c
===
--- /dev/null
+++ clang/test/Driver/zos-profiling-error.c
@@ -0,0 +1,2 @@
+// RUN: %clang 2>&1 -### --target=s390x-none-zos -pg -S %s | FileCheck -check-prefix=FAIL-PG-NAME %s
+// FAIL-PG-NAME: error: unsupported option '-pg' for target 's390x-none-zos'
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6336,6 +6336,12 @@
   << A->getAsString(Args) << TripleStr;
 }
   }
+  if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
+if (TC.getTriple().isOSzOS()) {
+  D.Diag(diag::err_drv_unsupported_opt_for_target)
+  << A->getAsString(Args) << TripleStr;
+}
+  }
 
   if (Args.getLastArg(options::OPT_fapple_kext) ||
   (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D143446: [clang][deps] Ensure module invocation can be serialized

2023-02-07 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir updated this revision to Diff 495573.

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

https://reviews.llvm.org/D143446

Files:
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Basic/LangOptions.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/ClangScanDeps/modules-implied-args.c
  clang/tools/clang-scan-deps/ClangScanDeps.cpp

Index: clang/tools/clang-scan-deps/ClangScanDeps.cpp
===
--- clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -8,6 +8,7 @@
 
 #include "clang/Driver/Driver.h"
 #include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/TextDiagnosticPrinter.h"
 #include "clang/Tooling/CommonOptionsParser.h"
 #include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
 #include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
@@ -197,6 +198,12 @@
 llvm::cl::init(RDRK_ModifyCompilerPath),
 llvm::cl::cat(DependencyScannerCategory));
 
+llvm::cl::opt
+RoundTripArgs("round-trip-args", llvm::cl::Optional,
+  llvm::cl::desc("verify that command-line arguments are "
+ "canonical by parsing and re-serializing"),
+  llvm::cl::cat(DependencyScannerCategory));
+
 llvm::cl::opt Verbose("v", llvm::cl::Optional,
 llvm::cl::desc("Use verbose output."),
 llvm::cl::init(false),
@@ -275,6 +282,37 @@
 }
   }
 
+  bool roundTripCommand(ArrayRef ArgStrs,
+DiagnosticsEngine &Diags) {
+if (ArgStrs.empty() || ArgStrs[0] != "-cc1")
+  return false;
+SmallVector Args;
+for (const std::string &Arg : ArgStrs)
+  Args.push_back(Arg.c_str());
+return !CompilerInvocation::checkCC1RoundTrip(Args, Diags);
+  }
+
+  // Returns \c true if any command lines fail to round-trip. We expect
+  // commands already be canonical when output by the scanner.
+  bool roundTripCommands(raw_ostream &ErrOS) {
+IntrusiveRefCntPtr DiagOpts = new DiagnosticOptions{};
+TextDiagnosticPrinter DiagConsumer(ErrOS, &*DiagOpts);
+IntrusiveRefCntPtr Diags =
+CompilerInstance::createDiagnostics(&*DiagOpts, &DiagConsumer,
+/*ShouldOwnClient=*/false);
+
+for (auto &&M : Modules)
+  if (roundTripCommand(M.second.BuildArguments, *Diags))
+return true;
+
+for (auto &&I : Inputs)
+  for (const auto &Cmd : I.Commands)
+if (roundTripCommand(Cmd.Arguments, *Diags))
+  return true;
+
+return false;
+  }
+
   void printFullOutput(raw_ostream &OS) {
 // Sort the modules by name to get a deterministic order.
 std::vector ModuleIDs;
@@ -612,6 +650,15 @@
   }
   Pool.wait();
 
+#ifndef NDEBUG
+  bool DoRoundTripDefault = true;
+#else
+  bool DoRoundTripDefault = false;
+#endif
+  if (RoundTripArgs.getNumOccurrences() ? RoundTripArgs : DoRoundTripDefault)
+if (FD.roundTripCommands(llvm::errs()))
+  HadErrors = true;
+
   if (Format == ScanningOutputFormat::Full)
 FD.printFullOutput(llvm::outs());
 
Index: clang/test/ClangScanDeps/modules-implied-args.c
===
--- /dev/null
+++ clang/test/ClangScanDeps/modules-implied-args.c
@@ -0,0 +1,46 @@
+// Check that we get canonical round-trippable command-lines, in particular
+// for the options modified for modules.
+
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full -round-trip-args > %t/result.json
+// RUN: cat %t/result.json  | sed 's:\?:/:g' | FileCheck %s -DPREFIX=%/t --check-prefixes=CHECK,NEGATIVE
+
+// -ffast-math implies -menable-no-infs, -menable-no-nans, and -mreassociate;
+// those options are modified by resetNonModularOptions.
+
+// NEGATIVE-NOT: "-menable-no-infs"
+// NEGATIVE-NOT: "-menable-no-nans"
+// NEGATIVE-NOT: "-mreassociate"
+
+// CHECK:  "modules": [
+// CHECK-NEXT:   {
+// CHECK:  "clang-module-deps": []
+// CHECK:  "command-line": [
+// CHECK:"-ffast-math"
+// CHECK:  ]
+// CHECK:  "name": "Mod"
+// CHECK:}
+// CHECK-NEXT: ]
+// CHECK:  "translation-units": [
+// CHECK-NEXT:   {
+// CHECK-NEXT: "commands": [
+// CHECK:{
+// CHECK:  "command-line": [
+// CHECK:"-ffast-math"
+// CHECK:  ]
+
+//--- cdb.json.template
+[{
+  "file": "DIR/tu.c",
+  "directory": "DIR",
+  "command": "clang -fsyntax-only DIR/tu.c -fmodules -fmodules-cache-path=DIR/cache -ffast-math"
+}]
+
+//--- module.modulemap
+module Mod { header "mod.h" }
+//--- mod.h
+//--- tu.c
+#include "mod.h"
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--

[PATCH] D143495: [AMDGPU ASAN] Remove reference to asan bitcode library

2023-02-07 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl accepted this revision.
yaxunl added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143495

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


[clang] 152f291 - [clang][deps] Fix race condition

2023-02-07 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2023-02-07T09:26:56-08:00
New Revision: 152f2914607ffe632202ee660208d6dfba6c8870

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

LOG: [clang][deps] Fix race condition

D140176 introduced new `FullDeps` API that's not thread-safe, breaking the 
class invariant. This was causing race condition when `clang-scan-deps` was run 
with multiple threads.

Reviewed By: steven_wu, akyrtzi

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

Added: 


Modified: 
clang/tools/clang-scan-deps/ClangScanDeps.cpp

Removed: 




diff  --git a/clang/tools/clang-scan-deps/ClangScanDeps.cpp 
b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
index 41bc0ea7f0247..1458d11eb323f 100644
--- a/clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -252,14 +252,17 @@ class FullDeps {
 public:
   void mergeDeps(StringRef Input, TranslationUnitDeps TUDeps,
  size_t InputIndex) {
+mergeDeps(std::move(TUDeps.ModuleGraph), InputIndex);
+
 InputDeps ID;
 ID.FileName = std::string(Input);
 ID.ContextHash = std::move(TUDeps.ID.ContextHash);
 ID.FileDeps = std::move(TUDeps.FileDeps);
 ID.ModuleDeps = std::move(TUDeps.ClangModuleDeps);
-mergeDeps(std::move(TUDeps.ModuleGraph), InputIndex);
 ID.DriverCommandLine = std::move(TUDeps.DriverCommandLine);
 ID.Commands = std::move(TUDeps.Commands);
+
+std::unique_lock ul(Lock);
 Inputs.push_back(std::move(ID));
   }
 



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


[PATCH] D143428: [clang][deps] Fix race condition

2023-02-07 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG152f2914607f: [clang][deps] Fix race condition (authored by 
jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143428

Files:
  clang/tools/clang-scan-deps/ClangScanDeps.cpp


Index: clang/tools/clang-scan-deps/ClangScanDeps.cpp
===
--- clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -252,14 +252,17 @@
 public:
   void mergeDeps(StringRef Input, TranslationUnitDeps TUDeps,
  size_t InputIndex) {
+mergeDeps(std::move(TUDeps.ModuleGraph), InputIndex);
+
 InputDeps ID;
 ID.FileName = std::string(Input);
 ID.ContextHash = std::move(TUDeps.ID.ContextHash);
 ID.FileDeps = std::move(TUDeps.FileDeps);
 ID.ModuleDeps = std::move(TUDeps.ClangModuleDeps);
-mergeDeps(std::move(TUDeps.ModuleGraph), InputIndex);
 ID.DriverCommandLine = std::move(TUDeps.DriverCommandLine);
 ID.Commands = std::move(TUDeps.Commands);
+
+std::unique_lock ul(Lock);
 Inputs.push_back(std::move(ID));
   }
 


Index: clang/tools/clang-scan-deps/ClangScanDeps.cpp
===
--- clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -252,14 +252,17 @@
 public:
   void mergeDeps(StringRef Input, TranslationUnitDeps TUDeps,
  size_t InputIndex) {
+mergeDeps(std::move(TUDeps.ModuleGraph), InputIndex);
+
 InputDeps ID;
 ID.FileName = std::string(Input);
 ID.ContextHash = std::move(TUDeps.ID.ContextHash);
 ID.FileDeps = std::move(TUDeps.FileDeps);
 ID.ModuleDeps = std::move(TUDeps.ClangModuleDeps);
-mergeDeps(std::move(TUDeps.ModuleGraph), InputIndex);
 ID.DriverCommandLine = std::move(TUDeps.DriverCommandLine);
 ID.Commands = std::move(TUDeps.Commands);
+
+std::unique_lock ul(Lock);
 Inputs.push_back(std::move(ID));
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   >