[PATCH] D152435: [analyzer][CStringChecker] Adjust the invalidation operation on the super region of the destination buffer during string copy

2023-07-03 Thread Ella Ma via Phabricator via cfe-commits
OikawaKirie added a comment.

I will submit it again later to update the code as you suggested.

Besides,

> Build Status
> Buildable 242737  
> Build 376801: pre-merge checkslibcxx CI FAILED

What does this mean? Was this patch correctly compiled and checked in the 
previous build? How can I avoid this failure?

Thx


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

https://reviews.llvm.org/D152435

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


[PATCH] D153006: [clang][dataflow] Perform deep copies in copy and move operations.

2023-07-03 Thread Martin Böhme via Phabricator via cfe-commits
mboehme marked an inline comment as done.
mboehme added a subscriber: donat.nagy.
mboehme added a comment.

In D153006#4463759 , @RKSimon wrote:

> @mboehme https://lab.llvm.org/buildbot/#/builders/124 is still broken - 
> please can you revert the patch series?

Sorry, I did not see this in time to revert.

It seems this has been fixed in the meantime by 
https://github.com/llvm/llvm-project/commit/cec30e2b190bd58a26f54b5fd4232d3828632466.
 Thank you to @donat.nagy for the fix, and apologies for the breakage.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153006

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


[PATCH] D152435: [analyzer][CStringChecker] Adjust the invalidation operation on the super region of the destination buffer during string copy

2023-07-03 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D152435#4467672 , @OikawaKirie 
wrote:

> I will submit it again later to update the code as you suggested.

Feel free to commit it with that modifications included.

> Besides,
>
>> Build Status
>> Buildable 242737 
>> Build 376801: pre-merge checks   libcxx CI FAILED
>
> What does this mean? Was this patch correctly compiled and checked in the 
> previous build? How can I avoid this failure?

This is likely some anomaly. In general, you should check those logs to see if 
it's related to your patch. If not, than you can proceed and check if any of 
the bots cry after you commit.
If they do, triage what went wrong and decide if you attempt a fix commit or a 
revert.


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

https://reviews.llvm.org/D152435

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


[clang] 77a599a - [analyzer] Fix false negative when using a nullable parameter directly without binding to a variable

2023-07-03 Thread Balazs Benics via cfe-commits

Author: tripleCC
Date: 2023-07-03T09:28:41+02:00
New Revision: 77a599ae5828df343e2aa6acc634fe9acb152c99

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

LOG: [analyzer] Fix false negative when using a nullable parameter directly 
without binding to a variable

If a parameter has a nullability annotation, the nullability information
of the parameter should be set as a NullabilityState trait at the
beginning of the function.

Patch By tripleCC!

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
clang/test/Analysis/nullability.mm

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
index 11d5e77db0c731..635b6e4f6bd71d 100644
--- a/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
@@ -26,12 +26,13 @@
 
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 
+#include "clang/Analysis/AnyCall.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
-#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
-#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
 
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/Path.h"
@@ -81,7 +82,8 @@ class NullabilityChecker
 : public Checker,
  check::PostCall, check::PostStmt,
  check::PostObjCMessage, check::DeadSymbols, eval::Assume,
- check::Location, check::Event> {
+ check::Location, check::Event,
+ check::BeginFunction> {
 
 public:
   // If true, the checker will not diagnose nullabilility issues for calls
@@ -102,6 +104,7 @@ class NullabilityChecker
   void checkEvent(ImplicitNullDerefEvent Event) const;
   void checkLocation(SVal Location, bool IsLoad, const Stmt *S,
  CheckerContext &C) const;
+  void checkBeginFunction(CheckerContext &Ctx) const;
   ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
  bool Assumption) const;
 
@@ -563,6 +566,37 @@ void NullabilityChecker::checkEvent(ImplicitNullDerefEvent 
Event) const {
   }
 }
 
+void NullabilityChecker::checkBeginFunction(CheckerContext &C) const {
+  if (!C.inTopFrame())
+return;
+
+  const LocationContext *LCtx = C.getLocationContext();
+  auto AbstractCall = AnyCall::forDecl(LCtx->getDecl());
+  if (!AbstractCall || AbstractCall->parameters().empty())
+return;
+
+  ProgramStateRef State = C.getState();
+  for (const ParmVarDecl *Param : AbstractCall->parameters()) {
+if (!isValidPointerType(Param->getType()))
+  continue;
+
+Nullability RequiredNullability =
+getNullabilityAnnotation(Param->getType());
+if (RequiredNullability != Nullability::Nullable)
+  continue;
+
+const VarRegion *ParamRegion = State->getRegion(Param, LCtx);
+const MemRegion *ParamPointeeRegion =
+State->getSVal(ParamRegion).getAsRegion();
+if (!ParamPointeeRegion)
+  continue;
+
+State = State->set(ParamPointeeRegion,
+   NullabilityState(RequiredNullability));
+  }
+  C.addTransition(State);
+}
+
 // Whenever we see a load from a typed memory region that's been annotated as
 // 'nonnull', we want to trust the user on that and assume that it is is indeed
 // non-null.

diff  --git a/clang/test/Analysis/nullability.mm 
b/clang/test/Analysis/nullability.mm
index 44c241e07ee50a..5a702f86564a61 100644
--- a/clang/test/Analysis/nullability.mm
+++ b/clang/test/Analysis/nullability.mm
@@ -145,6 +145,17 @@ void testArgumentTracking(Dummy *_Nonnull nonnull, Dummy 
*_Nullable nullable) {
   }
 }
 
+void testArgumentTrackingDirectly(Dummy *_Nonnull nonnull, Dummy *_Nullable 
nullable) {
+  switch(getRandom()) {
+  case 1: testMultiParamChecking(nonnull, nullable, nonnull); break;
+  case 2: testMultiParamChecking(nonnull, nonnull, nonnull); break;
+  case 3: testMultiParamChecking(nonnull, nullable, nullable); break; // 
expected-warning {{Nullable pointer is passed to a callee that requires a 
non-null 3rd parameter}}
+  case 4: testMultiParamChecking(nullable, nullable, nonnull); // 
expected-warning {{Nullable pointer is passed to a callee that requires a 
non-null 1st parameter}}
+  case 5: testMultiParamChecking(nullable, nullable, nullable); // 
expect

[PATCH] D153017: [analyzer] Fix false negative when using a nullable parameter directly without binding to a variable

2023-07-03 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG77a599ae5828: [analyzer] Fix false negative when using a 
nullable parameter directly without… (authored by tripleCC, committed by 
steakhal).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153017

Files:
  clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
  clang/test/Analysis/nullability.mm


Index: clang/test/Analysis/nullability.mm
===
--- clang/test/Analysis/nullability.mm
+++ clang/test/Analysis/nullability.mm
@@ -145,6 +145,17 @@
   }
 }
 
+void testArgumentTrackingDirectly(Dummy *_Nonnull nonnull, Dummy *_Nullable 
nullable) {
+  switch(getRandom()) {
+  case 1: testMultiParamChecking(nonnull, nullable, nonnull); break;
+  case 2: testMultiParamChecking(nonnull, nonnull, nonnull); break;
+  case 3: testMultiParamChecking(nonnull, nullable, nullable); break; // 
expected-warning {{Nullable pointer is passed to a callee that requires a 
non-null 3rd parameter}}
+  case 4: testMultiParamChecking(nullable, nullable, nonnull); // 
expected-warning {{Nullable pointer is passed to a callee that requires a 
non-null 1st parameter}}
+  case 5: testMultiParamChecking(nullable, nullable, nullable); // 
expected-warning {{Nullable pointer is passed to a callee that requires a 
non-null 1st parameter}}
+  case 6: testMultiParamChecking((Dummy *_Nonnull)0, nullable, nonnull); break;
+  }
+}
+
 Dummy *_Nonnull testNullableReturn(Dummy *_Nullable a) {
   Dummy *p = a;
   return p; // expected-warning {{Nullable pointer is returned from a function 
that is expected to return a non-null value}}
Index: clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
@@ -26,12 +26,13 @@
 
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 
+#include "clang/Analysis/AnyCall.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
-#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
-#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
 
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/Path.h"
@@ -81,7 +82,8 @@
 : public Checker,
  check::PostCall, check::PostStmt,
  check::PostObjCMessage, check::DeadSymbols, eval::Assume,
- check::Location, check::Event> {
+ check::Location, check::Event,
+ check::BeginFunction> {
 
 public:
   // If true, the checker will not diagnose nullabilility issues for calls
@@ -102,6 +104,7 @@
   void checkEvent(ImplicitNullDerefEvent Event) const;
   void checkLocation(SVal Location, bool IsLoad, const Stmt *S,
  CheckerContext &C) const;
+  void checkBeginFunction(CheckerContext &Ctx) const;
   ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
  bool Assumption) const;
 
@@ -563,6 +566,37 @@
   }
 }
 
+void NullabilityChecker::checkBeginFunction(CheckerContext &C) const {
+  if (!C.inTopFrame())
+return;
+
+  const LocationContext *LCtx = C.getLocationContext();
+  auto AbstractCall = AnyCall::forDecl(LCtx->getDecl());
+  if (!AbstractCall || AbstractCall->parameters().empty())
+return;
+
+  ProgramStateRef State = C.getState();
+  for (const ParmVarDecl *Param : AbstractCall->parameters()) {
+if (!isValidPointerType(Param->getType()))
+  continue;
+
+Nullability RequiredNullability =
+getNullabilityAnnotation(Param->getType());
+if (RequiredNullability != Nullability::Nullable)
+  continue;
+
+const VarRegion *ParamRegion = State->getRegion(Param, LCtx);
+const MemRegion *ParamPointeeRegion =
+State->getSVal(ParamRegion).getAsRegion();
+if (!ParamPointeeRegion)
+  continue;
+
+State = State->set(ParamPointeeRegion,
+   NullabilityState(RequiredNullability));
+  }
+  C.addTransition(State);
+}
+
 // Whenever we see a load from a typed memory region that's been annotated as
 // 'nonnull', we want to trust the user on that and assume that it is is indeed
 // non-null.


Index: clang/test/Analysis/nullability.mm
===
--- clang/test/Analysis/nullability.mm
+++ clang/test/Analysis/nullability.mm
@@ -145,6 +145,17 @@
   }
 }
 
+void testArgumentTrackingDirectly(Dummy *_Nonnull nonnull, 

[PATCH] D154325: [analyzer][NFC] Move away from using raw-for loops inside StaticAnalyzer

2023-07-03 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

There remained a few more cases using raw-for loops, but those were slightly 
more tricky to uplift as they either use weird iterators or employ some fancy 
look-ahead/behind or iterate in parallel over different sequences etc.
I'll also make a measurement to confirm it doesn't change any reports.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154325

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


[PATCH] D153741: [Tooling][Rewriter] Remove the redundant AtomicallyMovedFile Implementation.

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

rebase and update.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153741

Files:
  clang/lib/Rewrite/Rewriter.cpp

Index: clang/lib/Rewrite/Rewriter.cpp
===
--- clang/lib/Rewrite/Rewriter.cpp
+++ clang/lib/Rewrite/Rewriter.cpp
@@ -14,22 +14,18 @@
 #include "clang/Rewrite/Core/Rewriter.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticIDs.h"
-#include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Rewrite/Core/RewriteBuffer.h"
 #include "clang/Rewrite/Core/RewriteRope.h"
-#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
-#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Error.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 #include 
-#include 
-#include 
 #include 
 
 using namespace clang;
@@ -410,68 +406,21 @@
   return false;
 }
 
-namespace {
-
-// A wrapper for a file stream that atomically overwrites the target.
-//
-// Creates a file output stream for a temporary file in the constructor,
-// which is later accessible via getStream() if ok() return true.
-// Flushes the stream and moves the temporary file to the target location
-// in the destructor.
-class AtomicallyMovedFile {
-public:
-  AtomicallyMovedFile(DiagnosticsEngine &Diagnostics, StringRef Filename,
-  bool &AllWritten)
-  : Diagnostics(Diagnostics), Filename(Filename), AllWritten(AllWritten) {
-TempFilename = Filename;
-TempFilename += "-";
-int FD;
-if (llvm::sys::fs::createUniqueFile(TempFilename, FD, TempFilename)) {
-  AllWritten = false;
-  Diagnostics.Report(clang::diag::err_unable_to_make_temp)
-<< TempFilename;
-} else {
-  FileStream.reset(new llvm::raw_fd_ostream(FD, /*shouldClose=*/true));
-}
-  }
-
-  ~AtomicallyMovedFile() {
-if (!ok()) return;
-
-// Close (will also flush) theFileStream.
-FileStream->close();
-if (std::error_code ec = llvm::sys::fs::rename(TempFilename, Filename)) {
-  AllWritten = false;
-  Diagnostics.Report(clang::diag::err_unable_to_rename_temp)
-<< TempFilename << Filename << ec.message();
-  // If the remove fails, there's not a lot we can do - this is already an
-  // error.
-  llvm::sys::fs::remove(TempFilename);
-}
-  }
-
-  bool ok() { return (bool)FileStream; }
-  raw_ostream &getStream() { return *FileStream; }
-
-private:
-  DiagnosticsEngine &Diagnostics;
-  StringRef Filename;
-  SmallString<128> TempFilename;
-  std::unique_ptr FileStream;
-  bool &AllWritten;
-};
-
-} // namespace
-
 bool Rewriter::overwriteChangedFiles() {
   bool AllWritten = true;
+  auto& Diag = getSourceMgr().getDiagnostics();
+  unsigned OverwriteFailure = Diag.getCustomDiagID(
+  DiagnosticsEngine::Error, "unable to overwrite file %0: %1");
   for (buffer_iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) {
-const FileEntry *Entry =
-getSourceMgr().getFileEntryForID(I->first);
-AtomicallyMovedFile File(getSourceMgr().getDiagnostics(), Entry->getName(),
- AllWritten);
-if (File.ok()) {
-  I->second.write(File.getStream());
+const FileEntry *Entry = getSourceMgr().getFileEntryForID(I->first);
+if (auto Error =
+llvm::writeToOutput(Entry->getName(), [&](llvm::raw_ostream &OS) {
+  I->second.write(OS);
+  return llvm::Error::success();
+})) {
+  Diag.Report(OverwriteFailure)
+  << Entry->getName() << llvm::toString(std::move(Error));
+  AllWritten = false;
 }
   }
   return !AllWritten;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153741: [Tooling][Rewriter] Remove the redundant AtomicallyMovedFile Implementation.

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

Thanks for the review!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153741

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


[clang] 653920c - [Tooling][Rewriter] Remove the redundant AtomicallyMovedFile Implementation.

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

Author: Haojian Wu
Date: 2023-07-03T09:38:11+02:00
New Revision: 653920cb158bf895cdb0b32098a105f26007290a

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

LOG: [Tooling][Rewriter] Remove the redundant AtomicallyMovedFile 
Implementation.

Replace it with llvm::writeToOutput.

Reviewed By: avl

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

Added: 


Modified: 
clang/lib/Rewrite/Rewriter.cpp

Removed: 




diff  --git a/clang/lib/Rewrite/Rewriter.cpp b/clang/lib/Rewrite/Rewriter.cpp
index 8950bfb7c4dccf..ef2858990dd954 100644
--- a/clang/lib/Rewrite/Rewriter.cpp
+++ b/clang/lib/Rewrite/Rewriter.cpp
@@ -14,22 +14,18 @@
 #include "clang/Rewrite/Core/Rewriter.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticIDs.h"
-#include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Rewrite/Core/RewriteBuffer.h"
 #include "clang/Rewrite/Core/RewriteRope.h"
-#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
-#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Error.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 #include 
-#include 
-#include 
 #include 
 
 using namespace clang;
@@ -410,68 +406,21 @@ bool Rewriter::IncreaseIndentation(CharSourceRange range,
   return false;
 }
 
-namespace {
-
-// A wrapper for a file stream that atomically overwrites the target.
-//
-// Creates a file output stream for a temporary file in the constructor,
-// which is later accessible via getStream() if ok() return true.
-// Flushes the stream and moves the temporary file to the target location
-// in the destructor.
-class AtomicallyMovedFile {
-public:
-  AtomicallyMovedFile(DiagnosticsEngine &Diagnostics, StringRef Filename,
-  bool &AllWritten)
-  : Diagnostics(Diagnostics), Filename(Filename), AllWritten(AllWritten) {
-TempFilename = Filename;
-TempFilename += "-";
-int FD;
-if (llvm::sys::fs::createUniqueFile(TempFilename, FD, TempFilename)) {
-  AllWritten = false;
-  Diagnostics.Report(clang::diag::err_unable_to_make_temp)
-<< TempFilename;
-} else {
-  FileStream.reset(new llvm::raw_fd_ostream(FD, /*shouldClose=*/true));
-}
-  }
-
-  ~AtomicallyMovedFile() {
-if (!ok()) return;
-
-// Close (will also flush) theFileStream.
-FileStream->close();
-if (std::error_code ec = llvm::sys::fs::rename(TempFilename, Filename)) {
-  AllWritten = false;
-  Diagnostics.Report(clang::diag::err_unable_to_rename_temp)
-<< TempFilename << Filename << ec.message();
-  // If the remove fails, there's not a lot we can do - this is already an
-  // error.
-  llvm::sys::fs::remove(TempFilename);
-}
-  }
-
-  bool ok() { return (bool)FileStream; }
-  raw_ostream &getStream() { return *FileStream; }
-
-private:
-  DiagnosticsEngine &Diagnostics;
-  StringRef Filename;
-  SmallString<128> TempFilename;
-  std::unique_ptr FileStream;
-  bool &AllWritten;
-};
-
-} // namespace
-
 bool Rewriter::overwriteChangedFiles() {
   bool AllWritten = true;
+  auto& Diag = getSourceMgr().getDiagnostics();
+  unsigned OverwriteFailure = Diag.getCustomDiagID(
+  DiagnosticsEngine::Error, "unable to overwrite file %0: %1");
   for (buffer_iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) {
-const FileEntry *Entry =
-getSourceMgr().getFileEntryForID(I->first);
-AtomicallyMovedFile File(getSourceMgr().getDiagnostics(), Entry->getName(),
- AllWritten);
-if (File.ok()) {
-  I->second.write(File.getStream());
+const FileEntry *Entry = getSourceMgr().getFileEntryForID(I->first);
+if (auto Error =
+llvm::writeToOutput(Entry->getName(), [&](llvm::raw_ostream &OS) {
+  I->second.write(OS);
+  return llvm::Error::success();
+})) {
+  Diag.Report(OverwriteFailure)
+  << Entry->getName() << llvm::toString(std::move(Error));
+  AllWritten = false;
 }
   }
   return !AllWritten;



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


[PATCH] D153741: [Tooling][Rewriter] Remove the redundant AtomicallyMovedFile Implementation.

2023-07-03 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 rG653920cb158b: [Tooling][Rewriter] Remove the redundant 
AtomicallyMovedFile Implementation. (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153741

Files:
  clang/lib/Rewrite/Rewriter.cpp

Index: clang/lib/Rewrite/Rewriter.cpp
===
--- clang/lib/Rewrite/Rewriter.cpp
+++ clang/lib/Rewrite/Rewriter.cpp
@@ -14,22 +14,18 @@
 #include "clang/Rewrite/Core/Rewriter.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticIDs.h"
-#include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Rewrite/Core/RewriteBuffer.h"
 #include "clang/Rewrite/Core/RewriteRope.h"
-#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
-#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Error.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 #include 
-#include 
-#include 
 #include 
 
 using namespace clang;
@@ -410,68 +406,21 @@
   return false;
 }
 
-namespace {
-
-// A wrapper for a file stream that atomically overwrites the target.
-//
-// Creates a file output stream for a temporary file in the constructor,
-// which is later accessible via getStream() if ok() return true.
-// Flushes the stream and moves the temporary file to the target location
-// in the destructor.
-class AtomicallyMovedFile {
-public:
-  AtomicallyMovedFile(DiagnosticsEngine &Diagnostics, StringRef Filename,
-  bool &AllWritten)
-  : Diagnostics(Diagnostics), Filename(Filename), AllWritten(AllWritten) {
-TempFilename = Filename;
-TempFilename += "-";
-int FD;
-if (llvm::sys::fs::createUniqueFile(TempFilename, FD, TempFilename)) {
-  AllWritten = false;
-  Diagnostics.Report(clang::diag::err_unable_to_make_temp)
-<< TempFilename;
-} else {
-  FileStream.reset(new llvm::raw_fd_ostream(FD, /*shouldClose=*/true));
-}
-  }
-
-  ~AtomicallyMovedFile() {
-if (!ok()) return;
-
-// Close (will also flush) theFileStream.
-FileStream->close();
-if (std::error_code ec = llvm::sys::fs::rename(TempFilename, Filename)) {
-  AllWritten = false;
-  Diagnostics.Report(clang::diag::err_unable_to_rename_temp)
-<< TempFilename << Filename << ec.message();
-  // If the remove fails, there's not a lot we can do - this is already an
-  // error.
-  llvm::sys::fs::remove(TempFilename);
-}
-  }
-
-  bool ok() { return (bool)FileStream; }
-  raw_ostream &getStream() { return *FileStream; }
-
-private:
-  DiagnosticsEngine &Diagnostics;
-  StringRef Filename;
-  SmallString<128> TempFilename;
-  std::unique_ptr FileStream;
-  bool &AllWritten;
-};
-
-} // namespace
-
 bool Rewriter::overwriteChangedFiles() {
   bool AllWritten = true;
+  auto& Diag = getSourceMgr().getDiagnostics();
+  unsigned OverwriteFailure = Diag.getCustomDiagID(
+  DiagnosticsEngine::Error, "unable to overwrite file %0: %1");
   for (buffer_iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) {
-const FileEntry *Entry =
-getSourceMgr().getFileEntryForID(I->first);
-AtomicallyMovedFile File(getSourceMgr().getDiagnostics(), Entry->getName(),
- AllWritten);
-if (File.ok()) {
-  I->second.write(File.getStream());
+const FileEntry *Entry = getSourceMgr().getFileEntryForID(I->first);
+if (auto Error =
+llvm::writeToOutput(Entry->getName(), [&](llvm::raw_ostream &OS) {
+  I->second.write(OS);
+  return llvm::Error::success();
+})) {
+  Diag.Report(OverwriteFailure)
+  << Entry->getName() << llvm::toString(std::move(Error));
+  AllWritten = false;
 }
   }
   return !AllWritten;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D154325: [analyzer][NFC] Move away from using raw-for loops inside StaticAnalyzer

2023-07-03 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus accepted this revision.
Szelethus added a comment.
This revision is now accepted and ready to land.

But this renders much of my C++98 knowledge obsolete!11


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154325

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


[PATCH] D128648: [Clang][AArch64][SME] Add vector read/write (mova) intrinsics

2023-07-03 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen added inline comments.



Comment at: clang/test/CodeGen/aarch64-sme-intrinsics/acle_sme_read.c:13
+#else
+#define ARM_STREAMING_ATTR __attribute__((arm_streaming))
+#endif

The spelling has recently changed to the `__arm_streaming`. Also with the new 
attribute keywords, the position of the attributes is more strict and need sto 
be after the function arguments (e.g. `svint8_t test_svread_..(...) 
ARM_STREAMING_ATTR {`)

Sorry if I previously gave you the wrong steer here to add these macros, but 
I've changed my mind and think it's better to remove them for now. That means 
we won't have any streaming attributes on the functions in the tests, but we 
can (and will need to) add those when we add diagnostics for missing 
attributes, for example when using a `shared ZA` intrinsic  when the function 
misses `__arm_shared_za/__arm_new_za`, or when using a streaming intrinsic when 
the function is not `__arm_streaming`. Writing this also made me realise the 
functions below would be missing `__arm_shared_za` attributes.

Can you remove these macros from the patches? Again, my apologies for the wrong 
steer!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128648

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


[PATCH] D140690: [dfsan] Support Linux loongarch64

2023-07-03 Thread Limin Zhang 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 rG280d163887ea: [dfsan] Support Linux loongarch64 (authored by 
Ami-zhang).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140690

Files:
  clang/lib/Driver/ToolChains/Linux.cpp
  compiler-rt/cmake/Modules/AllSupportedArchDefs.cmake
  compiler-rt/test/dfsan/lit.cfg.py
  llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp


Index: llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp
@@ -305,6 +305,14 @@
 };
 // NOLINTEND(readability-identifier-naming)
 
+// loongarch64 Linux
+const MemoryMapParams Linux_LoongArch64_MemoryMapParams = {
+0,  // AndMask (not used)
+0x5000, // XorMask
+0,  // ShadowBase (not used)
+0x1000, // OriginBase
+};
+
 namespace {
 
 class DFSanABIList {
@@ -1128,6 +1136,9 @@
   case Triple::x86_64:
 MapParams = &Linux_X86_64_MemoryMapParams;
 break;
+  case Triple::loongarch64:
+MapParams = &Linux_LoongArch64_MemoryMapParams;
+break;
   default:
 report_fatal_error("unsupported architecture");
   }
Index: compiler-rt/test/dfsan/lit.cfg.py
===
--- compiler-rt/test/dfsan/lit.cfg.py
+++ compiler-rt/test/dfsan/lit.cfg.py
@@ -25,5 +25,5 @@
 config.suffixes = [".c", ".cpp"]
 
 # DataFlowSanitizer tests are currently supported on Linux only.
-if not (config.host_os in ["Linux"] and config.target_arch in ["aarch64", 
"x86_64"]):
+if not (config.host_os in ["Linux"] and config.target_arch in ["aarch64", 
"x86_64", "loongarch64"]):
 config.unsupported = True
Index: compiler-rt/cmake/Modules/AllSupportedArchDefs.cmake
===
--- compiler-rt/cmake/Modules/AllSupportedArchDefs.cmake
+++ compiler-rt/cmake/Modules/AllSupportedArchDefs.cmake
@@ -30,7 +30,7 @@
 ${MIPS32} ${MIPS64} ${PPC64} ${S390X} ${SPARC} ${SPARCV9} ${HEXAGON}
 ${LOONGARCH64})
 set(ALL_ASAN_ABI_SUPPORTED_ARCH ${X86_64} ${ARM64})
-set(ALL_DFSAN_SUPPORTED_ARCH ${X86_64} ${MIPS64} ${ARM64})
+set(ALL_DFSAN_SUPPORTED_ARCH ${X86_64} ${MIPS64} ${ARM64} ${LOONGARCH64})
 
 if(ANDROID)
   set(OS_NAME "Android")
Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -795,7 +795,7 @@
   Res |= SanitizerKind::Memory;
   Res |= SanitizerKind::Vptr;
   Res |= SanitizerKind::SafeStack;
-  if (IsX86_64 || IsMIPS64 || IsAArch64)
+  if (IsX86_64 || IsMIPS64 || IsAArch64 || IsLoongArch64)
 Res |= SanitizerKind::DataFlow;
   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsArmArch || IsPowerPC64 ||
   IsRISCV64 || IsSystemZ || IsHexagon || IsLoongArch64)


Index: llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp
@@ -305,6 +305,14 @@
 };
 // NOLINTEND(readability-identifier-naming)
 
+// loongarch64 Linux
+const MemoryMapParams Linux_LoongArch64_MemoryMapParams = {
+0,  // AndMask (not used)
+0x5000, // XorMask
+0,  // ShadowBase (not used)
+0x1000, // OriginBase
+};
+
 namespace {
 
 class DFSanABIList {
@@ -1128,6 +1136,9 @@
   case Triple::x86_64:
 MapParams = &Linux_X86_64_MemoryMapParams;
 break;
+  case Triple::loongarch64:
+MapParams = &Linux_LoongArch64_MemoryMapParams;
+break;
   default:
 report_fatal_error("unsupported architecture");
   }
Index: compiler-rt/test/dfsan/lit.cfg.py
===
--- compiler-rt/test/dfsan/lit.cfg.py
+++ compiler-rt/test/dfsan/lit.cfg.py
@@ -25,5 +25,5 @@
 config.suffixes = [".c", ".cpp"]
 
 # DataFlowSanitizer tests are currently supported on Linux only.
-if not (config.host_os in ["Linux"] and config.target_arch in ["aarch64", "x86_64"]):
+if not (config.host_os in ["Linux"] and config.target_arch in ["aarch64", "x86_64", "loongarch64"]):
 config.unsupported = True
Index: compiler-rt/cmake/Modules/AllSupportedArchDefs.cmake
===
--- compiler-rt/cmake/Modules/AllSupportedArchDefs.cmake
+++ compiler-rt/cmake/Modules/AllSupportedArchDefs.cmake
@@ -30,7 +30,7 @@
 ${MIPS32} ${MIPS64} ${PPC64} ${S390X} ${SPARC} ${SPARCV9} ${HEXAGON}
 ${LOONGARCH64})
 set(ALL_ASAN_ABI_SUPPORTED_ARCH ${X86_64} ${ARM64})
-set(ALL_DFSAN_SUPPORTED_ARCH 

[PATCH] D153738: Add LibClang guide

2023-07-03 Thread Manuel via Phabricator via cfe-commits
manuel5975p accepted this revision.
manuel5975p added a comment.
This revision is now accepted and ready to land.

Thanks a lot for carefully going through this. I will dispose of the 
documentation for CXType after accepting.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153738

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


[clang] 1bd2d33 - [analyzer][CStringChecker] Adjust the invalidation operation on the super region of the destination buffer during string copy

2023-07-03 Thread Ella Ma via cfe-commits

Author: Ella Ma
Date: 2023-07-03T16:13:47+08:00
New Revision: 1bd2d335b649f2e09d7e4bdd0b92c78489ded022

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

LOG: [analyzer][CStringChecker] Adjust the invalidation operation on the super 
region of the destination buffer during string copy

Fixing GitHub issue: https://github.com/llvm/llvm-project/issues/55019
Following the previous fix https://reviews.llvm.org/D12571 on issue 
https://github.com/llvm/llvm-project/issues/23328

The two issues report false memory leaks after calling string-copy APIs with a 
buffer field in an object as the destination.
The buffer invalidation incorrectly drops the assignment to a heap memory block 
when no overflow problems happen.
And the pointer of the dropped assignment is declared in the same object of the 
destination buffer.

The previous fix only considers the `memcpy` functions whose copy length is 
available from arguments.
In this issue, the copy length is inferable from the buffer declaration and 
string literals being copied.
Therefore, I have adjusted the previous fix to reuse the copy length computed 
before.

Besides, for APIs that never overflow (strsep) or we never know whether they 
can overflow (std::copy),
new invalidation operations have been introduced to inform 
CStringChecker::InvalidateBuffer whether or not to
invalidate the super region that encompasses the destination buffer.

Reviewed By: steakhal

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

Added: 
clang/test/Analysis/issue-55019.cpp

Modified: 
clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
clang/test/Analysis/Inputs/system-header-simulator.h
clang/test/Analysis/pr22954.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
index 01a35505a90a2c..af9cf1443bacd3 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -260,11 +260,34 @@ class CStringChecker : public Checker< eval::Call,
  const Expr *expr,
  SVal val) const;
 
-  static ProgramStateRef InvalidateBuffer(CheckerContext &C,
-  ProgramStateRef state,
-  const Expr *Ex, SVal V,
-  bool IsSourceBuffer,
-  const Expr *Size);
+  /// Invalidate the destination buffer determined by characters copied.
+  static ProgramStateRef
+  invalidateDestinationBufferBySize(CheckerContext &C, ProgramStateRef S,
+const Expr *BufE, SVal BufV, SVal SizeV,
+QualType SizeTy);
+
+  /// Operation never overflows, do not invalidate the super region.
+  static ProgramStateRef invalidateDestinationBufferNeverOverflows(
+  CheckerContext &C, ProgramStateRef S, const Expr *BufE, SVal BufV);
+
+  /// We do not know whether the operation can overflow (e.g. size is unknown),
+  /// invalidate the super region and escape related pointers.
+  static ProgramStateRef invalidateDestinationBufferAlwaysEscapeSuperRegion(
+  CheckerContext &C, ProgramStateRef S, const Expr *BufE, SVal BufV);
+
+  /// Invalidate the source buffer for escaping pointers.
+  static ProgramStateRef invalidateSourceBuffer(CheckerContext &C,
+ProgramStateRef S,
+const Expr *BufE, SVal BufV);
+
+  /// @param InvalidationTraitOperations Determine how to invlidate the
+  /// MemRegion by setting the invalidation traits. Return true to cause 
pointer
+  /// escape, or false otherwise.
+  static ProgramStateRef invalidateBufferAux(
+  CheckerContext &C, ProgramStateRef State, const Expr *Ex, SVal V,
+  llvm::function_ref
+  InvalidationTraitOperations);
 
   static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
   const MemRegion *MR);
@@ -310,10 +333,9 @@ class CStringChecker : public Checker< eval::Call,
   // Return true if the destination buffer of the copy function may be in 
bound.
   // Expects SVal of Size to be positive and unsigned.
   // Expects SVal of FirstBuf to be a FieldRegion.
-  static bool IsFirstBufInBound(CheckerContext &C,
-ProgramStateRef state,
-const Expr *FirstBuf,
-const Expr *Size);
+  static bool isFirstBufInBound(CheckerContext &C, ProgramStateRef State,
+SVal BufVal, QualType BufTy, SVal LengthVal,
+Qual

[PATCH] D152435: [analyzer][CStringChecker] Adjust the invalidation operation on the super region of the destination buffer during string copy

2023-07-03 Thread Ella Ma 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 rG1bd2d335b649: [analyzer][CStringChecker] Adjust the 
invalidation operation on the super… (authored by OikawaKirie).

Changed prior to commit:
  https://reviews.llvm.org/D152435?vs=536662&id=536683#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152435

Files:
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/test/Analysis/Inputs/system-header-simulator.h
  clang/test/Analysis/issue-55019.cpp
  clang/test/Analysis/pr22954.c

Index: clang/test/Analysis/pr22954.c
===
--- clang/test/Analysis/pr22954.c
+++ clang/test/Analysis/pr22954.c
@@ -556,12 +556,13 @@
   x263.s2 = strdup("hello");
   char input[] = {'a', 'b', 'c', 'd'};
   memcpy(x263.s1, input, *(len + n));
-  clang_analyzer_eval(x263.s1[0] == 0); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(x263.s1[0] == 0); // expected-warning{{UNKNOWN}}\
+  expected-warning{{Potential leak of memory pointed to by 'x263.s2'}}
   clang_analyzer_eval(x263.s1[1] == 0); // expected-warning{{UNKNOWN}}
   clang_analyzer_eval(x263.s1[2] == 0); // expected-warning{{UNKNOWN}}
   clang_analyzer_eval(x263.s1[3] == 0); // expected-warning{{UNKNOWN}}
   clang_analyzer_eval(x263.s2 == 0); // expected-warning{{UNKNOWN}}
-  return 0; // expected-warning{{Potential leak of memory pointed to by 'x263.s2'}}
+  return 0;
 }
 
 
Index: clang/test/Analysis/issue-55019.cpp
===
--- /dev/null
+++ clang/test/Analysis/issue-55019.cpp
@@ -0,0 +1,89 @@
+// Refer issue 55019 for more details.
+// A supplemental test case of pr22954.c for other functions modeled in
+// the CStringChecker.
+
+// RUN: %clang_analyze_cc1 %s -verify \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=unix \
+// RUN:   -analyzer-checker=debug.ExprInspection
+
+#include "Inputs/system-header-simulator.h"
+#include "Inputs/system-header-simulator-cxx.h"
+
+void *malloc(size_t);
+void free(void *);
+
+struct mystruct {
+  void *ptr;
+  char arr[4];
+};
+
+void clang_analyzer_dump(const void *);
+
+// CStringChecker::memsetAux
+void fmemset() {
+  mystruct x;
+  x.ptr = malloc(1);
+  clang_analyzer_dump(x.ptr); // expected-warning {{HeapSymRegion}}
+  memset(x.arr, 0, sizeof(x.arr));
+  clang_analyzer_dump(x.ptr); // expected-warning {{HeapSymRegion}}
+  free(x.ptr);// no-leak-warning
+}
+
+// CStringChecker::evalCopyCommon
+void fmemcpy() {
+  mystruct x;
+  x.ptr = malloc(1);
+  clang_analyzer_dump(x.ptr); // expected-warning {{HeapSymRegion}}
+  memcpy(x.arr, "hi", 2);
+  clang_analyzer_dump(x.ptr); // expected-warning {{HeapSymRegion}}
+  free(x.ptr);// no-leak-warning
+}
+
+// CStringChecker::evalStrcpyCommon
+void fstrcpy() {
+  mystruct x;
+  x.ptr = malloc(1);
+  clang_analyzer_dump(x.ptr); // expected-warning {{HeapSymRegion}}
+  strcpy(x.arr, "hi");
+  clang_analyzer_dump(x.ptr); // expected-warning {{HeapSymRegion}}
+  free(x.ptr);// no-leak-warning
+}
+
+void fstrncpy() {
+  mystruct x;
+  x.ptr = malloc(1);
+  clang_analyzer_dump(x.ptr); // expected-warning {{HeapSymRegion}}
+  strncpy(x.arr, "hi", sizeof(x.arr));
+  clang_analyzer_dump(x.ptr); // expected-warning {{HeapSymRegion}}
+  free(x.ptr);// no-leak-warning
+}
+
+// CStringChecker::evalStrsep
+void fstrsep() {
+  mystruct x;
+  x.ptr = malloc(1);
+  clang_analyzer_dump(x.ptr); // expected-warning {{HeapSymRegion}}
+  char *p = x.arr;
+  (void)strsep(&p, "x");
+  clang_analyzer_dump(x.ptr); // expected-warning {{HeapSymRegion}}
+  free(x.ptr);// no-leak-warning
+}
+
+// CStringChecker::evalStdCopyCommon
+void fstdcopy() {
+  mystruct x;
+  x.ptr = new char;
+  clang_analyzer_dump(x.ptr); // expected-warning {{HeapSymRegion}}
+
+  const char *p = "x";
+  std::copy(p, p + 1, x.arr);
+
+  // FIXME: As we currently cannot know whether the copy overflows, the checker
+  // invalidates the entire `x` object. When the copy size through iterators
+  // can be correctly modeled, we can then update the verify direction from
+  // SymRegion to HeapSymRegion as this std::copy call never overflows and
+  // hence the pointer `x.ptr` shall not be invalidated.
+  clang_analyzer_dump(x.ptr);   // expected-warning {{SymRegion}}
+  delete static_cast(x.ptr); // no-leak-warning
+}
Index: clang/test/Analysis/Inputs/system-header-simulator.h
===
--- clang/test/Analysis/Inputs/system-header-simulator.h
+++ clang/test/Analysis/Inputs/system-header-simulator.h
@@ -63,7 +63,9 @@
 
 char *strcpy(char *restrict, const char *restrict);
 char *strncpy(char *dst, const char *src, size_t n);
+char *strsep(char **stringp, const char *delim);
 vo

[PATCH] D135849: [llvm] Return canonical virtual path from `RedirectingFileSystem`

2023-07-03 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

In D135849#4464234 , @benlangmuir 
wrote:

>> Just realized this most likely won't work if the case-insensitive VFS is 
>> specified with wrong spelling too, e.g. Fw.framework.
>
> Is this about the spelling in the VFS definition itself, or about the path 
> being looked up?

Yes, spelling in the VFS definition itself.

> If it's the VFS definition maybe we can say that's a bug for whoever wrote 
> the VFS? Ideally we could diagnose but I'm not sure we want to pay for a lot 
> of calls to realpath.

You mean diagnosing whenever the spelling in the VFS definition differs from 
its realpath? How could we make that work with symlinks in place?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135849

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


[PATCH] D153006: [clang][dataflow] Perform deep copies in copy and move operations.

2023-07-03 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added inline comments.



Comment at: clang/include/clang/Analysis/FlowSensitive/RecordOps.h:26
+/// fields of record type. It also copies properties from the `StructValue`
+/// associated with `Dst` to the `StructValue` associated with `Src` (if these
+/// `StructValue`s exist).

Shouldn't it go the other way, from Src to Dst?



Comment at: clang/include/clang/Analysis/FlowSensitive/RecordOps.h:53
+/// refer to the same storage location. If `StructValue`s are associated with
+/// `Loc1` and `Loc2`, it also compares the properties on those `StructValue`s.
+///

Could you add a caveat that only 'true' return values from this function matter?

That is, "false" means "might or might not be equal at runtime, we don't know".



Comment at: clang/unittests/Analysis/FlowSensitive/TestingSupport.h:391
+llvm::Error
+runDataflowReturnError(llvm::StringRef Code, VerifyResultsT VerifyResults,
+   DataflowAnalysisOptions Options,

Could you change VerifyResultsT to a std::function (like in other overloads 
above) so that the type signature is clear?

I'm also unsure about the name - why start a new overload set? It seems like 
another variant of the checkDataflow() functions above.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153006

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


[PATCH] D154328: [AST] Add API to iterate already loaded specializations

2023-07-03 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld created this revision.
Hahnfeld added reviewers: erichkeane, aaron.ballman.
Herald added a project: All.
Hahnfeld requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

These new functions allow to look at specializations without triggering 
deserialization, which might be problematic in some contexts.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154328

Files:
  clang/include/clang/AST/DeclTemplate.h


Index: clang/include/clang/AST/DeclTemplate.h
===
--- clang/include/clang/AST/DeclTemplate.h
+++ clang/include/clang/AST/DeclTemplate.h
@@ -1114,6 +1114,20 @@
 return makeSpecIterator(getSpecializations(), true);
   }
 
+  /// All specializations that that have already been loaded, ie avoiding
+  /// deserialization of lazily registered specializations.
+  spec_range loaded_specializations() const {
+return spec_range(loaded_spec_begin(), loaded_spec_end());
+  }
+
+  spec_iterator loaded_spec_begin() const {
+return makeSpecIterator(getCommonPtr()->Specializations, false);
+  }
+
+  spec_iterator loaded_spec_end() const {
+return makeSpecIterator(getCommonPtr()->Specializations, true);
+  }
+
   /// Return whether this function template is an abbreviated function 
template,
   /// e.g. `void foo(auto x)` or `template void foo(auto x)`
   bool isAbbreviated() const {
@@ -2454,6 +2468,20 @@
 return makeSpecIterator(getSpecializations(), true);
   }
 
+  /// All specializations that that have already been loaded, ie avoiding
+  /// deserialization of lazily registered specializations.
+  spec_range loaded_specializations() const {
+return spec_range(loaded_spec_begin(), loaded_spec_end());
+  }
+
+  spec_iterator loaded_spec_begin() const {
+return makeSpecIterator(getCommonPtr()->Specializations, false);
+  }
+
+  spec_iterator loaded_spec_end() const {
+return makeSpecIterator(getCommonPtr()->Specializations, true);
+  }
+
   // Implement isa/cast/dyncast support
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classofKind(Kind K) { return K == ClassTemplate; }
@@ -3262,6 +3290,20 @@
 return makeSpecIterator(getSpecializations(), true);
   }
 
+  /// All specializations that that have already been loaded, ie avoiding
+  /// deserialization of lazily registered specializations.
+  spec_range loaded_specializations() const {
+return spec_range(loaded_spec_begin(), loaded_spec_end());
+  }
+
+  spec_iterator loaded_spec_begin() const {
+return makeSpecIterator(getCommonPtr()->Specializations, false);
+  }
+
+  spec_iterator loaded_spec_end() const {
+return makeSpecIterator(getCommonPtr()->Specializations, true);
+  }
+
   // Implement isa/cast/dyncast support
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classofKind(Kind K) { return K == VarTemplate; }


Index: clang/include/clang/AST/DeclTemplate.h
===
--- clang/include/clang/AST/DeclTemplate.h
+++ clang/include/clang/AST/DeclTemplate.h
@@ -1114,6 +1114,20 @@
 return makeSpecIterator(getSpecializations(), true);
   }
 
+  /// All specializations that that have already been loaded, ie avoiding
+  /// deserialization of lazily registered specializations.
+  spec_range loaded_specializations() const {
+return spec_range(loaded_spec_begin(), loaded_spec_end());
+  }
+
+  spec_iterator loaded_spec_begin() const {
+return makeSpecIterator(getCommonPtr()->Specializations, false);
+  }
+
+  spec_iterator loaded_spec_end() const {
+return makeSpecIterator(getCommonPtr()->Specializations, true);
+  }
+
   /// Return whether this function template is an abbreviated function template,
   /// e.g. `void foo(auto x)` or `template void foo(auto x)`
   bool isAbbreviated() const {
@@ -2454,6 +2468,20 @@
 return makeSpecIterator(getSpecializations(), true);
   }
 
+  /// All specializations that that have already been loaded, ie avoiding
+  /// deserialization of lazily registered specializations.
+  spec_range loaded_specializations() const {
+return spec_range(loaded_spec_begin(), loaded_spec_end());
+  }
+
+  spec_iterator loaded_spec_begin() const {
+return makeSpecIterator(getCommonPtr()->Specializations, false);
+  }
+
+  spec_iterator loaded_spec_end() const {
+return makeSpecIterator(getCommonPtr()->Specializations, true);
+  }
+
   // Implement isa/cast/dyncast support
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classofKind(Kind K) { return K == ClassTemplate; }
@@ -3262,6 +3290,20 @@
 return makeSpecIterator(getSpecializations(), true);
   }
 
+  /// All specializations that that have already been loaded, ie avoiding
+  /// deserialization of lazily registered specializations.
+  spec_range loaded_specializations() const {
+return spec_rang

[PATCH] D137787: [CodeGen] Relax assertion on generating destructor call

2023-07-03 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld abandoned this revision.
Hahnfeld added a comment.

apparently not needed anymore downstream...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137787

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


[PATCH] D134677: [Clang][AArch64][SME] Add ZA zeroing intrinsics

2023-07-03 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen added a comment.

Other than my comment on the test, the patch looks good to me.




Comment at: clang/test/CodeGen/aarch64-sme-intrinsics/acle_sme_zero.c:20
+//
+ARM_SHARED_ZA_ATTR void test_svzero_mask_za() {
+  svzero_mask_za(0);

The new keyword attributes are a bit stricter on the placement.

Because this is a //type// attribute (as opposed to a //declaration// 
attribute), it should be placed like this:

  void test_svzero_mask_za() ARM_SHARED_ZA_ATTR {

As I mentioned on D128648, I think it's better to remove all these macros for 
now and only add the attributes when we add diagnostics in Sema for missing 
attributes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134677

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


[PATCH] D152996: [RISCV][POC] Model frm control for vfadd

2023-07-03 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
eopXD updated this revision to Diff 536688.
eopXD added a comment.

Update suffix from

`vfadd_vv_i32m1_{policy_suffix, if any}_rm` to 
`vfadd_vv_i32m1_rm_{policy_suffix, if any}`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152996

Files:
  clang/include/clang/Basic/riscv_vector.td
  clang/include/clang/Basic/riscv_vector_common.td
  clang/include/clang/Support/RISCVVIntrinsicUtils.h
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaRISCVVectorLookup.cpp
  clang/lib/Support/RISCVVIntrinsicUtils.cpp
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/overloaded/vfadd.c
  clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/vfadd-out-of-range.c
  clang/utils/TableGen/RISCVVEmitter.cpp
  llvm/include/llvm/IR/IntrinsicsRISCV.td
  llvm/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.h
  llvm/lib/Target/RISCV/RISCVISelDAGToDAG.cpp
  llvm/lib/Target/RISCV/RISCVISelLowering.cpp
  llvm/lib/Target/RISCV/RISCVInsertReadWriteCSR.cpp
  llvm/lib/Target/RISCV/RISCVInstrFormats.td
  llvm/lib/Target/RISCV/RISCVInstrInfoVPseudos.td
  llvm/lib/Target/RISCV/RISCVInstrInfoVSDPatterns.td
  llvm/lib/Target/RISCV/RISCVInstrInfoVVLPatterns.td
  llvm/test/CodeGen/RISCV/rvv/alloca-load-store-scalable-struct.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-fmf.ll
  llvm/test/CodeGen/RISCV/rvv/masked-tama.ll
  llvm/test/CodeGen/RISCV/rvv/masked-tamu.ll
  llvm/test/CodeGen/RISCV/rvv/masked-tuma.ll
  llvm/test/CodeGen/RISCV/rvv/masked-tumu.ll
  llvm/test/CodeGen/RISCV/rvv/rv32-spill-vector-csr.ll
  llvm/test/CodeGen/RISCV/rvv/rv64-spill-vector-csr.ll
  llvm/test/CodeGen/RISCV/rvv/rvv-peephole-vmerge-masked-vops.ll
  llvm/test/CodeGen/RISCV/rvv/unmasked-tu.ll
  llvm/test/CodeGen/RISCV/rvv/vfadd.ll
  llvm/test/CodeGen/RISCV/rvv/vsetvli-insert-crossbb.ll
  llvm/test/CodeGen/RISCV/rvv/vsetvli-insert.ll

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


[PATCH] D154325: [analyzer][NFC] Move away from using raw-for loops inside StaticAnalyzer

2023-07-03 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

The transformations were done by hand. So I'd encourage you all to have a look 
and find places where it breaks. Also, it might have personal biases about the 
style I settled with. Feel free to challenge.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154325

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


[PATCH] D154329: [lldb] Replace llvm::writeFileAtomically with llvm::writeToOutput API.

2023-07-03 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added reviewers: avl, JDevlieghere.
Herald added a project: All.
hokein requested review of this revision.
Herald added a project: LLDB.
Herald added a subscriber: lldb-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154329

Files:
  lldb/tools/lldb-server/lldb-platform.cpp


Index: lldb/tools/lldb-server/lldb-platform.cpp
===
--- lldb/tools/lldb-server/lldb-platform.cpp
+++ lldb/tools/lldb-server/lldb-platform.cpp
@@ -22,7 +22,6 @@
 #include 
 
 #include "llvm/Support/FileSystem.h"
-#include "llvm/Support/FileUtilities.h"
 #include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -103,38 +102,14 @@
 return Status("Failed to create directory %s: %s",
   temp_file_spec.GetPath().c_str(), error.AsCString());
 
-  llvm::SmallString<64> temp_file_path;
-  temp_file_spec.AppendPathComponent("port-file.%%");
-  temp_file_path = temp_file_spec.GetPath();
-
   Status status;
-  if (auto Err =
-  handleErrors(llvm::writeFileAtomically(
-   temp_file_path, file_spec.GetPath(), socket_id),
-   [&status, &file_spec](const AtomicFileWriteError &E) {
- std::string ErrorMsgBuffer;
- llvm::raw_string_ostream S(ErrorMsgBuffer);
- E.log(S);
-
- switch (E.Error) {
- case atomic_write_error::failed_to_create_uniq_file:
-   status = Status("Failed to create temp file: %s",
-   ErrorMsgBuffer.c_str());
-   break;
- case atomic_write_error::output_stream_error:
-   status = Status("Failed to write to port file.");
-   break;
- case atomic_write_error::failed_to_rename_temp_file:
-   status = Status("Failed to rename file %s to %s: 
%s",
-   ErrorMsgBuffer.c_str(),
-   file_spec.GetPath().c_str(),
-   ErrorMsgBuffer.c_str());
-   break;
- }
-   })) {
+  if (auto Err = llvm::writeToOutput(file_spec.GetPath(),
+ [&socket_id](llvm::raw_ostream &OS) {
+   OS << socket_id;
+   return llvm::Error::success();
+ }))
 return Status("Failed to atomically write file %s",
   file_spec.GetPath().c_str());
-  }
   return status;
 }
 


Index: lldb/tools/lldb-server/lldb-platform.cpp
===
--- lldb/tools/lldb-server/lldb-platform.cpp
+++ lldb/tools/lldb-server/lldb-platform.cpp
@@ -22,7 +22,6 @@
 #include 
 
 #include "llvm/Support/FileSystem.h"
-#include "llvm/Support/FileUtilities.h"
 #include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -103,38 +102,14 @@
 return Status("Failed to create directory %s: %s",
   temp_file_spec.GetPath().c_str(), error.AsCString());
 
-  llvm::SmallString<64> temp_file_path;
-  temp_file_spec.AppendPathComponent("port-file.%%");
-  temp_file_path = temp_file_spec.GetPath();
-
   Status status;
-  if (auto Err =
-  handleErrors(llvm::writeFileAtomically(
-   temp_file_path, file_spec.GetPath(), socket_id),
-   [&status, &file_spec](const AtomicFileWriteError &E) {
- std::string ErrorMsgBuffer;
- llvm::raw_string_ostream S(ErrorMsgBuffer);
- E.log(S);
-
- switch (E.Error) {
- case atomic_write_error::failed_to_create_uniq_file:
-   status = Status("Failed to create temp file: %s",
-   ErrorMsgBuffer.c_str());
-   break;
- case atomic_write_error::output_stream_error:
-   status = Status("Failed to write to port file.");
-   break;
- case atomic_write_error::failed_to_rename_temp_file:
-   status = Status("Failed to rename file %s to %s: %s",
-   ErrorMsgBuffer.c_str(),
-   file_spec.GetPath().c_str(),
-   ErrorMsgBuffer.c_str());
-   break;
- }
-   })) {
+  if (auto Err = llvm::writeToOutput(file_spec.GetPath(),
+ [&socket_

[PATCH] D152356: [clang][ExtractAPI] Add --emit-symbol-graph option

2023-07-03 Thread Daniel Grumberg via Phabricator via cfe-commits
dang accepted this revision.
dang added a comment.
This revision is now accepted and ready to land.

LGTM thanks for working on this!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152356

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


[PATCH] D153740: [llvm][Support] Deprecate llvm::writeFileAtomically API

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

Restrict the patch to only remove the writeFileAtomically API


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153740

Files:
  llvm/include/llvm/Support/FileUtilities.h
  llvm/lib/Support/FileUtilities.cpp
  llvm/unittests/Support/CMakeLists.txt
  llvm/unittests/Support/FileUtilitiesTest.cpp

Index: llvm/unittests/Support/FileUtilitiesTest.cpp
===
--- llvm/unittests/Support/FileUtilitiesTest.cpp
+++ /dev/null
@@ -1,54 +0,0 @@
-//===- llvm/unittest/Support/FileUtilitiesTest.cpp - unit tests ---===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-
-#include "llvm/Support/FileUtilities.h"
-#include "llvm/Support/Errc.h"
-#include "llvm/Support/ErrorHandling.h"
-#include "llvm/Support/FileSystem.h"
-#include "llvm/Support/MemoryBuffer.h"
-#include "llvm/Support/Path.h"
-#include "llvm/Testing/Support/SupportHelpers.h"
-#include "gtest/gtest.h"
-#include 
-
-using namespace llvm;
-using namespace llvm::sys;
-
-using llvm::unittest::TempDir;
-
-#define ASSERT_NO_ERROR(x) \
-  if (std::error_code ASSERT_NO_ERROR_ec = x) {\
-SmallString<128> MessageStorage;   \
-raw_svector_ostream Message(MessageStorage);   \
-Message << #x ": did not return errc::success.\n"  \
-<< "error number: " << ASSERT_NO_ERROR_ec.value() << "\n"  \
-<< "error message: " << ASSERT_NO_ERROR_ec.message() << "\n";  \
-GTEST_FATAL_FAILURE_(MessageStorage.c_str());  \
-  } else { \
-  }
-
-namespace {
-TEST(writeFileAtomicallyTest, Test) {
-  // Create unique temporary directory for these tests
-  TempDir RootTestDirectory("writeFileAtomicallyTest", /*Unique*/ true);
-
-  SmallString<128> FinalTestfilePath(RootTestDirectory.path());
-  sys::path::append(FinalTestfilePath, "foo.txt");
-  const std::string TempUniqTestFileModel =
-  std::string(FinalTestfilePath) + "-";
-  const std::string TestfileContent = "fooFOOfoo";
-
-  llvm::Error Err = llvm::writeFileAtomically(TempUniqTestFileModel, FinalTestfilePath, TestfileContent);
-  ASSERT_FALSE(static_cast(Err));
-
-  std::ifstream FinalFileStream(std::string(FinalTestfilePath.str()));
-  std::string FinalFileContent;
-  FinalFileStream >> FinalFileContent;
-  ASSERT_EQ(FinalFileContent, TestfileContent);
-}
-} // anonymous namespace
Index: llvm/unittests/Support/CMakeLists.txt
===
--- llvm/unittests/Support/CMakeLists.txt
+++ llvm/unittests/Support/CMakeLists.txt
@@ -41,7 +41,6 @@
   ExtensibleRTTITest.cpp
   FileCollectorTest.cpp
   FileOutputBufferTest.cpp
-  FileUtilitiesTest.cpp
   FormatVariadicTest.cpp
   FSUniqueIDTest.cpp
   GlobPatternTest.cpp
Index: llvm/lib/Support/FileUtilities.cpp
===
--- llvm/lib/Support/FileUtilities.cpp
+++ llvm/lib/Support/FileUtilities.cpp
@@ -267,64 +267,6 @@
   return CompareFailed;
 }
 
-void llvm::AtomicFileWriteError::log(raw_ostream &OS) const {
-  OS << "atomic_write_error: ";
-  switch (Error) {
-  case atomic_write_error::failed_to_create_uniq_file:
-OS << "failed_to_create_uniq_file";
-return;
-  case atomic_write_error::output_stream_error:
-OS << "output_stream_error";
-return;
-  case atomic_write_error::failed_to_rename_temp_file:
-OS << "failed_to_rename_temp_file";
-return;
-  }
-  llvm_unreachable("unknown atomic_write_error value in "
-   "failed_to_rename_temp_file::log()");
-}
-
-llvm::Error llvm::writeFileAtomically(StringRef TempPathModel,
-  StringRef FinalPath, StringRef Buffer) {
-  return writeFileAtomically(TempPathModel, FinalPath,
- [&Buffer](llvm::raw_ostream &OS) {
-   OS.write(Buffer.data(), Buffer.size());
-   return llvm::Error::success();
- });
-}
-
-llvm::Error llvm::writeFileAtomically(
-StringRef TempPathModel, StringRef FinalPath,
-std::function Writer) {
-  SmallString<128> GeneratedUniqPath;
-  int TempFD;
-  if (sys::fs::createUniqueFile(TempPathModel, TempFD, GeneratedUniqPath)) {
-return llvm::make_error(
-atomic_write_error::failed_to_create_uniq_file);
-  }
-  llvm::FileRemover RemoveTmpFile

[PATCH] D153740: [llvm][Support] Deprecate llvm::writeFileAtomically API

2023-07-03 Thread Haojian Wu via Phabricator via cfe-commits
hokein marked an inline comment as done.
hokein added a comment.

Now this patch only contains the removal part of the API (I have cleaned all 
usages of `writeFileAtomically` API, except a remaining one in lldb 
https://reviews.llvm.org/D154329).




Comment at: lldb/tools/lldb-server/lldb-platform.cpp:107
   Status status;
-  if (auto Err =
-  handleErrors(llvm::writeFileAtomically(
-   temp_file_path, file_spec.GetPath(), socket_id),
-   [&status, &file_spec](const AtomicFileWriteError &E) {
- std::string ErrorMsgBuffer;
- llvm::raw_string_ostream S(ErrorMsgBuffer);
- E.log(S);
-
- switch (E.Error) {
- case atomic_write_error::failed_to_create_uniq_file:
-   status = Status("Failed to create temp file: %s",
-   ErrorMsgBuffer.c_str());
-   break;
- case atomic_write_error::output_stream_error:
-   status = Status("Failed to write to port file.");
-   break;
- case atomic_write_error::failed_to_rename_temp_file:
-   status = Status("Failed to rename file %s to %s: 
%s",
-   ErrorMsgBuffer.c_str(),
-   file_spec.GetPath().c_str(),
-   ErrorMsgBuffer.c_str());
-   break;
- }
-   })) {
+  if (auto Err = handleErrors(file_spec.GetPath(),
+  [&socket_id](llvm::raw_ostream &OS) {

avl wrote:
> the call to llvm::writeToOutput is probably missed here.
oops, good catch, the `handleError` should be `writeToOutput`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153740

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


[PATCH] D152996: [RISCV][POC] Model frm control for vfadd

2023-07-03 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
eopXD updated this revision to Diff 536699.
eopXD added a comment.

Fix bug in ManualCodeGen of vfadd.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152996

Files:
  clang/include/clang/Basic/riscv_vector.td
  clang/include/clang/Basic/riscv_vector_common.td
  clang/include/clang/Support/RISCVVIntrinsicUtils.h
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaRISCVVectorLookup.cpp
  clang/lib/Support/RISCVVIntrinsicUtils.cpp
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/overloaded/vfadd.c
  clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/vfadd-out-of-range.c
  clang/utils/TableGen/RISCVVEmitter.cpp
  llvm/include/llvm/IR/IntrinsicsRISCV.td
  llvm/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.h
  llvm/lib/Target/RISCV/RISCVISelDAGToDAG.cpp
  llvm/lib/Target/RISCV/RISCVISelLowering.cpp
  llvm/lib/Target/RISCV/RISCVInsertReadWriteCSR.cpp
  llvm/lib/Target/RISCV/RISCVInstrFormats.td
  llvm/lib/Target/RISCV/RISCVInstrInfoVPseudos.td
  llvm/lib/Target/RISCV/RISCVInstrInfoVSDPatterns.td
  llvm/lib/Target/RISCV/RISCVInstrInfoVVLPatterns.td
  llvm/test/CodeGen/RISCV/rvv/alloca-load-store-scalable-struct.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-fmf.ll
  llvm/test/CodeGen/RISCV/rvv/masked-tama.ll
  llvm/test/CodeGen/RISCV/rvv/masked-tamu.ll
  llvm/test/CodeGen/RISCV/rvv/masked-tuma.ll
  llvm/test/CodeGen/RISCV/rvv/masked-tumu.ll
  llvm/test/CodeGen/RISCV/rvv/rv32-spill-vector-csr.ll
  llvm/test/CodeGen/RISCV/rvv/rv64-spill-vector-csr.ll
  llvm/test/CodeGen/RISCV/rvv/rvv-peephole-vmerge-masked-vops.ll
  llvm/test/CodeGen/RISCV/rvv/unmasked-tu.ll
  llvm/test/CodeGen/RISCV/rvv/vfadd.ll
  llvm/test/CodeGen/RISCV/rvv/vsetvli-insert-crossbb.ll
  llvm/test/CodeGen/RISCV/rvv/vsetvli-insert.ll

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


[PATCH] D153776: [clang][analyzer] Display notes in StdLibraryFunctionsChecker only if interesting

2023-07-03 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy added a comment.

In D153776#4467627 , @balazske wrote:

> The success/failure note tags are not added to all functions, `dup` is one of 
> these, this means at `dup` no note tag is shown. A next patch can be made to 
> add these messages to all functions. The other places look good, but 
> CodeChecker is a bit tricky, you must select 
> //*_stdclf_notetag_interesting_test_2// at the small arrow after the "found 
> in:" text (upper right corner). The link is good but not that instance of the 
> bug is displayed because only the note tags are different.

I think we should definitely add success/failure note tags to all functions 
where this checker can suddenly assume that "Oops, this failed". If this 
"Assuming that 'foo' fails" message is not there, it's a very natural reaction 
to search for some earlier note that would let the checker deduce that this 
function will fail here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153776

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


[PATCH] D152996: [RISCV][POC] Model frm control for vfadd

2023-07-03 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
eopXD updated this revision to Diff 536700.
eopXD added a comment.

Undo the previous diff. There was no bug in the code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152996

Files:
  clang/include/clang/Basic/riscv_vector.td
  clang/include/clang/Basic/riscv_vector_common.td
  clang/include/clang/Support/RISCVVIntrinsicUtils.h
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaRISCVVectorLookup.cpp
  clang/lib/Support/RISCVVIntrinsicUtils.cpp
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/overloaded/vfadd.c
  clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/vfadd-out-of-range.c
  clang/utils/TableGen/RISCVVEmitter.cpp
  llvm/include/llvm/IR/IntrinsicsRISCV.td
  llvm/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.h
  llvm/lib/Target/RISCV/RISCVISelDAGToDAG.cpp
  llvm/lib/Target/RISCV/RISCVISelLowering.cpp
  llvm/lib/Target/RISCV/RISCVInsertReadWriteCSR.cpp
  llvm/lib/Target/RISCV/RISCVInstrFormats.td
  llvm/lib/Target/RISCV/RISCVInstrInfoVPseudos.td
  llvm/lib/Target/RISCV/RISCVInstrInfoVSDPatterns.td
  llvm/lib/Target/RISCV/RISCVInstrInfoVVLPatterns.td
  llvm/test/CodeGen/RISCV/rvv/alloca-load-store-scalable-struct.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-fmf.ll
  llvm/test/CodeGen/RISCV/rvv/masked-tama.ll
  llvm/test/CodeGen/RISCV/rvv/masked-tamu.ll
  llvm/test/CodeGen/RISCV/rvv/masked-tuma.ll
  llvm/test/CodeGen/RISCV/rvv/masked-tumu.ll
  llvm/test/CodeGen/RISCV/rvv/rv32-spill-vector-csr.ll
  llvm/test/CodeGen/RISCV/rvv/rv64-spill-vector-csr.ll
  llvm/test/CodeGen/RISCV/rvv/rvv-peephole-vmerge-masked-vops.ll
  llvm/test/CodeGen/RISCV/rvv/unmasked-tu.ll
  llvm/test/CodeGen/RISCV/rvv/vfadd.ll
  llvm/test/CodeGen/RISCV/rvv/vsetvli-insert-crossbb.ll
  llvm/test/CodeGen/RISCV/rvv/vsetvli-insert.ll

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


[clang] 4a792e0 - [clang] Fix new-expression with elaborated-type-specifier

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

Author: Mariya Podchishchaeva
Date: 2023-07-03T06:07:04-04:00
New Revision: 4a792e06e8e72f4c14e5a5251e71051d7a984820

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

LOG: [clang] Fix new-expression with elaborated-type-specifier

Expressions like
```
struct A {};
...
new struct A {};
struct A* b = (1 == 1) ? new struct A : new struct A;

```
were parsed as redefinitions of `struct A` and failed, however as clarified by
`CWG2141` new-expression cannot define a type, so both these examples
should be considered as references to the previously declared `struct A`.
The patch adds a "new" kind context for parsing declaration specifiers in
addition to already existing declarator context in order to track that
the parser is inside of a new expression.

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

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Parse/Parser.h
clang/lib/Parse/ParseDecl.cpp
clang/lib/Parse/ParseExprCXX.cpp
clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/p3-0x.cpp
clang/test/CXX/drs/dr19xx.cpp
clang/test/CXX/drs/dr21xx.cpp
clang/test/CXX/drs/dr6xx.cpp
clang/test/Parser/cxx11-type-specifier.cpp
clang/www/cxx_dr_status.html

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index bea609cdc08695..94eddd5e3b89c7 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -563,6 +563,8 @@ Bug Fixes in This Version
   (`#60709 `_).
 - Fixed a missed integer overflow warning with temporary values.
   (`#63629 `_)
+- Fixed parsing of elaborated type specifier inside of a new expression.
+  (`#34341 `_)
 
 Bug Fixes to Compiler Builtins
 ^^

diff  --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index c706482aec983f..210fbb183dc07e 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -2217,7 +2217,8 @@ class Parser : public CodeCompletionHandler {
 DSC_objc_method_result, // ObjC method result context, enables
 // 'instancetype'
 DSC_condition,  // condition declaration context
-DSC_association // A _Generic selection expression's type association
+DSC_association, // A _Generic selection expression's type association
+DSC_new, // C++ new expression
   };
 
   /// Is this a context in which we are parsing just a type-specifier (or
@@ -2239,6 +2240,7 @@ class Parser : public CodeCompletionHandler {
 case DeclSpecContext::DSC_trailing:
 case DeclSpecContext::DSC_alias_declaration:
 case DeclSpecContext::DSC_association:
+case DeclSpecContext::DSC_new:
   return true;
 }
 llvm_unreachable("Missing DeclSpecContext case");
@@ -2287,6 +2289,7 @@ class Parser : public CodeCompletionHandler {
 case DeclSpecContext::DSC_trailing:
 case DeclSpecContext::DSC_conv_operator:
 case DeclSpecContext::DSC_template_arg:
+case DeclSpecContext::DSC_new:
   return AllowDefiningTypeSpec::No;
 }
 llvm_unreachable("Missing DeclSpecContext case");
@@ -2310,6 +2313,7 @@ class Parser : public CodeCompletionHandler {
 case DeclSpecContext::DSC_association:
 case DeclSpecContext::DSC_conv_operator:
 case DeclSpecContext::DSC_template_arg:
+case DeclSpecContext::DSC_new:
 
   return false;
 }
@@ -2329,6 +2333,7 @@ class Parser : public CodeCompletionHandler {
 case DeclSpecContext::DSC_type_specifier:
 case DeclSpecContext::DSC_association:
 case DeclSpecContext::DSC_conv_operator:
+case DeclSpecContext::DSC_new:
   return true;
 
 case DeclSpecContext::DSC_objc_method_result:
@@ -2351,6 +2356,7 @@ class Parser : public CodeCompletionHandler {
 case DeclSpecContext::DSC_trailing:
 case DeclSpecContext::DSC_alias_declaration:
 case DeclSpecContext::DSC_template_param:
+case DeclSpecContext::DSC_new:
   return ImplicitTypenameContext::Yes;
 
 case DeclSpecContext::DSC_normal:

diff  --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 32085461ff8b7e..43b2a32cce71ca 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -2981,6 +2981,8 @@ 
Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
 return DeclSpecContext::DSC_condition;
   case DeclaratorContext::ConversionId:
 return DeclSpecContext::DSC_conv_operator;
+  case DeclaratorContext::CXXNew:
+return DeclSpecContext::DSC_new;
   case Declar

[PATCH] D153857: [clang] Fix new-expression with elaborated-type-specifier

2023-07-03 Thread Mariya Podchishchaeva 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 rG4a792e06e8e7: [clang] Fix new-expression with 
elaborated-type-specifier (authored by Fznamznon).

Changed prior to commit:
  https://reviews.llvm.org/D153857?vs=535779&id=536702#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153857

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Parse/Parser.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseExprCXX.cpp
  clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/p3-0x.cpp
  clang/test/CXX/drs/dr19xx.cpp
  clang/test/CXX/drs/dr21xx.cpp
  clang/test/CXX/drs/dr6xx.cpp
  clang/test/Parser/cxx11-type-specifier.cpp
  clang/www/cxx_dr_status.html

Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -12653,7 +12653,7 @@
 https://cplusplus.github.io/CWG/issues/2141.html";>2141
 CD4
 Ambiguity in new-expression with elaborated-type-specifier
-Unknown
+Clang 17
   
   
 https://cplusplus.github.io/CWG/issues/2142.html";>2142
Index: clang/test/Parser/cxx11-type-specifier.cpp
===
--- clang/test/Parser/cxx11-type-specifier.cpp
+++ clang/test/Parser/cxx11-type-specifier.cpp
@@ -13,10 +13,8 @@
   } catch (constexpr int) { // expected-error{{type name does not allow constexpr}}
   }
 
-  // These parse as type definitions, not as type references with braced
-  // initializers. Sad but true...
-  (void) new struct S {}; // expected-error{{'S' cannot be defined in a type specifier}}
-  (void) new enum E { e }; // expected-error{{'E' cannot be defined in a type specifier}}
+  (void) new struct S {};
+  (void) new enum E { e };
 }
 
 // And for trailing-type-specifier-seq
Index: clang/test/CXX/drs/dr6xx.cpp
===
--- clang/test/CXX/drs/dr6xx.cpp
+++ clang/test/CXX/drs/dr6xx.cpp
@@ -1078,9 +1078,10 @@
 (void)const_cast(0); // expected-error {{cannot be defined in a type specifier}}
 (void)sizeof(struct F*);
 (void)sizeof(struct F{}*); // expected-error {{cannot be defined in a type specifier}}
-(void)new struct G*;
-(void)new struct G{}*; // expected-error {{cannot be defined in a type specifier}}
+(void)new struct G*; // expected-note {{forward}}
+(void)new struct G{}*; // expected-error {{incomplete}}
 #if __cplusplus >= 201103L
+// expected-error@-2 {{expected expression}}
 (void)alignof(struct H*);
 (void)alignof(struct H{}*); // expected-error {{cannot be defined in a type specifier}}
 #endif
Index: clang/test/CXX/drs/dr21xx.cpp
===
--- clang/test/CXX/drs/dr21xx.cpp
+++ clang/test/CXX/drs/dr21xx.cpp
@@ -120,6 +120,31 @@
 #endif
 }
 
+namespace dr2141 { // dr2141: 17
+struct A{};
+
+template 
+struct B{};
+
+void foo() {
+  struct A *b = (1 == 1) ? new struct A : new struct A;
+  struct S *a = (1 == 1) ? new struct S : new struct S; // expected-error 2{{allocation of incomplete type}} // expected-note 2{{forward}}
+
+#if __cplusplus >= 201103L
+  A *aa = new struct A{};
+  B *bb = new struct B{};
+  (void)new struct C{}; // expected-error {{allocation of incomplete type }} // expected-note {{forward}}
+
+  struct A *c = (1 == 1) ? new struct A {} : new struct A {};
+
+  alignof(struct D{}); // expected-error {{cannot be defined in a type specifier}}
+#endif
+
+  sizeof(struct E{}); // expected-error {{cannot be defined in a type specifier}}
+
+}
+}
+
 namespace dr2157 { // dr2157: 11
 #if __cplusplus >= 201103L
   enum E : int;
Index: clang/test/CXX/drs/dr19xx.cpp
===
--- clang/test/CXX/drs/dr19xx.cpp
+++ clang/test/CXX/drs/dr19xx.cpp
@@ -194,7 +194,7 @@
 enum E : int {1}; // expected-error {{expected identifier}} (not bit-field)
   };
   auto *p1 = new enum E : int; // expected-error {{only permitted as a standalone declaration}}
-  auto *p2 = new enum F : int {}; // expected-error {{cannot be defined in a type specifier}}
+  auto *p2 = new enum F : int {}; // expected-error {{only permitted as a standalone declaration}}
   auto *p3 = true ? new enum G : int {}; // expected-error {{forward reference}} expected-error {{incomplete}} expected-note {{declaration}}
   auto h() -> enum E : int {}; // expected-error {{only permitted as a standalone declaration}}
 
Index: clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/p3-0x.cpp
===
--- clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/p3-0x.cpp
+++ clang/test/CXX/dcl.dcl/dcl.spec/dcl.type/p3-0x.cpp
@@ -21,8 +21,8 @@
   for (struct S { S(int) {} } s : Undeclared); // expected-error{{types may not be defined in a 

[clang] 899c867 - [clang-format] Fixed bad performance with enabled qualifier fixer.

2023-07-03 Thread via cfe-commits

Author: Sedenion
Date: 2023-07-03T11:54:33+01:00
New Revision: 899c86779440dca84085fb53a1fbba6c5aa5a3b6

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

LOG: [clang-format] Fixed bad performance with enabled qualifier fixer.

This fixes github issue #57117: If the "QualifierAlignment"
option of clang-format is set to anything else but "Leave", the
"QualifierAlignmentFixer" pass gets enabled. This pass scales
quadratically with the number of preprocessor branches, i.e.
with the number of elements in TokenAnalyzer::UnwrappedLines.
The reason is that QualifierAlignmentFixer::process() generates
the UnwrappedLines, but then QualifierAlignmentFixer::analyze()
calls LeftRightQualifierAlignmentFixer::process() several times
(once for each qualifier) which again each time generates the
UnwrappedLines.

This commit gets rid of this double loop by registering the
individual LeftRightQualifierAlignmentFixer passes directly in
the top most container of passes (local variable "Passes" in
reformat()).
With this change, the original example in the github issue #57117
now takes only around 3s instead of >300s to format.

Since QualifierAlignmentFixer::analyze() got deleted, we also
no longer have the code with the NonNoOpFixes. This causes
replacements that end up not changing anything to appear in the
list of final replacements. There is a unit test to check that
this does not happen: QualifierFixerTest.NoOpQualifierReplacements.
However, it got broken at some point in time. So this commit
fixes the test. To keep the behavior that no no-op replacements
should appear from the qualifier fixer, the corresponding code
from QualifierAlignmentFixer::analyze() was moved to the top
reformat() function. Thus, is now done for **every** replacement
of every formatting pass. If no-op replacements are a problem
for the qualifier fixer, then it seems to be a good idea to
filter them out always.

See
https://github.com/llvm/llvm-project/issues/57117#issuecomment-1546716934
for some more details.

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 5fee5e6c261a93..fd46dfec21d8de 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3472,21 +3472,16 @@ reformat(const FormatStyle &Style, StringRef Code,
   typedef std::function(
   const Environment &)>
   AnalyzerPass;
-  SmallVector Passes;
+
+  SmallVector Passes;
 
   Passes.emplace_back([&](const Environment &Env) {
 return IntegerLiteralSeparatorFixer().process(Env, Expanded);
   });
 
   if (Style.isCpp()) {
-if (Style.QualifierAlignment != FormatStyle::QAS_Leave) {
-  Passes.emplace_back([&](const Environment &Env) {
-return QualifierAlignmentFixer(Env, Expanded, Code, Ranges,
-   FirstStartColumn, NextStartColumn,
-   LastStartColumn, FileName)
-.process();
-  });
-}
+if (Style.QualifierAlignment != FormatStyle::QAS_Leave)
+  addQualifierAlignmentFixerPasses(Expanded, Passes);
 
 if (Style.InsertBraces) {
   FormatStyle S = Expanded;
@@ -3571,6 +3566,24 @@ reformat(const FormatStyle &Style, StringRef Code,
 }
   }
 
+  if (Style.QualifierAlignment != FormatStyle::QAS_Leave) {
+// Don't make replacements that replace nothing. QualifierAlignment can
+// produce them if one of its early passes changes e.g. `const volatile` to
+// `volatile const` and then a later pass changes it back again.
+tooling::Replacements NonNoOpFixes;
+for (const tooling::Replacement &Fix : Fixes) {
+  StringRef OriginalCode = Code.substr(Fix.getOffset(), Fix.getLength());
+  if (!OriginalCode.equals(Fix.getReplacementText())) {
+auto Err = NonNoOpFixes.add(Fix);
+if (Err) {
+  llvm::errs() << "Error adding replacements : "
+   << llvm::toString(std::move(Err)) << "\n";
+}
+  }
+}
+Fixes = std::move(NonNoOpFixes);
+  }
+
   return {Fixes, Penalty};
 }
 } // namespace internal

diff  --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index ff54fb75b3dd98..2e3b21cfda79eb 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -25,18 +25,13 @@
 namespace clang {
 namespace format {
 
-QualifierAlignmentFixer::QualifierAlignmentFixer(
-const Environment &Env, const FormatStyle 

[PATCH] D153228: [clang-format] Fixed bad performance with enabled qualifier fixer.

2023-07-03 Thread MyDeveloperDay via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG899c86779440: [clang-format] Fixed bad performance with 
enabled qualifier fixer. (authored by Sedeniono, committed by MyDeveloperDay).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153228

Files:
  clang/lib/Format/Format.cpp
  clang/lib/Format/QualifierAlignmentFixer.cpp
  clang/lib/Format/QualifierAlignmentFixer.h
  clang/unittests/Format/QualifierFixerTest.cpp

Index: clang/unittests/Format/QualifierFixerTest.cpp
===
--- clang/unittests/Format/QualifierFixerTest.cpp
+++ clang/unittests/Format/QualifierFixerTest.cpp
@@ -1016,8 +1016,8 @@
   std::vector Left;
   std::vector Right;
   std::vector ConfiguredTokens;
-  QualifierAlignmentFixer::PrepareLeftRightOrdering(Style.QualifierOrder, Left,
-Right, ConfiguredTokens);
+  prepareLeftRightOrderingForQualifierAlignmentFixer(Style.QualifierOrder, Left,
+ Right, ConfiguredTokens);
 
   EXPECT_EQ(Left.size(), (size_t)2);
   EXPECT_EQ(Right.size(), (size_t)2);
@@ -1181,10 +1181,12 @@
   Style.QualifierAlignment = FormatStyle::QAS_Custom;
   Style.QualifierOrder = {"static", "const", "type"};
 
-  ReplacementCount = 0;
-  EXPECT_EQ(ReplacementCount, 0);
   verifyFormat("static const uint32 foo[] = {0, 31};", Style);
+  EXPECT_EQ(ReplacementCount, 0);
+
   verifyFormat("#define MACRO static const", Style);
+  EXPECT_EQ(ReplacementCount, 0);
+
   verifyFormat("using sc = static const", Style);
   EXPECT_EQ(ReplacementCount, 0);
 }
Index: clang/lib/Format/QualifierAlignmentFixer.h
===
--- clang/lib/Format/QualifierAlignmentFixer.h
+++ clang/lib/Format/QualifierAlignmentFixer.h
@@ -25,32 +25,13 @@
 const Environment &)>
 AnalyzerPass;
 
-class QualifierAlignmentFixer : public TokenAnalyzer {
-  // Left to Right ordering requires multiple passes
-  SmallVector Passes;
-  StringRef &Code;
-  ArrayRef Ranges;
-  unsigned FirstStartColumn;
-  unsigned NextStartColumn;
-  unsigned LastStartColumn;
-  StringRef FileName;
+void addQualifierAlignmentFixerPasses(const FormatStyle &Style,
+  SmallVectorImpl &Passes);
 
-public:
-  QualifierAlignmentFixer(const Environment &Env, const FormatStyle &Style,
-  StringRef &Code, ArrayRef Ranges,
-  unsigned FirstStartColumn, unsigned NextStartColumn,
-  unsigned LastStartColumn, StringRef FileName);
-
-  std::pair
-  analyze(TokenAnnotator &Annotator,
-  SmallVectorImpl &AnnotatedLines,
-  FormatTokenLexer &Tokens) override;
-
-  static void PrepareLeftRightOrdering(const std::vector &Order,
-   std::vector &LeftOrder,
-   std::vector &RightOrder,
-   std::vector &Qualifiers);
-};
+void prepareLeftRightOrderingForQualifierAlignmentFixer(
+const std::vector &Order, std::vector &LeftOrder,
+std::vector &RightOrder,
+std::vector &Qualifiers);
 
 class LeftRightQualifierAlignmentFixer : public TokenAnalyzer {
   std::string Qualifier;
Index: clang/lib/Format/QualifierAlignmentFixer.cpp
===
--- clang/lib/Format/QualifierAlignmentFixer.cpp
+++ clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -25,18 +25,13 @@
 namespace clang {
 namespace format {
 
-QualifierAlignmentFixer::QualifierAlignmentFixer(
-const Environment &Env, const FormatStyle &Style, StringRef &Code,
-ArrayRef Ranges, unsigned FirstStartColumn,
-unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName)
-: TokenAnalyzer(Env, Style), Code(Code), Ranges(Ranges),
-  FirstStartColumn(FirstStartColumn), NextStartColumn(NextStartColumn),
-  LastStartColumn(LastStartColumn), FileName(FileName) {
+void addQualifierAlignmentFixerPasses(const FormatStyle &Style,
+  SmallVectorImpl &Passes) {
   std::vector LeftOrder;
   std::vector RightOrder;
   std::vector ConfiguredQualifierTokens;
-  PrepareLeftRightOrdering(Style.QualifierOrder, LeftOrder, RightOrder,
-   ConfiguredQualifierTokens);
+  prepareLeftRightOrderingForQualifierAlignmentFixer(
+  Style.QualifierOrder, LeftOrder, RightOrder, ConfiguredQualifierTokens);
 
   // Handle the left and right alignment separately.
   for (const auto &Qualifier : LeftOrder) {
@@ -59,51 +54,6 @@
   }
 }
 
-std::pair QualifierAlignmentFixer::analyze(
-TokenAnnotator & /*Annotator*/,
-SmallVectorImpl & /*AnnotatedLines*/,
-FormatTokenLexer & /*Tokens*/) {
-  auto Env = Environment::make(Code, FileName, Ranges, FirstStartC

[PATCH] D154334: [clang] Add `__has_extension ()` for C++11 features

2023-07-03 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon created this revision.
Herald added a project: All.
Fznamznon requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Add `__has_extension (cxx_defaulted_functions)` and
`__has_extension (cxx_defaulted_functions)` since they are accepted in
C++98 mode as extensions.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154334

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Features.def
  clang/test/Lexer/has_extension_cxx.cpp


Index: clang/test/Lexer/has_extension_cxx.cpp
===
--- clang/test/Lexer/has_extension_cxx.cpp
+++ clang/test/Lexer/has_extension_cxx.cpp
@@ -11,6 +11,16 @@
 int c_generic_selections();
 #endif
 
+// CHECK: has_deleted_functions
+#if __has_extension(cxx_default_function_template_args)
+int has_deleted_functions();
+#endif
+
+// CHECK: has_deleted_functions
+#if __has_extension(cxx_defaulted_functions)
+int has_deleted_functions();
+#endif
+
 // CHECK: has_deleted_functions
 #if __has_extension(cxx_deleted_functions)
 int has_deleted_functions();
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -247,6 +247,8 @@
 EXTENSION(c_thread_local, PP.getTargetInfo().isTLSSupported())
 // C++11 features supported by other languages as extensions.
 EXTENSION(cxx_atomic, LangOpts.CPlusPlus)
+EXTENSION(cxx_default_function_template_args, LangOpts.CPlusPlus)
+EXTENSION(cxx_defaulted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_deleted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_explicit_conversions, LangOpts.CPlusPlus)
 EXTENSION(cxx_inline_namespaces, LangOpts.CPlusPlus)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -565,6 +565,9 @@
   (`#63629 `_)
 - Fixed parsing of elaborated type specifier inside of a new expression.
   (`#34341 `_)
+- Clang now correctly evaluates ``__has_extension (cxx_defaulted_functions)``
+  and ``__has_extension (cxx_default_function_template_args)`` to 1.
+  (`#61758 `_)
 
 Bug Fixes to Compiler Builtins
 ^^


Index: clang/test/Lexer/has_extension_cxx.cpp
===
--- clang/test/Lexer/has_extension_cxx.cpp
+++ clang/test/Lexer/has_extension_cxx.cpp
@@ -11,6 +11,16 @@
 int c_generic_selections();
 #endif
 
+// CHECK: has_deleted_functions
+#if __has_extension(cxx_default_function_template_args)
+int has_deleted_functions();
+#endif
+
+// CHECK: has_deleted_functions
+#if __has_extension(cxx_defaulted_functions)
+int has_deleted_functions();
+#endif
+
 // CHECK: has_deleted_functions
 #if __has_extension(cxx_deleted_functions)
 int has_deleted_functions();
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -247,6 +247,8 @@
 EXTENSION(c_thread_local, PP.getTargetInfo().isTLSSupported())
 // C++11 features supported by other languages as extensions.
 EXTENSION(cxx_atomic, LangOpts.CPlusPlus)
+EXTENSION(cxx_default_function_template_args, LangOpts.CPlusPlus)
+EXTENSION(cxx_defaulted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_deleted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_explicit_conversions, LangOpts.CPlusPlus)
 EXTENSION(cxx_inline_namespaces, LangOpts.CPlusPlus)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -565,6 +565,9 @@
   (`#63629 `_)
 - Fixed parsing of elaborated type specifier inside of a new expression.
   (`#34341 `_)
+- Clang now correctly evaluates ``__has_extension (cxx_defaulted_functions)``
+  and ``__has_extension (cxx_default_function_template_args)`` to 1.
+  (`#61758 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D154334: [clang] Add `__has_extension ()` for C++11 features

2023-07-03 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon updated this revision to Diff 536715.
Fznamznon added a comment.

Fix test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154334

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Features.def
  clang/test/Lexer/has_extension_cxx.cpp


Index: clang/test/Lexer/has_extension_cxx.cpp
===
--- clang/test/Lexer/has_extension_cxx.cpp
+++ clang/test/Lexer/has_extension_cxx.cpp
@@ -11,6 +11,16 @@
 int c_generic_selections();
 #endif
 
+// CHECK: has_default_function_template_args
+#if __has_extension(cxx_default_function_template_args)
+int has_default_function_template_args();
+#endif
+
+// CHECK: has_defaulted_functions
+#if __has_extension(cxx_defaulted_functions)
+int has_defaulted_functions();
+#endif
+
 // CHECK: has_deleted_functions
 #if __has_extension(cxx_deleted_functions)
 int has_deleted_functions();
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -247,6 +247,8 @@
 EXTENSION(c_thread_local, PP.getTargetInfo().isTLSSupported())
 // C++11 features supported by other languages as extensions.
 EXTENSION(cxx_atomic, LangOpts.CPlusPlus)
+EXTENSION(cxx_default_function_template_args, LangOpts.CPlusPlus)
+EXTENSION(cxx_defaulted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_deleted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_explicit_conversions, LangOpts.CPlusPlus)
 EXTENSION(cxx_inline_namespaces, LangOpts.CPlusPlus)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -565,6 +565,9 @@
   (`#63629 `_)
 - Fixed parsing of elaborated type specifier inside of a new expression.
   (`#34341 `_)
+- Clang now correctly evaluates ``__has_extension (cxx_defaulted_functions)``
+  and ``__has_extension (cxx_default_function_template_args)`` to 1.
+  (`#61758 `_)
 
 Bug Fixes to Compiler Builtins
 ^^


Index: clang/test/Lexer/has_extension_cxx.cpp
===
--- clang/test/Lexer/has_extension_cxx.cpp
+++ clang/test/Lexer/has_extension_cxx.cpp
@@ -11,6 +11,16 @@
 int c_generic_selections();
 #endif
 
+// CHECK: has_default_function_template_args
+#if __has_extension(cxx_default_function_template_args)
+int has_default_function_template_args();
+#endif
+
+// CHECK: has_defaulted_functions
+#if __has_extension(cxx_defaulted_functions)
+int has_defaulted_functions();
+#endif
+
 // CHECK: has_deleted_functions
 #if __has_extension(cxx_deleted_functions)
 int has_deleted_functions();
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -247,6 +247,8 @@
 EXTENSION(c_thread_local, PP.getTargetInfo().isTLSSupported())
 // C++11 features supported by other languages as extensions.
 EXTENSION(cxx_atomic, LangOpts.CPlusPlus)
+EXTENSION(cxx_default_function_template_args, LangOpts.CPlusPlus)
+EXTENSION(cxx_defaulted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_deleted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_explicit_conversions, LangOpts.CPlusPlus)
 EXTENSION(cxx_inline_namespaces, LangOpts.CPlusPlus)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -565,6 +565,9 @@
   (`#63629 `_)
 - Fixed parsing of elaborated type specifier inside of a new expression.
   (`#34341 `_)
+- Clang now correctly evaluates ``__has_extension (cxx_defaulted_functions)``
+  and ``__has_extension (cxx_default_function_template_args)`` to 1.
+  (`#61758 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D154335: [clang][tooling] Fix early termination when there are nested expansions

2023-07-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: sammccall.
Herald added a subscriber: arphaman.
Herald added a project: All.
kadircet requested review of this revision.
Herald added projects: clang, clang-tools-extra.
Herald added a subscriber: cfe-commits.

This also does some cleanups, I am happy to undo them (or send as
separate patches):

- Change the early exit to stop only once we hit an expansion inside the main 
file, to make sure we keep following the nested expansions.
- Add more tests to cover all the cases mentioned in the implementation
- Drop the adjustments for prev/next tokens. We do the final checks based on 
the expansion locations anyway, so any intermediate mapping was a no-op.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154335

Files:
  clang-tools-extra/clangd/unittests/tweaks/AddUsingTests.cpp
  clang/lib/Tooling/Syntax/Tokens.cpp
  clang/unittests/Tooling/Syntax/TokensTest.cpp

Index: clang/unittests/Tooling/Syntax/TokensTest.cpp
===
--- clang/unittests/Tooling/Syntax/TokensTest.cpp
+++ clang/unittests/Tooling/Syntax/TokensTest.cpp
@@ -769,12 +769,15 @@
   // Critical cases for mapping of Prev/Next in spelledForExpandedSlow.
   recordTokens(R"cpp(
 #define ID(X) X
-ID(prev ID(good))
+ID(prev good)
+ID(prev ID(good2))
 #define LARGE ID(prev ID(bad))
 LARGE
   )cpp");
   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
   ValueIs(SameRange(findSpelled("good";
+  EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good2")),
+  ValueIs(SameRange(findSpelled("good2";
   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("bad")), std::nullopt);
 
   recordTokens(R"cpp(
@@ -785,19 +788,32 @@
 LARGE
   )cpp");
   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
-ValueIs(SameRange(findSpelled("good";
+  ValueIs(SameRange(findSpelled("good";
   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("bad")), std::nullopt);
 
   recordTokens(R"cpp(
 #define ID(X) X
 #define ID2(X, Y) X Y
-ID2(prev, ID(good))
+ID2(prev, good)
+ID2(prev, ID(good2))
 #define LARGE ID2(prev, bad)
 LARGE
   )cpp");
   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
-ValueIs(SameRange(findSpelled("good";
+  ValueIs(SameRange(findSpelled("good";
+  EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good2")),
+  ValueIs(SameRange(findSpelled("good2";
   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("bad")), std::nullopt);
+
+  // Prev from macro body.
+  recordTokens(R"cpp(
+#define ID(X) X
+#define ID2(X, Y) X prev ID(Y)
+ID2(not_prev, good)
+  )cpp");
+  EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
+  ValueIs(SameRange(findSpelled("good";
+  EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("prev good")), std::nullopt);
 }
 
 TEST_F(TokenBufferTest, ExpandedTokensForRange) {
Index: clang/lib/Tooling/Syntax/Tokens.cpp
===
--- clang/lib/Tooling/Syntax/Tokens.cpp
+++ clang/lib/Tooling/Syntax/Tokens.cpp
@@ -103,66 +103,13 @@
 // The token `a` is wrapped in 4 arg-expansions, we only want to unwrap 2.
 // We distinguish them by whether the macro expands into the target file.
 // Fortunately, the target file ones will always appear first.
-auto &ExpMacro =
-SM.getSLocEntry(SM.getFileID(ExpFirst.getExpansionLocStart()))
-.getExpansion();
-if (ExpMacro.getExpansionLocStart().isMacroID())
+auto ExpFileID = SM.getFileID(ExpFirst.getExpansionLocStart());
+if (ExpFileID == TargetFile)
   break;
 // Replace each endpoint with its spelling inside the macro arg.
 // (This is getImmediateSpellingLoc without repeating lookups).
 First = ExpFirst.getSpellingLoc().getLocWithOffset(DecFirst.second);
 Last = ExpLast.getSpellingLoc().getLocWithOffset(DecLast.second);
-
-// Now: how do we adjust the previous/next bounds? Three cases:
-// A) If they are also part of the same macro arg, we translate them too.
-//   This will ensure that we don't select any macros nested within the
-//   macro arg that cover extra tokens. Critical case:
-//  #define ID(X) X
-//  ID(prev target) // selecting 'target' succeeds
-//  #define LARGE ID(prev target)
-//  LARGE // selecting 'target' fails.
-// B) They are not in the macro at all, then their expansion range is a
-//sibling to it, and we can safely substitute that.
-//  #define PREV prev
-//  #define ID(X) X
-//  PREV ID(target) // selecting 'target' succeeds.
-//  #define LARGE PREV ID(target)
-//  LARGE // selecting 'target' fails.
-// C) They are in a different arg of this macro, or the macro body.
-//Now selecting the whole 

[clang] 8e9145e - [clang][ExtractAPI] Add --emit-symbol-graph option

2023-07-03 Thread via cfe-commits

Author: Ankur
Date: 2023-07-03T17:32:30+05:30
New Revision: 8e9145e4314202b960dd883e6a7b21707ed5c176

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

LOG: [clang][ExtractAPI] Add --emit-symbol-graph option

Add new --emit-symbol-graph= option which generates ExtractAPI symbol
graph information of .c/.m files on regular compilation job and put them in
the provided "DIR" directory.

Reviewed By: dang

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

Added: 
clang/include/clang/ExtractAPI/ExtractAPIActionBase.h
clang/test/ExtractAPI/emit-symbol-graph/multi_file.c
clang/test/ExtractAPI/emit-symbol-graph/single_file.c

Modified: 
clang/include/clang/Driver/Options.td
clang/include/clang/ExtractAPI/FrontendActions.h
clang/include/clang/Frontend/FrontendOptions.h
clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c3242ac2a804b8..f74a589d1baaa6 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1198,6 +1198,9 @@ def extract_api : Flag<["-"], "extract-api">, 
Flags<[CC1Option]>, Group;
 def product_name_EQ: Joined<["--"], "product-name=">, Flags<[CC1Option]>,
   MarshallingInfoString>;
+def emit_symbol_graph_EQ: JoinedOrSeparate<["--"], "emit-symbol-graph=">, 
Flags<[CC1Option]>,
+HelpText<"Generate Extract API information as a side effect of 
compilation.">,
+MarshallingInfoString>;
 def extract_api_ignores_EQ: CommaJoined<["--"], "extract-api-ignores=">, 
Flags<[CC1Option]>,
 HelpText<"Comma separated list of files containing a new line separated 
list of API symbols to ignore when extracting API information.">,
 MarshallingInfoStringVector>;

diff  --git a/clang/include/clang/ExtractAPI/ExtractAPIActionBase.h 
b/clang/include/clang/ExtractAPI/ExtractAPIActionBase.h
new file mode 100644
index 00..ac4f391db5f14a
--- /dev/null
+++ b/clang/include/clang/ExtractAPI/ExtractAPIActionBase.h
@@ -0,0 +1,54 @@
+//===- ExtractAPI/ExtractAPIActionBase.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 file defines the ExtractAPIActionBase class.
+///
+//===--===//
+
+#ifndef LLVM_CLANG_EXTRACTAPI_ACTION_BASE_H
+#define LLVM_CLANG_EXTRACTAPI_ACTION_BASE_H
+
+#include "clang/ExtractAPI/API.h"
+#include "clang/ExtractAPI/APIIgnoresList.h"
+
+namespace clang {
+
+/// Base class to be used by front end actions to generate ExtarctAPI info
+///
+/// Deriving from this class equips an action with all the necessary tools to
+/// generate ExractAPI information in form of symbol-graphs
+class ExtractAPIActionBase {
+protected:
+  /// A representation of the APIs this action extracts.
+  std::unique_ptr API;
+
+  /// A stream to the output file of this action.
+  std::unique_ptr OS;
+
+  /// The product this action is extracting API information for.
+  std::string ProductName;
+
+  /// The synthesized input buffer that contains all the provided input header
+  /// files.
+  std::unique_ptr Buffer;
+
+  /// The list of symbols to ignore during serialization
+  extractapi::APIIgnoresList IgnoresList;
+
+  /// Implements EndSourceFileAction for Symbol-Graph generation
+  ///
+  /// Use the serializer to generate output symbol graph files from
+  /// the information gathered during the execution of Action.
+  void ImplEndSourceFileAction();
+};
+
+} // namespace clang
+
+#endif // LLVM_CLANG_EXTRACTAPI_ACTION_BASE_H

diff  --git a/clang/include/clang/ExtractAPI/FrontendActions.h 
b/clang/include/clang/ExtractAPI/FrontendActions.h
index e946b33abbd984..c67864aac9af9c 100644
--- a/clang/include/clang/ExtractAPI/FrontendActions.h
+++ b/clang/include/clang/ExtractAPI/FrontendActions.h
@@ -7,41 +7,27 @@
 
//===--===//
 ///
 /// \file
-/// This file defines the ExtractAPIAction frontend action.
+/// This file defines the ExtractAPIAction and WrappingExtractAPIAction 
frontend
+/// actions.
 ///
 
//===--===//
 
 #ifndef LLVM_CLANG_EXTRACTAPI_FRONTEND_ACTIONS_H
 #define LLVM_CLANG_EXTRACTAPI_FRONTEND_ACTIONS_H
 
-#include "clang/ExtractAPI/API.h"
-#include "clang/ExtractAPI/APIIgnoresList.h"
+#include "clang/ExtractAPI/ExtractAPIActionBase.h

[PATCH] D152356: [clang][ExtractAPI] Add --emit-symbol-graph option

2023-07-03 Thread Ankur Saini 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 rG8e9145e43142: [clang][ExtractAPI] Add --emit-symbol-graph 
option (authored by Arsenic).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152356

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/ExtractAPI/ExtractAPIActionBase.h
  clang/include/clang/ExtractAPI/FrontendActions.h
  clang/include/clang/Frontend/FrontendOptions.h
  clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
  clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  clang/test/ExtractAPI/emit-symbol-graph/multi_file.c
  clang/test/ExtractAPI/emit-symbol-graph/single_file.c

Index: clang/test/ExtractAPI/emit-symbol-graph/single_file.c
===
--- /dev/null
+++ clang/test/ExtractAPI/emit-symbol-graph/single_file.c
@@ -0,0 +1,213 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: split-file %s %t
+// RUN: sed -e "s@INPUT_DIR@%{/t:regex_replacement}@g" \
+// RUN: %t/reference.output.json.in >> %t/reference.output.json
+// RUN: %clang_cc1 %t/main.c --emit-symbol-graph=%t/SymbolGraphs --product-name=basicfile -triple=x86_64-apple-macosx12.0.0
+
+// Generator version is not consistent across test runs, normalize it.
+// RUN: sed -e "s@\"generator\": \".*\"@\"generator\": \"?\"@g" \
+// RUN: %t/SymbolGraphs/main.json >> %t/output-normalized.json
+// RUN: diff %t/reference.output.json %t/output-normalized.json
+
+// CHECK-NOT: error:
+// CHECK-NOT: warning:
+
+//--- main.c
+#define TESTMACRO1 2
+#define TESTMARCRO2 5
+
+int main ()
+{
+  return 0;
+}
+
+
+//--- reference.output.json.in
+{
+  "metadata": {
+"formatVersion": {
+  "major": 0,
+  "minor": 5,
+  "patch": 3
+},
+"generator": "?"
+  },
+  "module": {
+"name": "basicfile",
+"platform": {
+  "architecture": "x86_64",
+  "operatingSystem": {
+"name": "macosx"
+  },
+  "vendor": "apple"
+}
+  },
+  "relationships": [],
+  "symbols": [
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:I",
+  "spelling": "int"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "main"
+},
+{
+  "kind": "text",
+  "spelling": "();"
+}
+  ],
+  "functionSignature": {
+"returns": [
+  {
+"kind": "typeIdentifier",
+"preciseIdentifier": "c:I",
+"spelling": "int"
+  }
+]
+  },
+  "identifier": {
+"interfaceLanguage": "c",
+"precise": "c:@F@main"
+  },
+  "kind": {
+"displayName": "Function",
+"identifier": "c.func"
+  },
+  "location": {
+"position": {
+  "character": 5,
+  "line": 4
+},
+"uri": "file://INPUT_DIR/main.c"
+  },
+  "names": {
+"navigator": [
+  {
+"kind": "identifier",
+"spelling": "main"
+  }
+],
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "main"
+  }
+],
+"title": "main"
+  },
+  "pathComponents": [
+"main"
+  ]
+},
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "keyword",
+  "spelling": "#define"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "TESTMACRO1"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "c",
+"precise": "c:main.c@8@macro@TESTMACRO1"
+  },
+  "kind": {
+"displayName": "Macro",
+"identifier": "c.macro"
+  },
+  "location": {
+"position": {
+  "character": 9,
+  "line": 1
+},
+"uri": "file://INPUT_DIR/main.c"
+  },
+  "names": {
+"navigator": [
+  {
+"kind": "identifier",
+"spelling": "TESTMACRO1"
+  }
+],
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "TESTMACRO1"
+  }
+],
+"title": "TESTMACRO1"
+  },
+  "pathComponents": [
+"TESTMACRO1"
+  ]
+},
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "keyword",
+  "spelling": "#define"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "TESTMARCRO2"
+}
+  ],
+  "identifier": {
+"i

[PATCH] D154334: [clang] Add `__has_extension ()` for C++11 features

2023-07-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

Thank you for this! LGTM. but can you also be sure to update this table: 
https://github.com/llvm/llvm-project/blob/main/clang/docs/LanguageExtensions.rst?plain=1#L1429


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154334

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


[PATCH] D154180: [OPENMP52] Codegen support for doacross clause.

2023-07-03 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/CodeGen/CGOpenMPRuntime.cpp:11405-11406
+  llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
+  const OMPDependClause *DepC = dyn_cast(C);
+  const OMPDoacrossClause *DoC = dyn_cast(C);
+  if ((DoC && DoC->getDependenceType() == OMPC_DOACROSS_source) ||

1. const auto *
2. Can you try torework it to make it more C++-ish? Use template deduction to 
avoid runtime dyn_casts.
e.g. something like:
```
namespace {
template 
class OMPDoacrossKind {
public:
bool isSink(const T *) {return false;}
}
}
template <>
class OMPDoacrossKInd {
public:
bool isSink(const OMPDependClause* C) {return C->getDependenceType();}
}
...
```
and use `if (OMPDoacrossKInd::isSink(C)) RTLFn = ...` and same for `Source`



Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:5859-5868
+  const auto DOC = dyn_cast(C);
+  const auto DC = dyn_cast(C);
+  bool IsDependSource = false;
+  if ((DC && DC->getDependencyKind() == OMPC_DEPEND_source) ||
+  (DOC && DOC->getDependenceType() == OMPC_DOACROSS_source))
+IsDependSource = true;
+  CGF.Builder.restoreIP(

Same, use template-based analysis instead of runtime-based.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154180

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


[PATCH] D153883: [Clang][OpenMP] Delay emission of __kmpc_alloc_shared for escaped VLAs

2023-07-03 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/CodeGen/CGDecl.cpp:1606
+  CGOpenMPRuntimeGPU &RT =
+  *(static_cast(&CGM.getOpenMPRuntime()));
+  if (RT.isDelayedVariableLengthDecl(*this, &D)) {

1. use `static_cast(CGM.getOpenMPRuntime())`
2. It will crash if your device is not GPU. Better to make `getKmpcAllocShared` 
and `getKmpcFreeShared` virtual (just like `isDelayedVariableLengthDecl`) in 
base CGOpenMPRuntime, since it may be required not only for GPU-based devices.



Comment at: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp:261
+  else
+DelayedVariableLengthDecls.insert(VD);
+} else

Yep, this is what I meant. The only question: do you really need this new 
parameter? CGF.CapturedStmtInfo provides the list of captures and you can try 
to use it.



Comment at: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp:1100-1104
+// Check if the size of the VLA is available at this point i.e. check that
+// it has been emitted already. If not available then skip it and use
+// delayed emission of __kmpc_alloc_shared.
+if (llvm::is_contained(I->getSecond().DelayedVariableLengthDecls, VD))
+  continue;

Do you still need this check?


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

https://reviews.llvm.org/D153883

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


[PATCH] D154329: [lldb] Replace llvm::writeFileAtomically with llvm::writeToOutput API.

2023-07-03 Thread Alexey Lapshin via Phabricator via cfe-commits
avl added inline comments.



Comment at: lldb/tools/lldb-server/lldb-platform.cpp:112
 return Status("Failed to atomically write file %s",
   file_spec.GetPath().c_str());
   return status;

probably, it would be better to add error text here?

```
return Status("Failed to atomically write file %s: %s",
  file_spec.GetPath().c_str(), 
toString(std::move(Err)).c_str());
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154329

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


[PATCH] D154329: [lldb] Replace llvm::writeFileAtomically with llvm::writeToOutput API.

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

address a comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154329

Files:
  lldb/tools/lldb-server/lldb-platform.cpp


Index: lldb/tools/lldb-server/lldb-platform.cpp
===
--- lldb/tools/lldb-server/lldb-platform.cpp
+++ lldb/tools/lldb-server/lldb-platform.cpp
@@ -22,7 +22,6 @@
 #include 
 
 #include "llvm/Support/FileSystem.h"
-#include "llvm/Support/FileUtilities.h"
 #include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -103,38 +102,15 @@
 return Status("Failed to create directory %s: %s",
   temp_file_spec.GetPath().c_str(), error.AsCString());
 
-  llvm::SmallString<64> temp_file_path;
-  temp_file_spec.AppendPathComponent("port-file.%%");
-  temp_file_path = temp_file_spec.GetPath();
-
   Status status;
-  if (auto Err =
-  handleErrors(llvm::writeFileAtomically(
-   temp_file_path, file_spec.GetPath(), socket_id),
-   [&status, &file_spec](const AtomicFileWriteError &E) {
- std::string ErrorMsgBuffer;
- llvm::raw_string_ostream S(ErrorMsgBuffer);
- E.log(S);
-
- switch (E.Error) {
- case atomic_write_error::failed_to_create_uniq_file:
-   status = Status("Failed to create temp file: %s",
-   ErrorMsgBuffer.c_str());
-   break;
- case atomic_write_error::output_stream_error:
-   status = Status("Failed to write to port file.");
-   break;
- case atomic_write_error::failed_to_rename_temp_file:
-   status = Status("Failed to rename file %s to %s: 
%s",
-   ErrorMsgBuffer.c_str(),
-   file_spec.GetPath().c_str(),
-   ErrorMsgBuffer.c_str());
-   break;
- }
-   })) {
-return Status("Failed to atomically write file %s",
-  file_spec.GetPath().c_str());
-  }
+  if (auto Err = llvm::writeToOutput(file_spec.GetPath(),
+ [&socket_id](llvm::raw_ostream &OS) {
+   OS << socket_id;
+   return llvm::Error::success();
+ }))
+return Status("Failed to atomically write file %s: %s",
+  file_spec.GetPath().c_str(),
+  llvm::toString(std::move(Err)).c_str());
   return status;
 }
 


Index: lldb/tools/lldb-server/lldb-platform.cpp
===
--- lldb/tools/lldb-server/lldb-platform.cpp
+++ lldb/tools/lldb-server/lldb-platform.cpp
@@ -22,7 +22,6 @@
 #include 
 
 #include "llvm/Support/FileSystem.h"
-#include "llvm/Support/FileUtilities.h"
 #include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -103,38 +102,15 @@
 return Status("Failed to create directory %s: %s",
   temp_file_spec.GetPath().c_str(), error.AsCString());
 
-  llvm::SmallString<64> temp_file_path;
-  temp_file_spec.AppendPathComponent("port-file.%%");
-  temp_file_path = temp_file_spec.GetPath();
-
   Status status;
-  if (auto Err =
-  handleErrors(llvm::writeFileAtomically(
-   temp_file_path, file_spec.GetPath(), socket_id),
-   [&status, &file_spec](const AtomicFileWriteError &E) {
- std::string ErrorMsgBuffer;
- llvm::raw_string_ostream S(ErrorMsgBuffer);
- E.log(S);
-
- switch (E.Error) {
- case atomic_write_error::failed_to_create_uniq_file:
-   status = Status("Failed to create temp file: %s",
-   ErrorMsgBuffer.c_str());
-   break;
- case atomic_write_error::output_stream_error:
-   status = Status("Failed to write to port file.");
-   break;
- case atomic_write_error::failed_to_rename_temp_file:
-   status = Status("Failed to rename file %s to %s: %s",
-   ErrorMsgBuffer.c_str(),
-   file_spec.GetPath().c_str(),
-   ErrorMsgBuffer.c_str());
-   break;
-   

[PATCH] D154329: [lldb] Replace llvm::writeFileAtomically with llvm::writeToOutput API.

2023-07-03 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: lldb/tools/lldb-server/lldb-platform.cpp:112
 return Status("Failed to atomically write file %s",
   file_spec.GetPath().c_str());
   return status;

avl wrote:
> probably, it would be better to add error text here?
> 
> ```
> return Status("Failed to atomically write file %s: %s",
>   file_spec.GetPath().c_str(), 
> toString(std::move(Err)).c_str());
> ```
good idea.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154329

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


[clang] d963420 - [Headers][X86] Ensure all AVX broadcast scalar load intrinsics are unaligned

2023-07-03 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2023-07-03T14:04:50+01:00
New Revision: d9634205d999439807a9f6c5a18be58ac1a55ced

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

LOG: [Headers][X86] Ensure all AVX broadcast scalar load intrinsics are 
unaligned

Similar to the existing _mm_load1_pd/_mm_loaddup_pd and broadcast vector loads, 
these intrinsic should ensure the loads are unaligned and not assume type 
alignment

Fixes #62325

Added: 


Modified: 
clang/lib/Headers/avxintrin.h
clang/test/CodeGen/X86/avx-builtins.c

Removed: 




diff  --git a/clang/lib/Headers/avxintrin.h b/clang/lib/Headers/avxintrin.h
index bd119220559e47..94fac5e6c9da47 100644
--- a/clang/lib/Headers/avxintrin.h
+++ b/clang/lib/Headers/avxintrin.h
@@ -3017,8 +3017,11 @@ _mm256_zeroupper(void)
 static __inline __m128 __DEFAULT_FN_ATTRS128
 _mm_broadcast_ss(float const *__a)
 {
-  float __f = *__a;
-  return __extension__ (__m128)(__v4sf){ __f, __f, __f, __f };
+  struct __mm_broadcast_ss_struct {
+float __f;
+  } __attribute__((__packed__, __may_alias__));
+  float __f = ((const struct __mm_broadcast_ss_struct*)__a)->__f;
+  return __extension__ (__m128){ __f, __f, __f, __f };
 }
 
 /// Loads a scalar double-precision floating point value from the
@@ -3036,7 +3039,10 @@ _mm_broadcast_ss(float const *__a)
 static __inline __m256d __DEFAULT_FN_ATTRS
 _mm256_broadcast_sd(double const *__a)
 {
-  double __d = *__a;
+  struct __mm256_broadcast_sd_struct {
+double __d;
+  } __attribute__((__packed__, __may_alias__));
+  double __d = ((const struct __mm256_broadcast_sd_struct*)__a)->__d;
   return __extension__ (__m256d)(__v4df){ __d, __d, __d, __d };
 }
 
@@ -3055,7 +3061,10 @@ _mm256_broadcast_sd(double const *__a)
 static __inline __m256 __DEFAULT_FN_ATTRS
 _mm256_broadcast_ss(float const *__a)
 {
-  float __f = *__a;
+  struct __mm256_broadcast_ss_struct {
+float __f;
+  } __attribute__((__packed__, __may_alias__));
+  float __f = ((const struct __mm256_broadcast_ss_struct*)__a)->__f;
   return __extension__ (__m256)(__v8sf){ __f, __f, __f, __f, __f, __f, __f, 
__f };
 }
 

diff  --git a/clang/test/CodeGen/X86/avx-builtins.c 
b/clang/test/CodeGen/X86/avx-builtins.c
index 761ab6e9eb2cb0..b68d192051b9bf 100644
--- a/clang/test/CodeGen/X86/avx-builtins.c
+++ b/clang/test/CodeGen/X86/avx-builtins.c
@@ -99,7 +99,7 @@ __m256 test_mm256_broadcast_ps(__m128* A) {
 
 __m256d test_mm256_broadcast_sd(double* A) {
   // CHECK-LABEL: test_mm256_broadcast_sd
-  // CHECK: load double, ptr %{{.*}}
+  // CHECK: load double, ptr %{{.*}}, align 1{{$}}
   // CHECK: insertelement <4 x double> undef, double %{{.*}}, i32 0
   // CHECK: insertelement <4 x double> %{{.*}}, double %{{.*}}, i32 1
   // CHECK: insertelement <4 x double> %{{.*}}, double %{{.*}}, i32 2
@@ -109,7 +109,7 @@ __m256d test_mm256_broadcast_sd(double* A) {
 
 __m128 test_mm_broadcast_ss(float* A) {
   // CHECK-LABEL: test_mm_broadcast_ss
-  // CHECK: load float, ptr %{{.*}}
+  // CHECK: load float, ptr %{{.*}}, align 1{{$}}
   // CHECK: insertelement <4 x float> undef, float %{{.*}}, i32 0
   // CHECK: insertelement <4 x float> %{{.*}}, float %{{.*}}, i32 1
   // CHECK: insertelement <4 x float> %{{.*}}, float %{{.*}}, i32 2
@@ -119,7 +119,7 @@ __m128 test_mm_broadcast_ss(float* A) {
 
 __m256 test_mm256_broadcast_ss(float* A) {
   // CHECK-LABEL: test_mm256_broadcast_ss
-  // CHECK: load float, ptr %{{.*}}
+  // CHECK: load float, ptr %{{.*}}, align 1{{$}}
   // CHECK: insertelement <8 x float> undef, float %{{.*}}, i32 0
   // CHECK: insertelement <8 x float> %{{.*}}, float %{{.*}}, i32 1
   // CHECK: insertelement <8 x float> %{{.*}}, float %{{.*}}, i32 2



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


[PATCH] D154339: [clang][dataflow] Make `runDataflowReturnError()` a non-template function.

2023-07-03 Thread Martin Böhme via Phabricator via cfe-commits
mboehme created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
mboehme requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

It turns out this didn't need to be a template at all.

Likewise, change callers to they're non-template functions.

Also, correct / clarify some comments in RecordOps.h.

This is in response to post-commit comments on https://reviews.llvm.org/D153006.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154339

Files:
  clang/include/clang/Analysis/FlowSensitive/RecordOps.h
  clang/unittests/Analysis/FlowSensitive/RecordOpsTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -38,21 +38,28 @@
 using ::testing::NotNull;
 using ::testing::UnorderedElementsAre;
 
-template 
-void runDataflow(llvm::StringRef Code, VerifyResultsT VerifyResults,
- DataflowAnalysisOptions Options,
- LangStandard::Kind Std = LangStandard::lang_cxx17,
- llvm::StringRef TargetFun = "target") {
+void runDataflow(
+llvm::StringRef Code,
+std::function<
+void(const llvm::StringMap> &,
+ ASTContext &)>
+VerifyResults,
+DataflowAnalysisOptions Options,
+LangStandard::Kind Std = LangStandard::lang_cxx17,
+llvm::StringRef TargetFun = "target") {
   ASSERT_THAT_ERROR(
   runDataflowReturnError(Code, VerifyResults, Options, Std, TargetFun),
   llvm::Succeeded());
 }
 
-template 
-void runDataflow(llvm::StringRef Code, VerifyResultsT VerifyResults,
- LangStandard::Kind Std = LangStandard::lang_cxx17,
- bool ApplyBuiltinTransfer = true,
- llvm::StringRef TargetFun = "target") {
+void runDataflow(
+llvm::StringRef Code,
+std::function<
+void(const llvm::StringMap> &,
+ ASTContext &)>
+VerifyResults,
+LangStandard::Kind Std = LangStandard::lang_cxx17,
+bool ApplyBuiltinTransfer = true, llvm::StringRef TargetFun = "target") {
   runDataflow(Code, std::move(VerifyResults),
   {ApplyBuiltinTransfer ? BuiltinOptions{}
 : std::optional()},
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -386,40 +386,15 @@
 
 /// Runs dataflow on `Code` with a `NoopAnalysis` and calls `VerifyResults` to
 /// verify the results.
-template 
-llvm::Error
-runDataflowReturnError(llvm::StringRef Code, VerifyResultsT VerifyResults,
-   DataflowAnalysisOptions Options,
-   LangStandard::Kind Std = LangStandard::lang_cxx17,
-   llvm::StringRef TargetFun = "target") {
-  using ast_matchers::hasName;
-  llvm::SmallVector ASTBuildArgs = {
-  // -fnodelayed-template-parsing is the default everywhere but on Windows.
-  // Set it explicitly so that tests behave the same on Windows as on other
-  // platforms.
-  "-fsyntax-only", "-fno-delayed-template-parsing",
-  "-std=" +
-  std::string(LangStandard::getLangStandardForKind(Std).getName())};
-  AnalysisInputs AI(
-  Code, hasName(TargetFun),
-  [UseBuiltinModel = Options.BuiltinOpts.has_value()](ASTContext &C,
-  Environment &Env) {
-return NoopAnalysis(
-C,
-DataflowAnalysisOptions{
-UseBuiltinModel ? Env.getDataflowAnalysisContext().getOptions()
-: std::optional()});
-  });
-  AI.ASTBuildArgs = ASTBuildArgs;
-  if (Options.BuiltinOpts)
-AI.BuiltinOptions = *Options.BuiltinOpts;
-  return checkDataflow(
-  std::move(AI),
-  /*VerifyResults=*/
-  [&VerifyResults](
-  const llvm::StringMap> &Results,
-  const AnalysisOutputs &AO) { VerifyResults(Results, AO.ASTCtx); });
-}
+llvm::Error runDataflowReturnError(
+llvm::StringRef Code,
+std::function<
+void(const llvm::StringMap> &,
+ ASTContext &)>
+VerifyResults,
+DataflowAnalysisOptions Options,
+LangStandard::Kind Std = LangStandard::lang_cxx17,
+llvm::StringRef TargetFun = "target");
 
 /// Returns the `ValueDecl` for the given identifier.
 ///
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
===
--- clang/unitt

[PATCH] D153006: [clang][dataflow] Perform deep copies in copy and move operations.

2023-07-03 Thread Martin Böhme via Phabricator via cfe-commits
mboehme marked 3 inline comments as done.
mboehme added a comment.

https://reviews.llvm.org/D154339 has changes in response to post-commit 
comments.




Comment at: clang/include/clang/Analysis/FlowSensitive/RecordOps.h:26
+/// fields of record type. It also copies properties from the `StructValue`
+/// associated with `Dst` to the `StructValue` associated with `Src` (if these
+/// `StructValue`s exist).

gribozavr2 wrote:
> Shouldn't it go the other way, from Src to Dst?
Oops. Fixed in https://reviews.llvm.org/D154339.



Comment at: clang/include/clang/Analysis/FlowSensitive/RecordOps.h:53
+/// refer to the same storage location. If `StructValue`s are associated with
+/// `Loc1` and `Loc2`, it also compares the properties on those `StructValue`s.
+///

gribozavr2 wrote:
> Could you add a caveat that only 'true' return values from this function 
> matter?
> 
> That is, "false" means "might or might not be equal at runtime, we don't 
> know".
Good point. Done in https://reviews.llvm.org/D154339.



Comment at: clang/unittests/Analysis/FlowSensitive/TestingSupport.h:391
+llvm::Error
+runDataflowReturnError(llvm::StringRef Code, VerifyResultsT VerifyResults,
+   DataflowAnalysisOptions Options,

gribozavr2 wrote:
> Could you change VerifyResultsT to a std::function (like in other overloads 
> above) so that the type signature is clear?
> 
> I'm also unsure about the name - why start a new overload set? It seems like 
> another variant of the checkDataflow() functions above.
> Could you change VerifyResultsT to a std::function (like in other overloads 
> above) so that the type signature is clear?

Done in https://reviews.llvm.org/D154339.

I could have sworn that when I moved this from TransferTest.cpp to here that I 
tried making this change and realized I couldn't for some reason. But obviously 
I was wrong.

> I'm also unsure about the name - why start a new overload set? It seems like 
> another variant of the checkDataflow() functions above.

This is really just moved from TransferTest.cpp -- and it's more closely 
related to the `runDataflow()` functions there and in the newly added 
RecordOps.cpp. (I can't call it `runDataflow()` because then it would differ 
only in return type from one of the functions in the overload set.)

Let's continue the discussion on https://reviews.llvm.org/D154339 if necessary.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153006

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


[PATCH] D151696: [x86] Remove CPU_SPECIFIC* MACROs and add getCPUDispatchMangling

2023-07-03 Thread Freddy, Ye via Phabricator via cfe-commits
FreddyYe added a comment.

gentle ping. If no objections, I'll merge this tomorrow.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151696

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


[PATCH] D152093: [clang][Analysis] Handle && and || against variable and its negation as tautology

2023-07-03 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet added a comment.

Ping


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

https://reviews.llvm.org/D152093

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


[PATCH] D153359: [clang][Diagnostics] Fix distant source ranges in bad-conversion notes

2023-07-03 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet updated this revision to Diff 536743.
hazohelet edited the summary of this revision.
hazohelet added a comment.

Edited release note so that it only mentions the clang 16 -> 17 changes, and 
not development internal ones


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

https://reviews.llvm.org/D153359

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaOverload.cpp
  clang/test/Misc/diag-overload-cand-ranges.cpp
  clang/test/Misc/diag-overload-cand-ranges.mm

Index: clang/test/Misc/diag-overload-cand-ranges.mm
===
--- /dev/null
+++ clang/test/Misc/diag-overload-cand-ranges.mm
@@ -0,0 +1,26 @@
+// RUN: not %clang_cc1 -fobjc-runtime-has-weak -fobjc-arc -fsyntax-only -fdiagnostics-print-source-range-info %s 2>&1 | FileCheck %s --strict-whitespace -check-prefixes=CHECK,ARC
+// RUN: not %clang_cc1 -fobjc-runtime-has-weak -fobjc-gc -fsyntax-only -fdiagnostics-print-source-range-info %s 2>&1 | FileCheck %s --strict-whitespace -check-prefixes=CHECK,GC
+
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+1]]:15-[[@LINE+1]]:28}: note: {{.*}}: 1st argument
+void powerful(__strong id &);
+void lifetime_gcattr_mismatch() {
+  static __weak id weak_id;
+  powerful(weak_id);
+}
+
+// CHECK:  error: no matching function
+// ARC::{[[@LINE+2]]:11-[[@LINE+2]]:21}: note: {{.*}}: cannot implicitly convert
+// GC: :{[[@LINE+1]]:11-[[@LINE+1]]:21}: note: {{.*}}: no known conversion
+void func(char *uiui);
+
+__attribute__((objc_root_class))
+@interface Interface
+- (void)something;
+@end
+
+@implementation Interface
+- (void)something{
+func(self);
+}
+@end
Index: clang/test/Misc/diag-overload-cand-ranges.cpp
===
--- /dev/null
+++ clang/test/Misc/diag-overload-cand-ranges.cpp
@@ -0,0 +1,72 @@
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-print-source-range-info %s 2>&1 | FileCheck %s --strict-whitespace
+// CHECK:  error: no matching function
+template  struct mcdata {
+  typedef int result_type;
+};
+template  typename mcdata::result_type wrap_mean(mcdata const &);
+// CHECK:  :{[[@LINE+1]]:19-[[@LINE+1]]:53}: note: {{.*}}: no overload of 'wrap_mean'
+void add_property(double (*)(mcdata const &));
+void f() { add_property(&wrap_mean); }
+
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+1]]:10-[[@LINE+1]]:51}: note: {{.*}}: cannot pass pointer to generic address space
+void baz(__attribute__((opencl_private)) int *Data) {}
+void fizz() {
+  int *Nop;
+  baz(Nop);
+  // CHECK:error: no matching function
+  // CHECK::[[@LINE+1]]:53: note: {{.*}}: 'this' object is in address space '__private'
+  __attribute__((opencl_private)) static auto err = [&]() {};
+  err();
+}
+
+// CHECK:  error: no matching function
+struct Bar {
+// CHECK:  :{[[@LINE+1]]:26-[[@LINE+1]]:32}: note: {{.*}} would lose const qualifier
+static void foo(int num, int *X) {}
+// CHECK:  :{[[@LINE+1]]:17-[[@LINE+1]]:25}: note: {{.*}} no known conversion
+static void foo(int *err, int *x) {}
+};
+void bar(const int *Y) {
+  Bar::foo(5, Y);
+}
+
+struct InComp;
+
+struct A {};
+struct B : public A{};
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+5]]:36-[[@LINE+5]]:50}: note: {{.*}}: cannot convert initializer
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+3]]:36-[[@LINE+3]]:50}: note: {{.*}}: cannot convert argument
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+1]]:11-[[@LINE+1]]:18}: note: {{.*}}: no known conversion
+void hoge(char aa, const char *bb, const A& third);
+
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+1]]:14-[[@LINE+1]]:16}: note: {{.*}}: cannot convert from base class
+void derived(B*);
+
+void func(const A &arg) {
+  hoge(1, "pass", {{{arg}}});
+  InComp *a;
+  hoge(1, "pass", a);
+  hoge("first", 5, 6);
+  A *b;
+  derived(b);
+}
+
+struct Q {
+  // CHECK:error: invalid operands
+  // CHECK::[[@LINE+1]]:6: note: {{.*}}: 'this' argument has type 'const Q'
+  Q &operator+(void*);
+};
+
+void fuga(const Q q) { q + 3; }
+
+template  class Type1 {};
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+1]]:43-[[@LINE+1]]:54}: note: {{.*}}: expects an lvalue
+template  void Function1(int zz, Type1 &x, int ww) {}
+
+void Function() { Function1(33, Type1<-42>(), 66); }
Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -10753,6 +10753,8 @@
   Expr *FromExpr = Conv.Bad.FromExpr;
   QualType FromTy = Conv.Bad.getFromType();
   QualType ToTy = Conv.Bad.getToType();
+  SourceRange ToParamRange =
+  !isObjectArgument ? Fn->getParamDecl(I)->getSourceRange() : SourceRange();
 
   if (FromTy == S.Context.OverloadTy) {
 assert(FromExpr && "overload set 

[PATCH] D153296: [AST] Stop evaluate constant expression if the condition expression which in switch statement contains errors

2023-07-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman requested changes to this revision.
aaron.ballman added a comment.
This revision now requires changes to proceed.

In D153296#4459769 , @yronglin wrote:

> Please help me, I have no better idea on this issue, do you have any better 
> ideas? @erichkeane @shafik

I think what's being suggested is to change `EvaluateDependentExpr()` somewhat 
along these lines:

  static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
assert(E->isValueDependent());
  
// Note that we have a side effect that matters for constant evaluation.
bool SideEffects = Info.noteSideEffect();
// If the reason we're here is because of a recovery expression, we don't
// want to continue to evaluate further as we will never know what the 
actual
// value is.
if (isa(E))
  return false;
  
// Otherwise, return whether we want to continue after noting the side
// effects, which should only happen if the expression has errors but isn't
// a recovery expression on its own.
assert(E->containsErrors() && "valid value-dependent expression should 
never "
  "reach invalid code path.");
return SideEffects;
  }

This way, code paths that get down to a `RecoveryExpr` will not continue to 
evaluate further (as there's really no point -- there's no way to get a 
reasonable value from from the recovery expression anyway), but the fix isn't 
specific to just switch statements. After making these changes, you should look 
for places where `EvaluateDependentExpr()` is being called to try to come up 
with a test case where that expression is a recovery expression so that we can 
fill out test coverage beyond just the situation with `switch` from the 
original report. Does that make sense?

(Marking as requesting changes so it's clear this review isn't yet accepted.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153296

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


[PATCH] D154297: clang-tidy: accessing checks not done for aliases of `std::array`

2023-07-03 Thread Jorge Pinto Sousa via Phabricator via cfe-commits
sousajo added a comment.

while landing it, if someone feels that the release work can be reworded please 
feel free to do so.


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

https://reviews.llvm.org/D154297

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


[PATCH] D154334: [clang] Add `__has_extension ()` for C++11 features

2023-07-03 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon added a comment.

In D154334#4468158 , @aaron.ballman 
wrote:

> Thank you for this! LGTM. but can you also be sure to update this table: 
> https://github.com/llvm/llvm-project/blob/main/clang/docs/LanguageExtensions.rst?plain=1#L1429

Hmm, I have a feeling that the table is for features that have `__cpp_*` macros 
defined for them. The features I intended to fix are described by the same doc 
here - 
https://github.com/llvm/llvm-project/blob/29f4c398717184a019791ed52d1d0d69ed5dabb6/clang/docs/LanguageExtensions.rst?plain=1#L1071
 .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154334

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


[PATCH] D154334: [clang] Add `__has_extension ()` for C++11 features

2023-07-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D154334#4468404 , @Fznamznon wrote:

> In D154334#4468158 , @aaron.ballman 
> wrote:
>
>> Thank you for this! LGTM. but can you also be sure to update this table: 
>> https://github.com/llvm/llvm-project/blob/main/clang/docs/LanguageExtensions.rst?plain=1#L1429
>
> Hmm, I have a feeling that the table is for features that have `__cpp_*` 
> macros defined for them. The features I intended to fix are described by the 
> same doc here - 
> https://github.com/llvm/llvm-project/blob/29f4c398717184a019791ed52d1d0d69ed5dabb6/clang/docs/LanguageExtensions.rst?plain=1#L1071
>  .

Oh shoot, you're right, these don't have the typical feature testing macros 
from http://eel.is/c++draft/tab:cpp.predefined.ft ! Sorry for the noise, this 
is fine as-is.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154334

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


[clang] 2d4f289 - [clang] Add `__has_extension ()` for C++11 features

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

Author: Mariya Podchishchaeva
Date: 2023-07-03T10:15:40-04:00
New Revision: 2d4f2890823fa3edc6ae563edec4dacad1989564

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

LOG: [clang] Add `__has_extension ()` for C++11 features

Add `__has_extension (cxx_defaulted_functions)` and
`__has_extension (cxx_default_function_template_args)` since they are
accepted in C++98 mode as extensions.

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

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/Features.def
clang/test/Lexer/has_extension_cxx.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 94eddd5e3b89c7..022d51b525c04c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -565,6 +565,9 @@ Bug Fixes in This Version
   (`#63629 `_)
 - Fixed parsing of elaborated type specifier inside of a new expression.
   (`#34341 `_)
+- Clang now correctly evaluates ``__has_extension (cxx_defaulted_functions)``
+  and ``__has_extension (cxx_default_function_template_args)`` to 1.
+  (`#61758 `_)
 
 Bug Fixes to Compiler Builtins
 ^^

diff  --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index 4113b4d868dda6..1eb4573a8f7fef 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -247,6 +247,8 @@ EXTENSION(c_static_assert, true)
 EXTENSION(c_thread_local, PP.getTargetInfo().isTLSSupported())
 // C++11 features supported by other languages as extensions.
 EXTENSION(cxx_atomic, LangOpts.CPlusPlus)
+EXTENSION(cxx_default_function_template_args, LangOpts.CPlusPlus)
+EXTENSION(cxx_defaulted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_deleted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_explicit_conversions, LangOpts.CPlusPlus)
 EXTENSION(cxx_inline_namespaces, LangOpts.CPlusPlus)

diff  --git a/clang/test/Lexer/has_extension_cxx.cpp 
b/clang/test/Lexer/has_extension_cxx.cpp
index d1267eaf85d84b..1ae6a446b300a7 100644
--- a/clang/test/Lexer/has_extension_cxx.cpp
+++ b/clang/test/Lexer/has_extension_cxx.cpp
@@ -11,6 +11,16 @@ int c_static_assert();
 int c_generic_selections();
 #endif
 
+// CHECK: has_default_function_template_args
+#if __has_extension(cxx_default_function_template_args)
+int has_default_function_template_args();
+#endif
+
+// CHECK: has_defaulted_functions
+#if __has_extension(cxx_defaulted_functions)
+int has_defaulted_functions();
+#endif
+
 // CHECK: has_deleted_functions
 #if __has_extension(cxx_deleted_functions)
 int has_deleted_functions();



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


[PATCH] D154334: [clang] Add `__has_extension ()` for C++11 features

2023-07-03 Thread Mariya Podchishchaeva 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 rG2d4f2890823f: [clang] Add `__has_extension ()` for C++11 
features (authored by Fznamznon).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154334

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Features.def
  clang/test/Lexer/has_extension_cxx.cpp


Index: clang/test/Lexer/has_extension_cxx.cpp
===
--- clang/test/Lexer/has_extension_cxx.cpp
+++ clang/test/Lexer/has_extension_cxx.cpp
@@ -11,6 +11,16 @@
 int c_generic_selections();
 #endif
 
+// CHECK: has_default_function_template_args
+#if __has_extension(cxx_default_function_template_args)
+int has_default_function_template_args();
+#endif
+
+// CHECK: has_defaulted_functions
+#if __has_extension(cxx_defaulted_functions)
+int has_defaulted_functions();
+#endif
+
 // CHECK: has_deleted_functions
 #if __has_extension(cxx_deleted_functions)
 int has_deleted_functions();
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -247,6 +247,8 @@
 EXTENSION(c_thread_local, PP.getTargetInfo().isTLSSupported())
 // C++11 features supported by other languages as extensions.
 EXTENSION(cxx_atomic, LangOpts.CPlusPlus)
+EXTENSION(cxx_default_function_template_args, LangOpts.CPlusPlus)
+EXTENSION(cxx_defaulted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_deleted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_explicit_conversions, LangOpts.CPlusPlus)
 EXTENSION(cxx_inline_namespaces, LangOpts.CPlusPlus)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -565,6 +565,9 @@
   (`#63629 `_)
 - Fixed parsing of elaborated type specifier inside of a new expression.
   (`#34341 `_)
+- Clang now correctly evaluates ``__has_extension (cxx_defaulted_functions)``
+  and ``__has_extension (cxx_default_function_template_args)`` to 1.
+  (`#61758 `_)
 
 Bug Fixes to Compiler Builtins
 ^^


Index: clang/test/Lexer/has_extension_cxx.cpp
===
--- clang/test/Lexer/has_extension_cxx.cpp
+++ clang/test/Lexer/has_extension_cxx.cpp
@@ -11,6 +11,16 @@
 int c_generic_selections();
 #endif
 
+// CHECK: has_default_function_template_args
+#if __has_extension(cxx_default_function_template_args)
+int has_default_function_template_args();
+#endif
+
+// CHECK: has_defaulted_functions
+#if __has_extension(cxx_defaulted_functions)
+int has_defaulted_functions();
+#endif
+
 // CHECK: has_deleted_functions
 #if __has_extension(cxx_deleted_functions)
 int has_deleted_functions();
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -247,6 +247,8 @@
 EXTENSION(c_thread_local, PP.getTargetInfo().isTLSSupported())
 // C++11 features supported by other languages as extensions.
 EXTENSION(cxx_atomic, LangOpts.CPlusPlus)
+EXTENSION(cxx_default_function_template_args, LangOpts.CPlusPlus)
+EXTENSION(cxx_defaulted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_deleted_functions, LangOpts.CPlusPlus)
 EXTENSION(cxx_explicit_conversions, LangOpts.CPlusPlus)
 EXTENSION(cxx_inline_namespaces, LangOpts.CPlusPlus)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -565,6 +565,9 @@
   (`#63629 `_)
 - Fixed parsing of elaborated type specifier inside of a new expression.
   (`#34341 `_)
+- Clang now correctly evaluates ``__has_extension (cxx_defaulted_functions)``
+  and ``__has_extension (cxx_default_function_template_args)`` to 1.
+  (`#61758 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D154335: [clang][tooling] Fix early termination when there are nested expansions

2023-07-03 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Tooling/Syntax/Tokens.cpp:116
-
-// Now: how do we adjust the previous/next bounds? Three cases:
-// A) If they are also part of the same macro arg, we translate them too.

(no action needed)

we had extensive discussion of why this change is a no-op, and how to prove it, 
and what comments to leave.
However in the end I don't think such a comment is necessary, because the code 
makes sense in isolation, and equivalence-to-previous-version isn't very 
interesting!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154335

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


[PATCH] D143052: [CMake] Replace llvm_check_linker_flag and llvm_check_compiler_linker_flag

2023-07-03 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a comment.
Herald added a subscriber: ekilmer.

What is the status of this? We now require CMake 3.20, can this be rebased and 
landed in some form?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143052

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


[PATCH] D154287: [clang-tidy] Add modernize-use-std-format check

2023-07-03 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-format.rst:6
+
+Converts calls to ``absl::StrFormat`` to equivalent calls to C++20's
+``std::format`` function, modifying the format string appropriately. The

Please synchronize first statement with Release Notes.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-format.rst:58
+  of -42 and the signed representation of 0x (often 4294967254
+  and -1 respectively.) When false (which is the default), these casts
+  will not be added which may cause a change in the output. Note that this

Please highlight `false` with single back-ticks.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-format.rst:70
+   immediately afterwards. The defaualt value for this option is
+   ``absl::StrFormat``.
+

Single back-ticks for option value.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-format.rst:84
+   `ReplacementFormatFunction` so that a ``#include`` directive can be added if
+   required. If `ReplacementFormatFunction` is ``std::format`` then this 
option will
+   default to , otherwise this option will default to nothing

Ditto.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154287

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


[PATCH] D154349: [include-cleaner] Add a signal to down-rank exporting headers

2023-07-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: hokein.
Herald added a project: All.
kadircet requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Currently exporter can have same relevance signals as the origin header
when name match signals don't trigger.
This patch introduces a tie braker signal to boost origin headers in
such cases, this is deliberately introduced with lower significance than
public-ness to make sure we still prefer a public-exporter instead of a
private-origin header.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154349

Files:
  clang-tools-extra/include-cleaner/lib/FindHeaders.cpp
  clang-tools-extra/include-cleaner/lib/TypesInternal.h
  clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
  clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/FindHeadersTest.cpp
@@ -8,17 +8,21 @@
 
 #include "AnalysisInternal.h"
 #include "TypesInternal.h"
+#include "clang-include-cleaner/Analysis.h"
 #include "clang-include-cleaner/Record.h"
 #include "clang-include-cleaner/Types.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/Basic/FileEntry.h"
 #include "clang/Basic/FileManager.h"
+#include "clang/Basic/LLVM.h"
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Testing/TestAST.h"
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
 #include 
 
 namespace clang::include_cleaner {
@@ -253,11 +257,11 @@
   EXPECT_THAT(
   findHeaders("private.inc"),
   UnorderedElementsAre(
-  HintedHeader(physicalHeader("private.inc"), Hints::None),
+  HintedHeader(physicalHeader("private.inc"), Hints::OriginHeader),
   HintedHeader(physicalHeader("public.h"), Hints::PublicHeader)));
   EXPECT_THAT(findHeaders("private.h"),
-  UnorderedElementsAre(
-  HintedHeader(physicalHeader("private.h"), Hints::None)));
+  UnorderedElementsAre(HintedHeader(physicalHeader("private.h"),
+Hints::OriginHeader)));
 }
 
 TEST_F(FindHeadersTest, PreferredHeaderHint) {
@@ -269,11 +273,12 @@
   )cpp");
   buildAST();
   // Headers explicitly marked should've preferred signal.
-  EXPECT_THAT(findHeaders("private.h"),
-  UnorderedElementsAre(
-  HintedHeader(physicalHeader("private.h"), Hints::None),
-  HintedHeader(Header("\"public.h\""),
-   Hints::PreferredHeader | Hints::PublicHeader)));
+  EXPECT_THAT(
+  findHeaders("private.h"),
+  UnorderedElementsAre(
+  HintedHeader(physicalHeader("private.h"), Hints::OriginHeader),
+  HintedHeader(Header("\"public.h\""),
+   Hints::PreferredHeader | Hints::PublicHeader)));
 }
 
 class HeadersForSymbolTest : public FindHeadersTest {
@@ -339,11 +344,12 @@
 }
 
 TEST_F(HeadersForSymbolTest, Ranking) {
-  // Sorting is done over (canonical, public, complete) triplet.
+  // Sorting is done over (canonical, public, complete, origin)-tuple.
   Inputs.Code = R"cpp(
 #include "private.h"
 #include "public.h"
 #include "public_complete.h"
+#include "exporter.h"
   )cpp";
   Inputs.ExtraFiles["public.h"] = guard(R"cpp(
 struct foo;
@@ -352,11 +358,15 @@
 // IWYU pragma: private, include "canonical.h"
 struct foo;
   )cpp");
+  Inputs.ExtraFiles["exporter.h"] = guard(R"cpp(
+  #include "private.h" // IWYU pragma: export
+  )cpp");
   Inputs.ExtraFiles["public_complete.h"] = guard("struct foo {};");
   buildAST();
   EXPECT_THAT(headersForFoo(), ElementsAre(Header("\"canonical.h\""),
physicalHeader("public_complete.h"),
physicalHeader("public.h"),
+   physicalHeader("exporter.h"),
physicalHeader("private.h")));
 }
 
@@ -424,6 +434,24 @@
physicalHeader("private.h")));
 }
 
+TEST_F(HeadersForSymbolTest, ExporterIsDownRanked) {
+  Inputs.Code = R"cpp(
+#include "exporter.h"
+#include "zoo.h"
+  )cpp";
+  // Deliberately named as zoo to make sure it doesn't get name-match boost and
+  // also gets lexicographically bigger order than "exporter".
+  Inputs.ExtraFiles["zoo.h"] = guard(R"cpp(
+struct foo {};
+  )cpp");
+  Inputs.ExtraFiles["exporter.h"] = guard(R"cpp(
+#include "zoo.h" // IWYU pragma: export
+  )cpp");
+  buildAST();
+  EXPECT_THAT(headersForFoo(), ElementsAre(physicalHeader("zoo.h"),
+

[PATCH] D153969: [clang][ExprConstant] Fix crash on uninitialized base class subobject

2023-07-03 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet updated this revision to Diff 536771.
hazohelet edited the summary of this revision.
hazohelet added a comment.

- Removed the `base class inherited here` redundant note
- Provided source range and added test for it

The provided source range is NOT directly calling 
`CXXBaseSpecifier::getSourceRange` so as not to cover the access specifiers 
like `public`, `private` or `protected`


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

https://reviews.llvm.org/D153969

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticASTKinds.td
  clang/lib/AST/ExprConstant.cpp
  clang/test/Misc/constexpr-subobj-init-source-ranges.cpp
  clang/test/SemaCXX/constexpr-subobj-initialization.cpp

Index: clang/test/SemaCXX/constexpr-subobj-initialization.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/constexpr-subobj-initialization.cpp
@@ -0,0 +1,30 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+namespace baseclass_uninit {
+struct DelBase {
+  constexpr DelBase() = delete; // expected-note {{'DelBase' has been explicitly marked deleted here}}
+};
+
+struct Foo : DelBase {  // expected-note 2{{constructor of base class 'DelBase' is not called}}
+  constexpr Foo() {}; // expected-error {{call to deleted constructor of 'DelBase'}}
+};
+constexpr Foo f; // expected-error {{must be initialized by a constant expression}}
+struct Bar : Foo {
+  constexpr Bar() {};
+};
+constexpr Bar bar; // expected-error {{must be initialized by a constant expression}}
+
+struct Base {};
+struct A : Base { // expected-note {{constructor of base class 'Base' is not called}}
+  constexpr A() : value() {} // expected-error {{member initializer 'value' does not name a non-static data member or base class}}
+};
+
+constexpr A a; // expected-error {{must be initialized by a constant expression}}
+
+struct B : Base { // expected-note {{constructor of base class 'Base' is not called}}
+  constexpr B() : {} // expected-error {{expected class member or base class name}}
+};
+
+constexpr B b; // expected-error {{must be initialized by a constant expression}}
+} // namespace baseclass_uninit
+
Index: clang/test/Misc/constexpr-subobj-init-source-ranges.cpp
===
--- /dev/null
+++ clang/test/Misc/constexpr-subobj-init-source-ranges.cpp
@@ -0,0 +1,11 @@
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-print-source-range-info %s 2>&1 | FileCheck %s --strict-whitespace
+
+struct DelBase {
+  constexpr DelBase() = delete;
+};
+
+// CHECK:  :{[[@LINE+1]]:21-[[@LINE+1]]:28}
+struct Foo : public DelBase {
+  constexpr Foo() {};
+};
+constexpr Foo f;
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -2415,9 +2415,16 @@
 if (const CXXRecordDecl *CD = dyn_cast(RD)) {
   unsigned BaseIndex = 0;
   for (const CXXBaseSpecifier &BS : CD->bases()) {
-if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
-   Value.getStructBase(BaseIndex), Kind,
-   /*SubobjectDecl=*/nullptr, CheckedTemps))
+const APValue &BaseValue = Value.getStructBase(BaseIndex);
+if (!BaseValue.hasValue()) {
+  SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
+  Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
+  << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
+  return false;
+}
+if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
+   Kind, /*SubobjectDecl=*/nullptr,
+   CheckedTemps))
   return false;
 ++BaseIndex;
   }
Index: clang/include/clang/Basic/DiagnosticASTKinds.td
===
--- clang/include/clang/Basic/DiagnosticASTKinds.td
+++ clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -70,6 +70,8 @@
   "is not a constant expression">;
 def note_constexpr_uninitialized : Note<
   "subobject %0 is not initialized">;
+def note_constexpr_uninitialized_base : Note<
+  "constructor of base class %0 is not called">;
 def note_constexpr_static_local : Note<
   "control flows through the definition of a %select{static|thread_local}0 variable">;
 def note_constexpr_subobject_declared_here : Note<
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -379,6 +379,8 @@
   (`#57081: `_)
 - Clang no longer emits inappropriate notes about the loss of ``__unaligned`` qualifier
   on overload resolution, when the actual reason for the failure is loss of other qualifiers.
+- Clang contexpr evaluator 

[clang] 9841daf - [clang][tooling] Fix early termination when there are nested expansions

2023-07-03 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2023-07-03T16:58:04+02:00
New Revision: 9841daf27076886c6ab8e155eb812bda76f77532

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

LOG: [clang][tooling] Fix early termination when there are nested expansions

This also does some cleanups, I am happy to undo them (or send as
separate patches):
- Change the early exit to stop only once we hit an expansion inside the
  main file, to make sure we keep following the nested expansions.
- Add more tests to cover all the cases mentioned in the implementation
- Drop the adjustments for prev/next tokens. We do the final checks
  based on the expansion locations anyway, so any intermediate mapping
  was a no-op.

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

Added: 


Modified: 
clang-tools-extra/clangd/unittests/tweaks/AddUsingTests.cpp
clang/lib/Tooling/Syntax/Tokens.cpp
clang/unittests/Tooling/Syntax/TokensTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/tweaks/AddUsingTests.cpp 
b/clang-tools-extra/clangd/unittests/tweaks/AddUsingTests.cpp
index da76ecad145548..1fd2487378d705 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/AddUsingTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/AddUsingTests.cpp
@@ -71,6 +71,13 @@ class cc {
   // NestedNameSpecifier, but no namespace.
   EXPECT_UNAVAILABLE(Header + "class Foo {}; class F^oo foo;");
 
+  // Nested macro case.
+  EXPECT_AVAILABLE(R"cpp(
+  #define ID2(X) X
+  #define ID(Y, X) Y;ID2(X)
+  namespace ns { struct Foo{}; }
+  ID(int xyz, ns::F^oo) f;)cpp");
+
   // Check that we do not trigger in header files.
   FileName = "test.h";
   ExtraArgs.push_back("-xc++-header"); // .h file is treated a C by default.

diff  --git a/clang/lib/Tooling/Syntax/Tokens.cpp 
b/clang/lib/Tooling/Syntax/Tokens.cpp
index 64e6eee6b62f2f..9c2f470e985fb6 100644
--- a/clang/lib/Tooling/Syntax/Tokens.cpp
+++ b/clang/lib/Tooling/Syntax/Tokens.cpp
@@ -103,66 +103,13 @@ SourceRange spelledForExpandedSlow(SourceLocation First, 
SourceLocation Last,
 // The token `a` is wrapped in 4 arg-expansions, we only want to unwrap 2.
 // We distinguish them by whether the macro expands into the target file.
 // Fortunately, the target file ones will always appear first.
-auto &ExpMacro =
-SM.getSLocEntry(SM.getFileID(ExpFirst.getExpansionLocStart()))
-.getExpansion();
-if (ExpMacro.getExpansionLocStart().isMacroID())
+auto ExpFileID = SM.getFileID(ExpFirst.getExpansionLocStart());
+if (ExpFileID == TargetFile)
   break;
 // Replace each endpoint with its spelling inside the macro arg.
 // (This is getImmediateSpellingLoc without repeating lookups).
 First = ExpFirst.getSpellingLoc().getLocWithOffset(DecFirst.second);
 Last = ExpLast.getSpellingLoc().getLocWithOffset(DecLast.second);
-
-// Now: how do we adjust the previous/next bounds? Three cases:
-// A) If they are also part of the same macro arg, we translate them too.
-//   This will ensure that we don't select any macros nested within the
-//   macro arg that cover extra tokens. Critical case:
-//  #define ID(X) X
-//  ID(prev target) // selecting 'target' succeeds
-//  #define LARGE ID(prev target)
-//  LARGE // selecting 'target' fails.
-// B) They are not in the macro at all, then their expansion range is a
-//sibling to it, and we can safely substitute that.
-//  #define PREV prev
-//  #define ID(X) X
-//  PREV ID(target) // selecting 'target' succeeds.
-//  #define LARGE PREV ID(target)
-//  LARGE // selecting 'target' fails.
-// C) They are in a 
diff erent arg of this macro, or the macro body.
-//Now selecting the whole macro arg is fine, but the whole macro is 
not.
-//Model this by setting using the edge of the macro call as the bound.
-//  #define ID2(X, Y) X Y
-//  ID2(prev, target) // selecting 'target' succeeds
-//  #define LARGE ID2(prev, target)
-//  LARGE // selecting 'target' fails
-auto AdjustBound = [&](SourceLocation &Bound) {
-  if (Bound.isInvalid() || !Bound.isMacroID()) // Non-macro must be case B.
-return;
-  auto DecBound = SM.getDecomposedLoc(Bound);
-  auto &ExpBound = SM.getSLocEntry(DecBound.first).getExpansion();
-  if (ExpBound.isMacroArgExpansion() &&
-  ExpBound.getExpansionLocStart() == ExpFirst.getExpansionLocStart()) {
-// Case A: translate to (spelling) loc within the macro arg.
-Bound = ExpBound.getSpellingLoc().getLocWithOffset(DecBound.second);
-return;
-  }
-  while (Bound.isMacroID()) {
-SourceRange Exp = SM.getImmediateExpansionRange(Bound).getAsRang

[PATCH] D154335: [clang][tooling] Fix early termination when there are nested expansions

2023-07-03 Thread Kadir Cetinkaya 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 rG9841daf27076: [clang][tooling] Fix early termination when 
there are nested expansions (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154335

Files:
  clang-tools-extra/clangd/unittests/tweaks/AddUsingTests.cpp
  clang/lib/Tooling/Syntax/Tokens.cpp
  clang/unittests/Tooling/Syntax/TokensTest.cpp

Index: clang/unittests/Tooling/Syntax/TokensTest.cpp
===
--- clang/unittests/Tooling/Syntax/TokensTest.cpp
+++ clang/unittests/Tooling/Syntax/TokensTest.cpp
@@ -769,12 +769,15 @@
   // Critical cases for mapping of Prev/Next in spelledForExpandedSlow.
   recordTokens(R"cpp(
 #define ID(X) X
-ID(prev ID(good))
+ID(prev good)
+ID(prev ID(good2))
 #define LARGE ID(prev ID(bad))
 LARGE
   )cpp");
   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
   ValueIs(SameRange(findSpelled("good";
+  EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good2")),
+  ValueIs(SameRange(findSpelled("good2";
   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("bad")), std::nullopt);
 
   recordTokens(R"cpp(
@@ -785,19 +788,32 @@
 LARGE
   )cpp");
   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
-ValueIs(SameRange(findSpelled("good";
+  ValueIs(SameRange(findSpelled("good";
   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("bad")), std::nullopt);
 
   recordTokens(R"cpp(
 #define ID(X) X
 #define ID2(X, Y) X Y
-ID2(prev, ID(good))
+ID2(prev, good)
+ID2(prev, ID(good2))
 #define LARGE ID2(prev, bad)
 LARGE
   )cpp");
   EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
-ValueIs(SameRange(findSpelled("good";
+  ValueIs(SameRange(findSpelled("good";
+  EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good2")),
+  ValueIs(SameRange(findSpelled("good2";
   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("bad")), std::nullopt);
+
+  // Prev from macro body.
+  recordTokens(R"cpp(
+#define ID(X) X
+#define ID2(X, Y) X prev ID(Y)
+ID2(not_prev, good)
+  )cpp");
+  EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
+  ValueIs(SameRange(findSpelled("good";
+  EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("prev good")), std::nullopt);
 }
 
 TEST_F(TokenBufferTest, ExpandedTokensForRange) {
Index: clang/lib/Tooling/Syntax/Tokens.cpp
===
--- clang/lib/Tooling/Syntax/Tokens.cpp
+++ clang/lib/Tooling/Syntax/Tokens.cpp
@@ -103,66 +103,13 @@
 // The token `a` is wrapped in 4 arg-expansions, we only want to unwrap 2.
 // We distinguish them by whether the macro expands into the target file.
 // Fortunately, the target file ones will always appear first.
-auto &ExpMacro =
-SM.getSLocEntry(SM.getFileID(ExpFirst.getExpansionLocStart()))
-.getExpansion();
-if (ExpMacro.getExpansionLocStart().isMacroID())
+auto ExpFileID = SM.getFileID(ExpFirst.getExpansionLocStart());
+if (ExpFileID == TargetFile)
   break;
 // Replace each endpoint with its spelling inside the macro arg.
 // (This is getImmediateSpellingLoc without repeating lookups).
 First = ExpFirst.getSpellingLoc().getLocWithOffset(DecFirst.second);
 Last = ExpLast.getSpellingLoc().getLocWithOffset(DecLast.second);
-
-// Now: how do we adjust the previous/next bounds? Three cases:
-// A) If they are also part of the same macro arg, we translate them too.
-//   This will ensure that we don't select any macros nested within the
-//   macro arg that cover extra tokens. Critical case:
-//  #define ID(X) X
-//  ID(prev target) // selecting 'target' succeeds
-//  #define LARGE ID(prev target)
-//  LARGE // selecting 'target' fails.
-// B) They are not in the macro at all, then their expansion range is a
-//sibling to it, and we can safely substitute that.
-//  #define PREV prev
-//  #define ID(X) X
-//  PREV ID(target) // selecting 'target' succeeds.
-//  #define LARGE PREV ID(target)
-//  LARGE // selecting 'target' fails.
-// C) They are in a different arg of this macro, or the macro body.
-//Now selecting the whole macro arg is fine, but the whole macro is not.
-//Model this by setting using the edge of the macro call as the bound.
-//  #define ID2(X, Y) X Y
-//  ID2(prev, target) // selecting 'target' succeeds
-//  #define LARGE ID2(prev, target)
-//  LARGE // selecting 'target' fails
-auto AdjustBound = [&](SourceLocation &Bound) {
-  if (Bound.isInva

[PATCH] D153881: Create diagnostic group for definition deprecation warning

2023-07-03 Thread Nuri Amari via Phabricator via cfe-commits
nuriamari added a comment.

In D153881#4467127 , @aaron.ballman 
wrote:

> I think it's a bit odd that we'd leave `const` under `-Wdeprecated` but 
> separate `constexpr` out into its own warning flag, but I'm also not opposed.

Would moving both const and constexpr into their own warning flag work? I don't 
really see cases where you'd want to disable only one or the other.

> Can you explain the need a bit more though? I think our belief was that 
> silencing this diagnostic was pretty trivial (delete the line in question), 
> so we wouldn't need a separate diagnostic group for it.

In our case we have libraries that are consumed both with say C++14 and C++17, 
so we can't just delete them, we've needed to add a standard version check. 
Admittedly not a huge change either, but we ran into many occurrences of this 
warning trying to adopt the latest Clang. I suppose I don't see the downside of 
a little more granular control.

> Also, these changes should have a release note added to 
> `clang/docs/ReleaseNotes.rst`.

Will do.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153881

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


[PATCH] D153340: [include-cleaner] Add an IgnoreHeaders flag to the command-line tool.

2023-07-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h:67
 /// Determine which headers should be inserted or removed from the main file.
 /// This exposes conclusions but not reasons: use lower-level walkUsed for 
that.
+AnalysisResults analyze(

can you add some comments about how header filter works? `A predicate that 
receives absolute path or spelling without quotes/brackets, when a phyiscal 
file doesn't exist. No analysis will be performed for headers that satisfy the 
predicate.`



Comment at: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Analysis.h:72
+const HeaderSearch &HS,
+llvm::function_ref HeaderFilter =
+[](llvm::StringRef HeaderPath) {

rather than a default here, can we just do no filtering when `HeaderFilter` is 
null ?



Comment at: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Types.h:137
 
+  llvm::StringRef resolvedPath() const;
+

again some comments here could be useful



Comment at: clang-tools-extra/include-cleaner/lib/Analysis.cpp:65
+const HeaderSearch &HS,
+llvm::function_ref HeaderFilter) {
   const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID());

can you drop `Path` or put it in comments



Comment at: clang-tools-extra/include-cleaner/test/tool.cpp:17
 
+//RUN: clang-include-cleaner -print=changes %s 
--ignore-headers="foobar\.h,foo\.h" -- -I%S/Inputs/ | FileCheck 
--match-full-lines --allow-empty --check-prefix=IGNORE %s
+// IGNORE-NOT: - "foobar.h"

can you ignore one but keep other?

it'd be useful to also test the regex behaviour



Comment at: clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp:106
+public:
+  Action(llvm::function_ref HeaderFilter)
+  : HeaderFilter(HeaderFilter){};

same as above, can you either drop or comment out `Path`



Comment at: clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp:113
   PragmaIncludes PI;
+  llvm::function_ref HeaderFilter;
 

same here for `Path`



Comment at: clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp:157
   case PrintStyle::Changes:
-for (const Include *I : Results.Unused)
+for (const Include *I : Results.Unused) {
   llvm::outs() << "- " << I->quote() << " @Line:" << I->Line << "\n";

nit: braces



Comment at: clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp:225
   }
+  std::vector FilterRegs;
+  llvm::SmallVector Headers;

nit: might be better to extract this into a function like: 
`std::function headerFilter() { /* parses flags, returns a 
null function on failure */ }`



Comment at: clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp:227
+  llvm::SmallVector Headers;
+  llvm::StringRef(IgnoreHeaders).split(Headers, ',', -1, /*KeepEmpty*/ false);
+  for (auto HeaderPattern : Headers) {

s/KeepEmpty/KeepEmpty=/


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153340

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


[PATCH] D154357: [Driver] Recognize powerpc-unknown-eabi as a bare-metal toolchain

2023-07-03 Thread Christian Walther via Phabricator via cfe-commits
cwalther created this revision.
cwalther added reviewers: MaskRay, jroelofs.
cwalther added projects: clang, PowerPC.
Herald added subscribers: luismarques, steven.zhang, s.egerton, shchenz, abidh, 
PkmX, simoncook, asb, kristof.beyls, arichardson, nemanjai.
Herald added a project: All.
cwalther requested review of this revision.
Herald added subscribers: cfe-commits, wangpc.

At Indel, we have been building bare-metal embedded applications that run on 
custom PowerPC and ARM systems with Clang and LLD for a couple of years now, 
using target triples `powerpc-indel-eabi`, `powerpc-indel-eabi750`, 
`arm-indel-eabi`, `aarch64-indel-eabi` (which I just learned from D153430 
 is wrong and should be `aarch64-indel-elf` 
instead, but that’s a different matter). This has worked fine for ARM, but for 
PowerPC we have been unable to call the linker (LLD) through the Clang driver, 
because it would insist on calling GCC as the linker, even when told 
`-fuse-ld=lld`. That does not work for us, there is no GCC around. Instead we 
had to call `ld.lld` directly, introducing some special cases in our build 
system to translate between linker-via-driver and linker-called-directly 
command line arguments. I have now dug into why that is, and found that the 
difference between ARM and PowerPC is that `arm-indel-eabi` hits a special case 
that causes the Clang driver to instantiate a `BareMetal` toolchain that is 
able to call LLD and works the way we need, whereas `powerpc-indel-eabi` lands 
in the default case of a `Generic_ELF` (subclass of `Generic_GCC`) toolchain 
which expects GCC.

It seems to me that maybe anything with OS `none` (although that doesn’t seem 
to be distinguished from `unknown`) or with environment `eabi` should be 
treated as bare-metal, but I don’t have a lot of experience in this regard. 
Since this seems to have been handled on a case-by-case basis in the past (arm 
, riscv , 
aarch64 ), what I am proposing here is to add 
another case to the list to also handle `powerpc[64][le]-unknown-unknown-eabi` 
using the `BareMetal` toolchain, following the example of the existing cases. 
(We don’t care about powerpc64 and powerpc[64]le, but it seemed appropriate to 
lump them in.)

I have run the `check-clang` tests and the patch didn’t break any of them, 
which makes me hopeful. Or do you think that this may break anyone’s usage? 
Should we additionally check for the presence of a `--gcc-toolchain` argument 
like in the RISC-V case? I am new here, so any guidance is appreciated.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154357

Files:
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/test/Driver/baremetal.cpp


Index: clang/test/Driver/baremetal.cpp
===
--- clang/test/Driver/baremetal.cpp
+++ clang/test/Driver/baremetal.cpp
@@ -345,6 +345,58 @@
 // CHECK-RV32IMAFC-SAME: 
"-L[[SYSROOT:[^"]+]]{{[/\\]+}}rv32imafc{{[/\\]+}}ilp32f{{[/\\]+}}lib"
 // CHECK-RV32IMAFC-SAME: 
"-L[[RESOURCE_DIR:[^"]+]]{{[/\\]+}}lib{{[/\\]+}}baremetal{{[/\\]+}}rv32imafc{{[/\\]+}}ilp32f"
 
+// RUN: %clang %s -### --target=powerpc-unknown-eabi 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-PPCEABI %s
+// CHECK-PPCEABI: InstalledDir: [[INSTALLEDDIR:.+]]
+// CHECK-PPCEABI: "-nostdsysteminc"
+// CHECK-PPCEABI-SAME: "-resource-dir" "[[RESOURCE:[^"]+]]"
+// CHECK-PPCEABI-SAME: "-internal-isystem" 
"[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+[^"]*}}include{{[/\\]+}}c++{{[/\\]+}}v1"
+// CHECK-PPCEABI-SAME: "-internal-isystem" "[[RESOURCE]]{{[/\\]+}}include"
+// CHECK-PPCEABI-SAME: "-internal-isystem" 
"[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+[^"]*}}include"
+// CHECK-PPCEABI-NEXT: ld{{(.exe)?}}" "{{.*}}.o" "-Bstatic"
+// CHECK-PPCEABI-SAME: 
"-L[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+[^"]*}}lib"
+// CHECK-PPCEABI-SAME: "-L[[RESOURCE]]{{[/\\]+}}lib{{[/\\]+}}baremetal"
+// CHECK-PPCEABI-SAME: "-lc" "-lm" "-lclang_rt.builtins-powerpc" "-o" "a.out"
+
+// RUN: %clang %s -### --target=powerpc64-unknown-eabi 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-PPC64EABI %s
+// CHECK-PPC64EABI: InstalledDir: [[INSTALLEDDIR:.+]]
+// CHECK-PPC64EABI: "-nostdsysteminc"
+// CHECK-PPC64EABI-SAME: "-resource-dir" "[[RESOURCE:[^"]+]]"
+// CHECK-PPC64EABI-SAME: "-internal-isystem" 
"[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+[^"]*}}include{{[/\\]+}}c++{{[/\\]+}}v1"
+// CHECK-PPC64EABI-SAME: "-internal-isystem" "[[RESOURCE]]{{[/\\]+}}include"
+// CHECK-PPC64EABI-SAME: "-internal-isystem" 
"[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+[^"]*}}include"
+// CHECK-PPC64EABI-NEXT: ld{{(.exe)?}}" "{{.*}}.o" "-Bstatic"
+// CHECK-PPC64EABI-SAME: 
"-L[[INSTALLEDDIR]]{{[/\\]+}}..{{[/\\]+}}lib{{[/\

[PATCH] D154359: [clang] Reset FP options before template instantiation

2023-07-03 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff created this revision.
sepavloff added reviewers: rsmith, rjmccall, aaron.ballman, efriedma.
Herald added a project: All.
sepavloff requested review of this revision.
Herald added a project: clang.

AST nodes that may depend on FP options keep them as a difference
relative to the options outside the AST node. At the moment of
instantiation the FP options may be different from the default values,
defined by command-line option. In such case FP attributes would have
unexpected values. For example, the code:

  template  void func_01(int last, C) {
func_01(last, int());
  }
  void func_02() { func_01(0, 1); }
  #pragma STDC FENV_ACCESS ON

caused compiler crash, because template instantiation takes place at the
end of translation unit, where pragma STDC FENV_ACCESS is in effect. As
a result, code in the template instantiation would use constrained
intrinsics while the function does not have StrictFP attribute.

To solve this problem, FP attributes in Sema must be set to default
values, defined by command line options.

This change resolves https://github.com/llvm/llvm-project/issues/63542.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154359

Files:
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/CodeGen/fp-template.cpp


Index: clang/test/CodeGen/fp-template.cpp
===
--- clang/test/CodeGen/fp-template.cpp
+++ clang/test/CodeGen/fp-template.cpp
@@ -15,4 +15,19 @@
 // CHECK-SAME:  (float noundef %{{.*}}, float noundef %{{.*}}) 
#[[ATTR01:[0-9]+]]{{.*}} {
 // CHECK:   call float @llvm.experimental.constrained.fadd.f32
 
+namespace PR63542 {
+  template  float stable_sort(float x, Compare) {
+float result = x + x;
+stable_sort(x, int());
+return result;
+  }
+  float linkage_wrap() { return stable_sort(0.0, 1); }
+}
+
+// CHECK-LABEL: define {{.*}} float @_ZN7PR6354211stable_sortIiEEffT_(
+// CHECK: fadd float
+
+// Must be at the end of translation unit.
+#pragma STDC FENV_ACCESS ON
+
 // CHECK: attributes #[[ATTR01]] = { {{.*}}strictfp
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -5087,6 +5087,10 @@
 // PushDeclContext because we don't have a scope.
 Sema::ContextRAII savedContext(*this, Function);
 
+FPFeaturesStateRAII SavedFPFeatures(*this);
+CurFPFeatures = FPOptions(getLangOpts());
+FpPragmaStack.CurrentValue = FPOptionsOverride();
+
 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
  TemplateArgs))
   return;


Index: clang/test/CodeGen/fp-template.cpp
===
--- clang/test/CodeGen/fp-template.cpp
+++ clang/test/CodeGen/fp-template.cpp
@@ -15,4 +15,19 @@
 // CHECK-SAME:  (float noundef %{{.*}}, float noundef %{{.*}}) #[[ATTR01:[0-9]+]]{{.*}} {
 // CHECK:   call float @llvm.experimental.constrained.fadd.f32
 
+namespace PR63542 {
+  template  float stable_sort(float x, Compare) {
+float result = x + x;
+stable_sort(x, int());
+return result;
+  }
+  float linkage_wrap() { return stable_sort(0.0, 1); }
+}
+
+// CHECK-LABEL: define {{.*}} float @_ZN7PR6354211stable_sortIiEEffT_(
+// CHECK: fadd float
+
+// Must be at the end of translation unit.
+#pragma STDC FENV_ACCESS ON
+
 // CHECK: attributes #[[ATTR01]] = { {{.*}}strictfp
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -5087,6 +5087,10 @@
 // PushDeclContext because we don't have a scope.
 Sema::ContextRAII savedContext(*this, Function);
 
+FPFeaturesStateRAII SavedFPFeatures(*this);
+CurFPFeatures = FPOptions(getLangOpts());
+FpPragmaStack.CurrentValue = FPOptionsOverride();
+
 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
  TemplateArgs))
   return;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D151696: [x86] Remove CPU_SPECIFIC* MACROs and add getCPUDispatchMangling

2023-07-03 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added inline comments.



Comment at: llvm/lib/TargetParser/X86TargetParser.cpp:378
+  { {"core_3rd_gen_avx"}, CK_IvyBridge, FEATURE_AVX, FeaturesIvyBridge, 'S', 
true },
+  { {"core-avx-i"}, CK_IvyBridge, FEATURE_AVX, FeaturesIvyBridge, '\0', false 
},
   // Haswell microarchitecture based processors.

I'm still not clear on what determines the mangling mode and cpu dispatch flag 
for cpu targets are supposedly the same? For example, none of these ivybridge 
equivalent configs have the same values.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151696

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


[PATCH] D154329: [lldb] Replace llvm::writeFileAtomically with llvm::writeToOutput API.

2023-07-03 Thread Alexey Lapshin via Phabricator via cfe-commits
avl added a comment.

this LGTM. thanks! Please, wait for approve from Jonas. I think someone from 
lldb needs to check whether new error reporting is OK.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154329

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


[PATCH] D153296: [AST] Stop evaluate constant expression if the condition expression which in switch statement contains errors

2023-07-03 Thread Yurong via Phabricator via cfe-commits
yronglin added a comment.

In D153296#4468373 , @aaron.ballman 
wrote:

> In D153296#4459769 , @yronglin 
> wrote:
>
>> Please help me, I have no better idea on this issue, do you have any better 
>> ideas? @erichkeane @shafik
>
> I think what's being suggested is to change `EvaluateDependentExpr()` 
> somewhat along these lines:
>
>   static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
> assert(E->isValueDependent());
>   
> // Note that we have a side effect that matters for constant evaluation.
> bool SideEffects = Info.noteSideEffect();
> // If the reason we're here is because of a recovery expression, we don't
> // want to continue to evaluate further as we will never know what the 
> actual
> // value is.
> if (isa(E))
>   return false;
>   
> // Otherwise, return whether we want to continue after noting the side
> // effects, which should only happen if the expression has errors but 
> isn't
> // a recovery expression on its own.
> assert(E->containsErrors() && "valid value-dependent expression should 
> never "
>   "reach invalid code path.");
> return SideEffects;
>   }
>
> This way, code paths that get down to a `RecoveryExpr` will not continue to 
> evaluate further (as there's really no point -- there's no way to get a 
> reasonable value from from the recovery expression anyway), but the fix isn't 
> specific to just switch statements. After making these changes, you should 
> look for places where `EvaluateDependentExpr()` is being called to try to 
> come up with a test case where that expression is a recovery expression so 
> that we can fill out test coverage beyond just the situation with `switch` 
> from the original report. Does that make sense?
>
> (Marking as requesting changes so it's clear this review isn't yet accepted.)

Thanks a lot! @aaron.ballman , I try to address comments and add more test, 
this case (https://godbolt.org/z/ExPoEKcrf) looks strange, why the do-statement 
missing in the printed AST?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153296

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


[PATCH] D153600: Implement -frecord-command-line for XCOFF

2023-07-03 Thread Jake Egan via Phabricator via cfe-commits
Jake-Egan updated this revision to Diff 536795.
Jake-Egan added a comment.

Thanks for the review @scott.linder. I applied the changes you requested with 
some differences.


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

https://reviews.llvm.org/D153600

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  llvm/include/llvm/CodeGen/AsmPrinter.h
  llvm/include/llvm/MC/MCStreamer.h
  llvm/include/llvm/MC/MCXCOFFStreamer.h
  llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
  llvm/lib/MC/MCAsmStreamer.cpp
  llvm/lib/MC/MCStreamer.cpp
  llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
  llvm/test/CodeGen/PowerPC/aix-command-line-metadata.ll

Index: llvm/test/CodeGen/PowerPC/aix-command-line-metadata.ll
===
--- /dev/null
+++ llvm/test/CodeGen/PowerPC/aix-command-line-metadata.ll
@@ -0,0 +1,22 @@
+; RUN: llc -mtriple powerpc-ibm-aix-xcoff < %s | \
+; RUN: FileCheck --check-prefix=ASM %s
+; RUN: llc -mtriple powerpc64-ibm-aix-xcoff < %s | \
+; RUN: FileCheck --check-prefix=ASM %s
+
+; RUN: not --crash llc -mtriple powerpc-ibm-aix-xcoff -filetype=obj  < %s 2>&1 | \
+; RUN: FileCheck --check-prefix=OBJ %s
+; RUN: not --crash llc -mtriple powerpc64-ibm-aix-xcoff -filetype=obj  < %s 2>&1 | \
+; RUN: FileCheck --check-prefix=OBJ %s
+
+; Verify that llvm.commandline metadata is emitted to .info sections and that the
+; metadata is padded if necessary.
+
+; OBJ: LLVM ERROR: emitXCOFFCInfoSym is not implemented yet on object generation path
+
+; ASM: .info ".GCC.command.line", 0x0030,
+; ASM: .info , 0x40282329, 0x636c616e, 0x67202d63, 0x6f6d6d61, 0x6e64202d, 0x6c696e65
+; ASM: .info , 0x00402823, 0x29736f6d, 0x65746869, 0x6e672065, 0x6c736531, 0x3233
+
+!llvm.commandline = !{!0, !1}
+!0 = !{!"clang -command -line"}
+!1 = !{!"something else123"}
Index: llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
===
--- llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
+++ llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp
@@ -290,6 +290,8 @@
   bool doFinalization(Module &M) override;
 
   void emitTTypeReference(const GlobalValue *GV, unsigned Encoding) override;
+
+  void emitModuleCommandLines(Module &M) override;
 };
 
 } // end anonymous namespace
@@ -2954,6 +2956,26 @@
   return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
 }
 
+void PPCAIXAsmPrinter::emitModuleCommandLines(Module &M) {
+  const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
+  if (!NMD || !NMD->getNumOperands())
+return;
+
+  std::string S;
+  raw_string_ostream RSOS(S);
+  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
+const MDNode *N = NMD->getOperand(i);
+assert(N->getNumOperands() == 1 &&
+   "llvm.commandline metadata entry can have only one operand");
+const MDString *MDS = cast(N->getOperand(0));
+// Add "@(#)" to support retrieving the command line information with the
+// AIX "what" command
+RSOS << "@(#)" << MDS->getString();
+RSOS.write('\0');
+  }
+  OutStreamer->emitXCOFFCInfoSym(".GCC.command.line", RSOS.str());
+}
+
 // Force static initialization.
 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmPrinter() {
   TargetRegistry::RegisterAsmPrinter(getThePPC32Target(),
Index: llvm/lib/MC/MCStreamer.cpp
===
--- llvm/lib/MC/MCStreamer.cpp
+++ llvm/lib/MC/MCStreamer.cpp
@@ -1208,6 +1208,11 @@
  "XCOFF targets");
 }
 
+void MCStreamer::emitXCOFFCInfoSym(StringRef Name, StringRef Metadata) {
+  llvm_unreachable("emitXCOFFCInfoSym is only supported on"
+   "XCOFF targets");
+}
+
 void MCStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
 void MCStreamer::emitELFSymverDirective(const MCSymbol *OriginalSym,
 StringRef Name, bool KeepOriginalSym) {}
Index: llvm/lib/MC/MCAsmStreamer.cpp
===
--- llvm/lib/MC/MCAsmStreamer.cpp
+++ llvm/lib/MC/MCAsmStreamer.cpp
@@ -37,6 +37,7 @@
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/Path.h"
 #include 
+#include 
 
 using namespace llvm;
 
@@ -200,6 +201,7 @@
 const MCSymbol *Trap,
 unsigned Lang, unsigned Reason,
 unsigned FunctionSize, bool hasDebug) override;
+  void emitXCOFFCInfoSym(StringRef Name, StringRef Metadata) override;
 
   void emitELFSize(MCSymbol *Symbol, const MCExpr *Value) override;
   void emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
@@ -966,6 +968,65 @@
   EmitEOL();
 }
 
+void MCAsmStreamer::emitXCOFFCInfoSym(StringRef Name, StringRef Metadata) {
+  const char *InfoDirective = "\t.info ";
+  const char *Separator = ", ";
+  constexpr int WordSize = sizeof(uint32_t);
+
+  // Start by emitting the .info pseudo-op and C_INFO symbol name.
+  OS << InfoDirective;
+  PrintQu

[PATCH] D154180: [OPENMP52] Codegen support for doacross clause.

2023-07-03 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 updated this revision to Diff 536798.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154180

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.h
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/test/OpenMP/ordered_doacross_codegen.c

Index: clang/test/OpenMP/ordered_doacross_codegen.c
===
--- clang/test/OpenMP/ordered_doacross_codegen.c
+++ clang/test/OpenMP/ordered_doacross_codegen.c
@@ -2,13 +2,21 @@
 // RUN: %clang_cc1 -fopenmp -triple x86_64-unknown-unknown -emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-NORMAL
 
+// RUN: %clang_cc1 -verify -fopenmp -triple x86_64-unknown-unknown -emit-llvm %s -o - -fopenmp-version=52 | FileCheck %s --check-prefixes=CHECK,CHECK-NORMAL
 // RUN: %clang_cc1 -verify -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -fopenmp-version=52 -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
 // RUN: %clang_cc1 -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
 
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=52 -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=52 -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
+
 // RUN: %clang_cc1 -verify -fopenmp-simd -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
+// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-version=52 -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
 // RUN: %clang_cc1 -fopenmp-simd -triple x86_64-unknown-unknown -emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp-simd -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
+// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=52 -triple x86_64-unknown-unknown -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=52 -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
 // SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
 // expected-no-diagnostics
 
@@ -51,7 +59,11 @@
 // CHECK-NORMAL-NEXT: call void @__kmpc_doacross_post(ptr [[IDENT]], i32 [[GTID]], ptr [[TMP]])
 // CHECK-IRBUILDER-NEXT: [[GTID1:%.+]] = call i32 @__kmpc_global_thread_num(ptr [[IDENT:@.+]])
 // CHECK-IRBUILDER-NEXT: call void @__kmpc_doacross_post(ptr [[IDENT]], i32 [[GTID1]], ptr [[TMP]])
+#if _OPENMP >= 202111
+#pragma omp ordered doacross(source:)
+#else
 #pragma omp ordered depend(source)
+#endif
 c[i] = c[i] + 1;
 foo();
 // CHECK: call void @foo()
@@ -66,7 +78,11 @@
 // CHECK-NORMAL-NEXT: call void @__kmpc_doacross_wait(ptr [[IDENT]], i32 [[GTID]], ptr [[TMP]])
 // CHECK-IRBUILDER-NEXT: [[GTID2:%.+]] = call i32 @__kmpc_global_thread_num(ptr [[IDENT:@.+]])
 // CHECK-IRBUILDER-NEXT: call void @__kmpc_doacross_wait(ptr [[IDENT]], i32 [[GTID2]], ptr [[TMP]])
+#if _OPENMP >= 202111
+#pragma omp ordered doacross(sink : i - 2)
+#else
 #pragma omp ordered depend(sink : i - 2)
+#endif
 d[i] = a[i - 2];
   }
   // CHECK: call void @__kmpc_for_static_fini(
Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -5839,37 +5839,48 @@
   return Fn;
 }
 
+template 
+static void emitRestoreIP(CodeGenFunction &CGF, const T *C,
+  llvm::OpenMPIRBuilder::InsertPointTy AllocaIP,
+  llvm::OpenMPIRBuilder &OMPBuilder) {
+
+  unsigned NumLoops = C->getNumLoops();
+  QualType Int64Ty = CGF.CGM.getContext().getIntTypeForBitwidth(
+  /*DestWidth=*/64, /*Signed=*/1);
+  llvm::SmallVector StoreValues;
+  for (unsigned I = 0; I < NumLoops; I++) {
+const Expr *CounterVal = C->getLoopData(I);
+assert(CounterVal);
+llvm::Value *StoreValue = CGF.EmitScalarConversion(
+CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
+CounterVal->getExprLoc());
+StoreValues.emplace_back(StoreValue);
+  }
+  OMPDoacrossKind ODK;
+  bool IsDependSource = false;
+  if (ODK.isSource(C))
+IsDependSource = true;
+  CGF.Builder.restoreIP(
+  OMPBuilder.createOrderedDepend(CGF.Builder, AllocaIP, NumLoops,
+

[PATCH] D154180: [OPENMP52] Codegen support for doacross clause.

2023-07-03 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 added inline comments.



Comment at: clang/lib/CodeGen/CGOpenMPRuntime.cpp:11405-11406
+  llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
+  const OMPDependClause *DepC = dyn_cast(C);
+  const OMPDoacrossClause *DoC = dyn_cast(C);
+  if ((DoC && DoC->getDependenceType() == OMPC_DOACROSS_source) ||

ABataev wrote:
> 1. const auto *
> 2. Can you try torework it to make it more C++-ish? Use template deduction to 
> avoid runtime dyn_casts.
> e.g. something like:
> ```
> namespace {
> template 
> class OMPDoacrossKind {
> public:
> bool isSink(const T *) {return false;}
> }
> }
> template <>
> class OMPDoacrossKInd {
> public:
> bool isSink(const OMPDependClause* C) {return C->getDependenceType();}
> }
> ...
> ```
> and use `if (OMPDoacrossKInd::isSink(C)) RTLFn = ...` and same for `Source`
Good idea!!!  Thank you so much.  Changed.



Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:5859-5868
+  const auto DOC = dyn_cast(C);
+  const auto DC = dyn_cast(C);
+  bool IsDependSource = false;
+  if ((DC && DC->getDependencyKind() == OMPC_DEPEND_source) ||
+  (DOC && DOC->getDependenceType() == OMPC_DOACROSS_source))
+IsDependSource = true;
+  CGF.Builder.restoreIP(

ABataev wrote:
> Same, use template-based analysis instead of runtime-based.
Thanks.  Changed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154180

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


[PATCH] D153600: Implement -frecord-command-line for XCOFF

2023-07-03 Thread Jake Egan via Phabricator via cfe-commits
Jake-Egan marked 6 inline comments as done.
Jake-Egan added inline comments.



Comment at: llvm/lib/MC/MCAsmStreamer.cpp:1022
+  if (PaddingSize) {
+assert(PaddedSize - Index == WordSize);
+std::array LastWord = {0};

I changed the assert that you requested because it would always fail:

```
assert(Length - Index == MetadataPaddingSize);
```




Comment at: llvm/lib/MC/MCAsmStreamer.cpp:980
+  size_t MetadataSize = Metadata.size();
+  uint32_t MetadataPaddingSize = 3 - (MetadataSize - 1) % 4;
+

scott.linder wrote:
> scott.linder wrote:
> > I couldn't quickly find a reference for the alignment requirement, but it 
> > seems like there is an additional requirement that the length must also be 
> > non-zero, not just even?
> > 
> > If so, can you update the comment?
> > 
> > I would also rather explicitly use `alignTo` and `max` to express this (see 
> > suggestion), but if we don't expect the optimizer to clean it up I'm fine 
> > with the more terse version.
> Can you factor this out at function scope? It gets repeated below
The length can be zero. See second paragraph of the comment section: 
https://www.ibm.com/docs/en/aix/7.2?topic=formats-xcoff-object-file-format#XCOFF__a1pyfk2b4joyc__title__1


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

https://reviews.llvm.org/D153600

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


[PATCH] D153600: Implement -frecord-command-line for XCOFF

2023-07-03 Thread Jake Egan via Phabricator via cfe-commits
Jake-Egan marked an inline comment as done.
Jake-Egan added inline comments.



Comment at: llvm/lib/MC/MCAsmStreamer.cpp:986
+
+  // If there's no metadata, the length is 0.
+  if (MetadataSize == 0) {

Handled the 0 length case here.


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

https://reviews.llvm.org/D153600

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


[PATCH] D153296: [AST] Stop evaluate constant expression if the condition expression which in switch statement contains errors

2023-07-03 Thread Yurong via Phabricator via cfe-commits
yronglin updated this revision to Diff 536802.
yronglin added a comment.

Address comment.

- Change `EvaluateDependentExpr`.
- Add more test for do/while/for/return/ctor.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153296

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/AST/ExprConstant.cpp
  clang/test/SemaCXX/constexpr-function-recovery-crash.cpp

Index: clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
===
--- clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
+++ clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
@@ -78,6 +78,132 @@
 constexpr int test12() { return "wrong"; } // expected-error {{cannot initialize return object of type 'int'}}
 constexpr int force12 = test12();  // expected-error {{must be initialized by a constant}}
 
+constexpr int test13() {
+switch (invalid_value) { // expected-error {{use of undeclared identifier}}
+case 0:
+return 7;
+default:
+break;
+}
+return 0;
+}
+
+static_assert(test13(), "should not crash"); // expected-error {{static assertion expression is not an integral constant expression}}
+
+constexpr int test14() {
+int sum = 0;
+for (int i = 0; i < invalid_value; ++i) // expected-error {{use of undeclared identifier}}
+sum = sum + i;
+return sum;
+}
+
+static_assert(test14(), "should not crash"); // expected-error {{static assertion failed due to requirement}}
+
+constexpr int test15() {
+int sum = 0;
+for (int i = 0; i < 10; i += invalid_value) // expected-error {{use of undeclared identifier}}
+sum = sum + i;
+return sum;
+}
+
+static_assert(test15(), "should not crash"); // expected-error {{static assertion expression is not an integral constant expression}}
+
+constexpr int test16() {
+int sum = 0;
+for (int i = invalid_value; i < 10; ++i) // expected-error {{use of undeclared identifier}}
+sum = sum + i;
+return sum;
+}
+
+static_assert(test16(), "should not crash"); // expected-error {{static assertion expression is not an integral constant expression}}
+
+constexpr int test17() {
+int sum = 0, i = 0;
+do
+  sum += i;
+while (invalid_value); // expected-error {{use of undeclared identifier}}
+return sum;
+}
+
+static_assert(test17(), "should not crash"); // expected-error {{static assertion failed due to requirement}}
+
+constexpr int test18() {
+  int sum = 0, i = 0;
+  while (invalid_value) // expected-error {{use of undeclared identifier}}
+sum += i;
+  return sum;
+}
+
+static_assert(test18(), "should not crash"); // expected-error {{static assertion expression is not an integral constant expression}}
+
+constexpr int test19() {
+struct Test19 {
+int a[2] = {0, 1};
+constexpr const int *begin() const {
+return invalid_value;  // expected-error {{use of undeclared identifier}}
+}
+constexpr const int *end() const {
+return a + 2;
+}
+};
+
+int sum = 0;
+Test19 t;
+for (const auto v : t) {
+sum += v;
+}
+return sum;
+}
+
+static_assert(test19(), "should not crash"); // expected-error {{static assertion expression is not an integral constant expression}}
+
+constexpr int test20() {
+struct Test20 {
+int a[2] = {0, 1};
+constexpr const int *begin() const {
+return a;
+}
+constexpr const int *end() const {
+return invalid_value;  // expected-error {{use of undeclared identifier}}
+}
+};
+
+int sum = 0;
+Test20 t;
+for (const auto v : t) {
+sum += v;
+}
+return sum;
+}
+
+static_assert(test20(), "should not crash"); // expected-error {{static assertion expression is not an integral constant expression}}
+
+constexpr int test21() {
+  return invalid_value; // expected-error {{use of undeclared identifier}}
+}
+
+static_assert(test21(), "should not crash"); // expected-error {{static assertion expression is not an integral constant expression}}
+
+constexpr int test22() {
+  struct Test22 {
+int value = invalid_value; // expected-error {{use of undeclared identifier}}
+  };
+  return Test22().value;
+}
+
+static_assert(test22(), "should not crash"); // expected-error {{static assertion expression is not an integral constant expression}}
+
+constexpr int test23() {
+  struct Test23 {
+int value;
+constexpr Test23(int v) : value(v) {}
+constexpr Test23(int a, int b) : Test23(a * b * invalid_value) {} // expected-error {{use of undeclared identifier}}
+  };
+  return Test23(1, 2).value;
+}
+
+static_assert(test23(), "should not crash"); // expected-error {{static assertion expression is not an integral constant expression}}
+
 #define TEST_EVALUATE(Name, X) \
   constexpr int testEvaluate##Name() { \
 X return 0;\
Index: 

[PATCH] D154283: [clang-tidy] Fix width/precision argument order in modernize-use-std-print

2023-07-03 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL added inline comments.



Comment at: clang-tools-extra/clang-tidy/utils/FormatStringConverter.h:73
+  // puts the width and preicision first.
+  std::vector> ArgRotates;
+

mikecrowe wrote:
> PiotrZSL wrote:
> > mikecrowe wrote:
> > > PiotrZSL wrote:
> > > > NOTE: You can use std::pair here.
> > > True, but in my mind `std::pair` only exists because `std::tuple` 
> > > couldn't be implemented in the C++98.
> > > 
> > > I was going to change it to use `std::pair` anyway, but I notice that I 
> > > already use `std::tuple` for `ArgFixes` just above. Should I change both 
> > > of them?
> > It will be compiled to same thing anyway. So it's up to you. Keep it 
> > consistent.
> > I personally use std::pair for 2 arguments, and std::tuple for more than 2.
> > But to be honest probably better would be to introduce some structure so 
> > that those two `unsigned` could be named. And probably same for ArgFixes, 
> > but there we got different types, so it's not a big problem.
> I think that you're probably right, but the names won't be used from the call 
> site since I use structured binding there. Do you mind if I do both together 
> in a separate commit?
Not a problem, lets leave it for a next change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154283

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


[clang-tools-extra] 2806cf4 - [clang-tidy] Fix width/precision argument order in modernize-use-std-print

2023-07-03 Thread Piotr Zegar via cfe-commits

Author: Mike Crowe
Date: 2023-07-03T16:39:04Z
New Revision: 2806cf4b5430ad6d4d5aa2d501aea1de67272876

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

LOG: [clang-tidy] Fix width/precision argument order in modernize-use-std-print

Victor Zverovich pointed out[1] that printf takes the field width and
precision arguments before the value to be printed whereas std::print
takes the value first (unless positional arguments are used.) Many of
the test cases in use-std-print.cpp were incorrect.

Teach the check to rotate the arguments when required to correct
this. Correct the test cases and add more.

[1] https://github.com/fmtlib/fmt/pull/3515#issuecomment-1615259893

Reviewed By: PiotrZSL

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
clang-tools-extra/clang-tidy/utils/FormatStringConverter.h
clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp 
b/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
index f12fa84ec6b141..3e6442c5fd63c1 100644
--- a/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
+++ b/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
@@ -340,6 +340,22 @@ void FormatStringConverter::emitPrecision(const 
PrintfSpecifier &FS,
   }
 }
 
+void FormatStringConverter::maybeRotateArguments(const PrintfSpecifier &FS) {
+  unsigned ArgCount = 0;
+  const OptionalAmount FieldWidth = FS.getFieldWidth();
+  const OptionalAmount FieldPrecision = FS.getPrecision();
+
+  if (FieldWidth.getHowSpecified() == OptionalAmount::Arg &&
+  !FieldWidth.usesPositionalArg())
+++ArgCount;
+  if (FieldPrecision.getHowSpecified() == OptionalAmount::Arg &&
+  !FieldPrecision.usesPositionalArg())
+++ArgCount;
+
+  if (ArgCount)
+ArgRotates.emplace_back(FS.getArgIndex() + ArgsOffset, ArgCount);
+}
+
 void FormatStringConverter::emitStringArgument(const Expr *Arg) {
   // If the argument is the result of a call to std::string::c_str() or
   // data() with a return type of char then we can remove that call and
@@ -531,6 +547,7 @@ bool FormatStringConverter::convertArgument(const 
PrintfSpecifier &FS,
 
   emitFieldWidth(FS, FormatSpec);
   emitPrecision(FS, FormatSpec);
+  maybeRotateArguments(FS);
 
   if (!emitType(FS, Arg, FormatSpec))
 return false;
@@ -682,5 +699,22 @@ void FormatStringConverter::applyFixes(DiagnosticBuilder 
&Diag,
 if (!ArgText.empty())
   Diag << FixItHint::CreateReplacement(Call->getSourceRange(), ArgText);
   }
+
+  // ArgCount is one less than the number of arguments to be rotated.
+  for (auto [ValueArgIndex, ArgCount] : ArgRotates) {
+assert(ValueArgIndex < NumArgs);
+assert(ValueArgIndex > ArgCount);
+
+// First move the value argument to the right place.
+Diag << tooling::fixit::createReplacement(*Args[ValueArgIndex - ArgCount],
+  *Args[ValueArgIndex], *Context);
+
+// Now shift down the field width and precision (if either are present) to
+// accommodate it.
+for (size_t Offset = 0; Offset < ArgCount; ++Offset)
+  Diag << tooling::fixit::createReplacement(
+  *Args[ValueArgIndex - Offset], *Args[ValueArgIndex - Offset - 1],
+  *Context);
+  }
 }
 } // namespace clang::tidy::utils

diff  --git a/clang-tools-extra/clang-tidy/utils/FormatStringConverter.h 
b/clang-tools-extra/clang-tidy/utils/FormatStringConverter.h
index b246013c24c457..200e530b40810b 100644
--- a/clang-tools-extra/clang-tidy/utils/FormatStringConverter.h
+++ b/clang-tools-extra/clang-tidy/utils/FormatStringConverter.h
@@ -67,6 +67,11 @@ class FormatStringConverter
   std::vector> ArgFixes;
   std::vector ArgCStrRemovals;
 
+  // Argument rotations to cope with the fact that std::print puts the value to
+  // be formatted first and the width and precision afterwards whereas printf
+  // puts the width and preicision first.
+  std::vector> ArgRotates;
+
   void emitAlignment(const PrintfSpecifier &FS, std::string &FormatSpec);
   void emitSign(const PrintfSpecifier &FS, std::string &FormatSpec);
   void emitAlternativeForm(const PrintfSpecifier &FS, std::string &FormatSpec);
@@ -81,6 +86,8 @@ class FormatStringConverter
   bool convertArgument(const PrintfSpecifier &FS, const Expr *Arg,
std::string &StandardFormatString);
 
+  void maybeRotateArguments(const PrintfSpecifier &FS);
+
   bool HandlePrintfSpecifier(const PrintfSpecifier &FS,
  const char *StartSpecifier, unsigned SpecifierLen,
  const TargetInfo &Target) override;

diff  --git 
a/clang-tools-extra/test

[PATCH] D154283: [clang-tidy] Fix width/precision argument order in modernize-use-std-print

2023-07-03 Thread Piotr Zegar via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2806cf4b5430: [clang-tidy] Fix width/precision argument 
order in modernize-use-std-print (authored by mikecrowe, committed by PiotrZSL).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154283

Files:
  clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
  clang-tools-extra/clang-tidy/utils/FormatStringConverter.h
  clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp
@@ -1024,7 +1024,7 @@
 
   printf("Right-justified integer with field width argument %*d after\n", 5, 424242);
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
-  // CHECK-FIXES: std::println("Right-justified integer with field width argument {:{}} after", 5, 424242);
+  // CHECK-FIXES: std::println("Right-justified integer with field width argument {:{}} after", 424242, 5);
 
   printf("Right-justified integer with field width argument %2$*1$d after\n", 5, 424242);
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
@@ -1061,7 +1061,7 @@
 
   printf("Left-justified integer with field width argument %-*d after\n", 5, 424242);
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
-  // CHECK-FIXES: std::println("Left-justified integer with field width argument {:<{}} after", 5, 424242);
+  // CHECK-FIXES: std::println("Left-justified integer with field width argument {:<{}} after", 424242, 5);
 
   printf("Left-justified integer with field width argument %2$-*1$d after\n", 5, 424242);
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
@@ -1087,15 +1087,15 @@
 
   printf("Hello %.*f after\n", 10, 3.14159265358979323846);
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
-  // CHECK-FIXES: std::println("Hello {:.{}f} after", 10, 3.14159265358979323846);
+  // CHECK-FIXES: std::println("Hello {:.{}f} after", 3.14159265358979323846, 10);
 
   printf("Hello %10.*f after\n", 3, 3.14159265358979323846);
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
-  // CHECK-FIXES: std::println("Hello {:10.{}f} after", 3, 3.14159265358979323846);
+  // CHECK-FIXES: std::println("Hello {:10.{}f} after", 3.14159265358979323846, 3);
 
   printf("Hello %*.*f after\n", 10, 4, 3.14159265358979323846);
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
-  // CHECK-FIXES: std::println("Hello {:{}.{}f} after", 10, 4, 3.14159265358979323846);
+  // CHECK-FIXES: std::println("Hello {:{}.{}f} after", 3.14159265358979323846, 10, 4);
 
   printf("Hello %1$.*2$f after\n", 3.14159265358979323846, 4);
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
@@ -1112,9 +1112,33 @@
 }
 
 void printf_field_width_and_precision() {
-  printf("Hello %1$*2$.*3$f after\n", 3.14159265358979323846, 4, 2);
+  printf("width only:%*d width and precision:%*.*f precision only:%.*f\n", 3, 42, 4, 2, 3.14159265358979323846, 5, 2.718);
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
-  // CHECK-FIXES: std::println("Hello {0:{1}.{2}f} after", 3.14159265358979323846, 4, 2);
+  // CHECK-FIXES: std::println("width only:{:{}} width and precision:{:{}.{}f} precision only:{:.{}f}", 42, 3, 3.14159265358979323846, 4, 2, 2.718, 5);
+
+  printf("width and precision positional:%1$*2$.*3$f after\n", 3.14159265358979323846, 4, 2);
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
+  // CHECK-FIXES: std::println("width and precision positional:{0:{1}.{2}f} after", 3.14159265358979323846, 4, 2);
+
+  const int width = 10, precision = 3;
+  printf("width only:%3$*1$d width and precision:%4$*1$.*2$f precision only:%5$.*2$f\n", width, precision, 42, 3.1415926, 2.718);
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::println' instead of 'printf' [modernize-use-std-print]
+  // CHECK-FIXES: std::println("width only:{2:{0}} width and precision:{3:{0}.{1}f} precision only:{4:.{1}f}", width, precision, 42, 3.1415926, 2.718);
+}
+
+void fprintf_field_width_and_precision() {
+  fprintf(stderr, "width only:%*d width and precision:%*.*f precision only:%.*f\n", 3, 42, 4, 2, 3.14159265358979323846, 5, 2.718);
+  // CHECK-MESSAGES: [[@LINE-1

[clang-tools-extra] ce2d44b - [clang-tidy] Accessing checks not done for aliases of `std::array`

2023-07-03 Thread Piotr Zegar via cfe-commits

Author: Jorge Pinto Sousa
Date: 2023-07-03T16:43:08Z
New Revision: ce2d44b0ab6da147931e9711e01d44a672ec3854

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

LOG: [clang-tidy] Accessing checks not done for aliases of `std::array`

Index accessing checks are not performed for aliases
of `std::array`, as only `std::array` itself seems to be checked.

This patch aims to extend it for aliases such as:
 `using MyArray = std::array;`

Reviewed By: PiotrZSL

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

Added: 


Modified: 

clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
index da7e6a32167901..fbc3cd314ee53a 100644
--- 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
@@ -49,7 +49,8 @@ void 
ProBoundsConstantArrayIndexCheck::registerMatchers(MatchFinder *Finder) {
   cxxOperatorCallExpr(
   hasOverloadedOperatorName("[]"),
   hasArgument(
-  0, hasType(cxxRecordDecl(hasName("::std::array")).bind("type"))),
+  0, hasType(hasUnqualifiedDesugaredType(recordType(hasDeclaration(
+ cxxRecordDecl(hasName("::std::array")).bind("type")),
   hasArgument(1, expr().bind("index")))
   .bind("expr"),
   this);

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 84333f6cb347bf..7c6efe60a013ae 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -321,6 +321,10 @@ Changes in existing checks
   :doc:`cppcoreguidelines-use-default-member-init
   ` instead.
 
+- Improved :doc:`cppcoreguidelines-pro-bounds-constant-array-index
+  ` check
+  to cover type aliases of ``std::array``.
+
 - Fixed a false positive in :doc:`cppcoreguidelines-slicing
   ` check when warning would be
   emitted in constructor for virtual base class initialization.

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
index 91c7fc1e3db597..e689677578f8d0 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
@@ -44,6 +44,28 @@ void f(std::array a, int pos) {
   a[1] = 3; // OK, constant index and inside bounds
   a[9] = 3; // OK, constant index and inside bounds
   a[const_index(6)] = 3; // OK, constant index and inside bounds
+
+  using MyArray = std::array;
+  MyArray m{};
+  m [ pos / 2 /*comment*/] = 1;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not use array subscript when 
the index is not an integer constant expression 
[cppcoreguidelines-pro-bounds-constant-array-index]
+  int jj = m[pos - 1];
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: do not use array subscript when 
the index is not an integer constant expression
+
+  m.at(pos-1) = 2; // OK, at() instead of []
+  gsl::at(m, pos-1) = 2; // OK, gsl::at() instead of []
+  m[-1] = 3;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: std::array<> index -1 is 
negative [cppcoreguidelines-pro-bounds-constant-array-index]
+  m[10] = 4;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: std::array<> index 10 is past 
the end of the array (which contains 10 elements) 
[cppcoreguidelines-pro-bounds-constant-array-index]
+
+  m[const_index(7)] = 3;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: std::array<> index 10 is past 
the end of the array (which contains 10 elements)
+
+  m[0] = 3; // OK, constant index and inside bounds
+  m[1] = 3; // OK, constant index and inside bounds
+  m[9] = 3; // OK, constant index and inside bounds
+  m[const_index(6)] = 3; // OK, constant index and inside bounds
 }
 
 void g() {



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


[PATCH] D154297: clang-tidy: accessing checks not done for aliases of `std::array`

2023-07-03 Thread Piotr Zegar via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGce2d44b0ab6d: [clang-tidy] Accessing checks not done for 
aliases of `std::array` (authored by sousajo, committed by PiotrZSL).

Changed prior to commit:
  https://reviews.llvm.org/D154297?vs=536622&id=536805#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154297

Files:
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
@@ -44,6 +44,28 @@
   a[1] = 3; // OK, constant index and inside bounds
   a[9] = 3; // OK, constant index and inside bounds
   a[const_index(6)] = 3; // OK, constant index and inside bounds
+
+  using MyArray = std::array;
+  MyArray m{};
+  m [ pos / 2 /*comment*/] = 1;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not use array subscript when 
the index is not an integer constant expression 
[cppcoreguidelines-pro-bounds-constant-array-index]
+  int jj = m[pos - 1];
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: do not use array subscript when 
the index is not an integer constant expression
+
+  m.at(pos-1) = 2; // OK, at() instead of []
+  gsl::at(m, pos-1) = 2; // OK, gsl::at() instead of []
+  m[-1] = 3;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: std::array<> index -1 is 
negative [cppcoreguidelines-pro-bounds-constant-array-index]
+  m[10] = 4;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: std::array<> index 10 is past 
the end of the array (which contains 10 elements) 
[cppcoreguidelines-pro-bounds-constant-array-index]
+
+  m[const_index(7)] = 3;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: std::array<> index 10 is past 
the end of the array (which contains 10 elements)
+
+  m[0] = 3; // OK, constant index and inside bounds
+  m[1] = 3; // OK, constant index and inside bounds
+  m[9] = 3; // OK, constant index and inside bounds
+  m[const_index(6)] = 3; // OK, constant index and inside bounds
 }
 
 void g() {
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -321,6 +321,10 @@
   :doc:`cppcoreguidelines-use-default-member-init
   ` instead.
 
+- Improved :doc:`cppcoreguidelines-pro-bounds-constant-array-index
+  ` check
+  to cover type aliases of ``std::array``.
+
 - Fixed a false positive in :doc:`cppcoreguidelines-slicing
   ` check when warning would be
   emitted in constructor for virtual base class initialization.
Index: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
===
--- 
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
+++ 
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
@@ -49,7 +49,8 @@
   cxxOperatorCallExpr(
   hasOverloadedOperatorName("[]"),
   hasArgument(
-  0, hasType(cxxRecordDecl(hasName("::std::array")).bind("type"))),
+  0, hasType(hasUnqualifiedDesugaredType(recordType(hasDeclaration(
+ cxxRecordDecl(hasName("::std::array")).bind("type")),
   hasArgument(1, expr().bind("index")))
   .bind("expr"),
   this);


Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-bounds-constant-array-index.cpp
@@ -44,6 +44,28 @@
   a[1] = 3; // OK, constant index and inside bounds
   a[9] = 3; // OK, constant index and inside bounds
   a[const_index(6)] = 3; // OK, constant index and inside bounds
+
+  using MyArray = std::array;
+  MyArray m{};
+  m [ pos / 2 /*comment*/] = 1;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not use array subscript when the index is not an integer constant expression [cppcoreguidelines-pro-bounds-constant-array-index]
+  int jj = m[pos - 1];
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: do not use array subscript when the index is not an integer constant expression
+
+  m.at(pos-1) = 2; // OK, at() instead of []
+  gsl::at(m, pos-1) = 2; // OK, gsl::at() instead of []
+  m[-1] = 3;
+  // CHECK-MESSAGES: :[[

[PATCH] D135849: [llvm] Return canonical virtual path from `RedirectingFileSystem`

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

> You mean diagnosing whenever the spelling in the VFS definition differs from 
> its realpath?

Right, this would be ideal, but may be too expensive in practice.

> How could we make that work with symlinks in place?

Ah right, we are intentionally allowing symlinks in the VFS path (e.g. 
Foo.framework/Headers) because we don't correctly handle symlink resolution in 
the VFS itself.

You can get the canonical spelling of a symlink in a couple of ways: you can 
readdir the parent directory and find all case-insensitive matches.  If there 
is only 1, that's the spelling, if there are more than 1  then it's a 
case-sensitive filesystem and the original path must be correct.  Another way 
that is OS-specific is on Darwin you can `open(..., O_SYMLINK)` the path 
component to open the symlink itself and then `fcntl(..., F_GETPATH, ...)` to 
get its realpath.  Both of these approaches require handling each component of 
the path individually, though each step is cacheable.  Not sure if there are 
any better ways.

As I said, not sure we can afford to diagnose this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135849

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


[PATCH] D154180: [OPENMP52] Codegen support for doacross clause.

2023-07-03 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/CodeGen/CGOpenMPRuntime.cpp:11410
   } else {
-assert(C->getDependencyKind() == OMPC_DEPEND_sink);
+assert(ODK.isSink(C));
 RTLFn = OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),

Add a message, please



Comment at: clang/lib/CodeGen/CGOpenMPRuntime.h:2279
+public:
+  bool isSink(const T *) { return false; }
+};

Add isSOurce 



Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:5860-5862
+  bool IsDependSource = false;
+  if (ODK.isSource(C))
+IsDependSource = true;

bool IsDependSource = ODK.isSource(C);


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154180

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


[PATCH] D154366: [clang][ExprConstant] Print template arguments when describing stack frame

2023-07-03 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet created this revision.
hazohelet added reviewers: aaron.ballman, tbaeder, cjdb, shafik.
Herald added a project: All.
hazohelet requested review of this revision.
Herald added a project: clang.

This patch adds additional printing of template argument list when the 
described function is a template specialization.
This can be useful when handling complex template functions in constexpr 
evaluator.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154366

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/AST/ExprConstant.cpp
  clang/test/AST/Interp/literals.cpp
  clang/test/SemaCXX/builtin-align-cxx.cpp
  clang/test/SemaCXX/constant-expression-cxx11.cpp
  clang/test/SemaCXX/constant-expression-cxx14.cpp
  clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp
  clang/test/SemaCXX/cxx2b-consteval-propagate.cpp

Index: clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
===
--- clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
+++ clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
@@ -45,7 +45,7 @@
 }
 
 int i = hh(); // expected-error {{call to immediate function 'examples::hh' is not a constant expression}} \
-   // expected-note {{in call to 'hh()'}}
+   // expected-note {{in call to 'hh()'}}
 
 struct A {
   int x;
Index: clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp
===
--- clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp
+++ clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp
@@ -117,11 +117,11 @@
 
   constexpr pad pir{4, 4};
   // expected-error@+2 {{constexpr variable 'piw' must be initialized by a constant expression}}
-  // expected-note@+1 {{in call to 'bit_cast(pir)'}}
+  // expected-note@+1 {{in call to 'bit_cast(pir)'}}
   constexpr int piw = bit_cast(pir).x;
 
   // expected-error@+2 {{constexpr variable 'bad' must be initialized by a constant expression}}
-  // expected-note@+1 {{in call to 'bit_cast(pir)'}}
+  // expected-note@+1 {{in call to 'bit_cast(pir)'}}
   constexpr no_pad bad = bit_cast(pir);
 
   constexpr pad fine = bit_cast(no_pad{1, 2, 3, 4, 5});
Index: clang/test/SemaCXX/constant-expression-cxx14.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx14.cpp
+++ clang/test/SemaCXX/constant-expression-cxx14.cpp
@@ -1038,7 +1038,7 @@
 void foo() __attribute__((enable_if(sum(Cs) == 'a' + 'b', "")));
 void run() { foo(); }
 
-static_assert(sum(Cs) == 'a' + 'b', ""); // expected-error{{not an integral constant expression}} expected-note{{in call to 'sum(Cs)'}}
+static_assert(sum(Cs) == 'a' + 'b', ""); // expected-error{{not an integral constant expression}} expected-note{{in call to 'sum<2>(Cs)'}}
 constexpr int S = sum(Cs); // expected-error{{must be initialized by a constant expression}} expected-note{{in call}}
 }
 
Index: clang/test/SemaCXX/constant-expression-cxx11.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx11.cpp
+++ clang/test/SemaCXX/constant-expression-cxx11.cpp
@@ -1781,7 +1781,7 @@
   static_assert(get(arr, 1) == 1, "");
   static_assert(get(arr, 4) == 4, "");
   static_assert(get(arr, 0) == 4, ""); // expected-error{{not an integral constant expression}} \
-  // expected-note{{in call to 'get(arr, 0)'}}
+  // expected-note{{in call to 'get(arr, 0)'}}
 }
 
 namespace std { struct type_info; }
Index: clang/test/SemaCXX/builtin-align-cxx.cpp
===
--- clang/test/SemaCXX/builtin-align-cxx.cpp
+++ clang/test/SemaCXX/builtin-align-cxx.cpp
@@ -137,26 +137,26 @@
 constexpr long const_value(long l) { return l; }
 // Check some invalid values during constant-evaluation
 static_assert(wrap_align_down(1, const_value(-1)), ""); // expected-error{{not an integral constant expression}}
-// expected-note@-1{{in call to 'wrap_align_down(1, -1)'}}
+// expected-note@-1{{in call to 'wrap_align_down(1, -1)'}}
 static_assert(wrap_align_up(1, const_value(-2)), ""); // expected-error{{not an integral constant expression}}
-// expected-note@-1{{in call to 'wrap_align_up(1, -2)'}}
+// expected-note@-1{{in call to 'wrap_align_up(1, -2)'}}
 static_assert(wrap_is_aligned(1, const_value(-3)), ""); // expected-error{{not an integral constant expression}}
-// expected-note@-1{{in call to 'wrap_is_aligned(1, -3)'}}
+// expected-note@-1{{in call to 'wrap_is_aligned(1, -3)'}}
 static_assert(wrap_align_down(1, const_value(17)), ""); // expected-error{{not an integral constant expression}}
-// expected-note@-1{{in call to 'wrap_align_down(1, 17)'}}
+// expected-note@-1{{in call to 'wrap_align_down(1, 17)'}}
 static_assert(wrap_align_up(1, const_value(18)), ""); // expected-error{{not an integral constant expression}}
-// expected-note@-1{{in call to 'wrap_align_up(1, 18)'}}
+// expected-note@-1{{in call to 'wrap_align_up(1, 18)'}}
 static_

[PATCH] D154368: [Clang] Fix constraint checking of non-generic lambdas.

2023-07-03 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin created this revision.
Herald added a project: All.
cor3ntin requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

A lambda call operator can be a templated entity -
and therefore have constraints while not being a function template

  template void f() {
[]() requires false { }();
  }

In that case, we would check the constraints of the call operator
which is non-viable. However, we would find a viable candidate:
the conversion operator to function pointer, and use it to
perform a surrogate call.
These constraints were not checked because:

- We never check the constraints of surrogate functions
- The lambda conversion operator has non constraints.

>From the wording, it is not clear what the intent is but
it seems reasonable to expect the constraints of the lambda conversion
operator to be checked and it is consistent with GCC and MSVC.

This patch also improve the diagnostics for constraint failure
on surrogate calls.

Fixes #63181


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154368

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/test/SemaTemplate/concepts.cpp

Index: clang/test/SemaTemplate/concepts.cpp
===
--- clang/test/SemaTemplate/concepts.cpp
+++ clang/test/SemaTemplate/concepts.cpp
@@ -410,8 +410,8 @@
 
 template 
 void SingleDepthReferencesTopLambda(U &&u) {
-  []()
-requires IsInt
+  []() // #SDRTL_OP
+requires IsInt // #SDRTL_REQ
   {}();
 }
 
@@ -434,8 +434,8 @@
 
 template 
 void DoubleDepthReferencesTopLambda(U &&u) {
-  []() { []()
-   requires IsInt
+  []() { []() // #DDRTL_OP
+   requires IsInt // #DDRTL_REQ
  {}(); }();
 }
 
@@ -459,10 +459,11 @@
 
 template 
 void DoubleDepthReferencesAllLambda(U &&u) {
-  [](U &&u2) {
-[](U && u3)
-  requires IsInt &&
-   IsInt && IsInt
+  [](U &&u2) { // #DDRAL_OP1
+[](U && u3) // #DDRAL_OP2
+  requires IsInt // #DDRAL_REQ
+&& IsInt
+&& IsInt
 {}(u2);
   }(u);
 }
@@ -484,8 +485,8 @@
 template 
 void ChecksLocalVar(T x) {
   T Local;
-  []()
-requires(IsInt)
+  []() // #CLV_OP
+requires(IsInt) // #CLV_REQ
   {}();
 }
 
@@ -529,6 +530,11 @@
   SingleDepthReferencesTopLambda(v);
   // FIXME: This should error on constraint failure! (Lambda!)
   SingleDepthReferencesTopLambda(will_fail);
+  // expected-note@-1{{in instantiation of function template specialization}}
+  // expected-error@#SDRTL_OP{{no matching function for call to object of type}}
+  // expected-note@#SDRTL_OP{{candidate function not viable: constraints not satisfied}}
+  // expected-note@#SDRTL_REQ{{because 'IsInt' evaluated to false}}
+
   DoubleDepthReferencesTop(v);
   DoubleDepthReferencesTop(will_fail);
   // expected-error@#DDRT_CALL{{no matching function for call to object of type 'lc2'}}
@@ -538,8 +544,12 @@
   // expected-note@#DDRT_REQ{{'IsInt' evaluated to false}}
 
   DoubleDepthReferencesTopLambda(v);
-  // FIXME: This should error on constraint failure! (Lambda!)
   DoubleDepthReferencesTopLambda(will_fail);
+  // expected-note@-1{{in instantiation of function template specialization}}
+  // expected-error@#DDRTL_OP{{no matching function for call to object of type}}
+  // expected-note@#DDRTL_OP{{candidate function not viable: constraints not satisfied}}
+  // expected-note@#DDRTL_OP{{while substituting into a lambda expression here}}
+  // expected-note@#DDRTL_REQ{{because 'IsInt' evaluated to false}}
   DoubleDepthReferencesAll(v);
   DoubleDepthReferencesAll(will_fail);
   // expected-error@#DDRA_CALL{{no matching function for call to object of type 'lc2'}}
@@ -549,8 +559,12 @@
   // expected-note@#DDRA_REQ{{'IsInt' evaluated to false}}
 
   DoubleDepthReferencesAllLambda(v);
-  // FIXME: This should error on constraint failure! (Lambda!)
   DoubleDepthReferencesAllLambda(will_fail);
+  // expected-note@-1{{in instantiation of function template specialization}}
+  // expected-note@#DDRAL_OP1{{while substituting into a lambda expression here}}
+  // expected-error@#DDRAL_OP2{{no matching function for call to object of type}}
+  // expected-note@#DDRAL_OP2{{candidate function not viable: constraints not satisfied}}
+  // expected-note@#DDRAL_REQ{{because 'IsInt' evaluated to false}}
 
   CausesFriendConstraint CFC;
   FriendFunc(CFC, 1);
@@ -565,6 +579,12 @@
   ChecksLocalVar(v);
   // FIXME: This should error on constraint failure! (Lambda!)
   ChecksLocalVar(will_fail);
+  // expected-note@-1{{in instantiation of function template specialization}}
+  // expected-error@#CLV_OP{{no matching function for call to object of type}}
+  // expected-note@#CLV_OP{{candidate function not viable: constraints not satisfied}}
+  // expected-note@#CLV_REQ{{because 'IsInt' evaluated to false}}
+
+
 
   LocalStructMemberVar(v);
   L

[PATCH] D154180: [OPENMP52] Codegen support for doacross clause.

2023-07-03 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 updated this revision to Diff 536838.
jyu2 added a comment.

Thanks  Alexey for the review!!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154180

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.h
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/test/OpenMP/ordered_doacross_codegen.c

Index: clang/test/OpenMP/ordered_doacross_codegen.c
===
--- clang/test/OpenMP/ordered_doacross_codegen.c
+++ clang/test/OpenMP/ordered_doacross_codegen.c
@@ -2,13 +2,21 @@
 // RUN: %clang_cc1 -fopenmp -triple x86_64-unknown-unknown -emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-NORMAL
 
+// RUN: %clang_cc1 -verify -fopenmp -triple x86_64-unknown-unknown -emit-llvm %s -o - -fopenmp-version=52 | FileCheck %s --check-prefixes=CHECK,CHECK-NORMAL
 // RUN: %clang_cc1 -verify -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -fopenmp-version=52 -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
 // RUN: %clang_cc1 -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
 
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=52 -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=52 -fopenmp-enable-irbuilder -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefixes=CHECK,CHECK-IRBUILDER
+
 // RUN: %clang_cc1 -verify -fopenmp-simd -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
+// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-version=52 -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
 // RUN: %clang_cc1 -fopenmp-simd -triple x86_64-unknown-unknown -emit-pch -o %t %s
 // RUN: %clang_cc1 -fopenmp-simd -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
+// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=52 -triple x86_64-unknown-unknown -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=52 -triple x86_64-unknown-unknown -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
 // SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
 // expected-no-diagnostics
 
@@ -51,7 +59,11 @@
 // CHECK-NORMAL-NEXT: call void @__kmpc_doacross_post(ptr [[IDENT]], i32 [[GTID]], ptr [[TMP]])
 // CHECK-IRBUILDER-NEXT: [[GTID1:%.+]] = call i32 @__kmpc_global_thread_num(ptr [[IDENT:@.+]])
 // CHECK-IRBUILDER-NEXT: call void @__kmpc_doacross_post(ptr [[IDENT]], i32 [[GTID1]], ptr [[TMP]])
+#if _OPENMP >= 202111
+#pragma omp ordered doacross(source:)
+#else
 #pragma omp ordered depend(source)
+#endif
 c[i] = c[i] + 1;
 foo();
 // CHECK: call void @foo()
@@ -66,7 +78,11 @@
 // CHECK-NORMAL-NEXT: call void @__kmpc_doacross_wait(ptr [[IDENT]], i32 [[GTID]], ptr [[TMP]])
 // CHECK-IRBUILDER-NEXT: [[GTID2:%.+]] = call i32 @__kmpc_global_thread_num(ptr [[IDENT:@.+]])
 // CHECK-IRBUILDER-NEXT: call void @__kmpc_doacross_wait(ptr [[IDENT]], i32 [[GTID2]], ptr [[TMP]])
+#if _OPENMP >= 202111
+#pragma omp ordered doacross(sink : i - 2)
+#else
 #pragma omp ordered depend(sink : i - 2)
+#endif
 d[i] = a[i - 2];
   }
   // CHECK: call void @__kmpc_for_static_fini(
Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -5839,37 +5839,46 @@
   return Fn;
 }
 
+template 
+static void emitRestoreIP(CodeGenFunction &CGF, const T *C,
+  llvm::OpenMPIRBuilder::InsertPointTy AllocaIP,
+  llvm::OpenMPIRBuilder &OMPBuilder) {
+
+  unsigned NumLoops = C->getNumLoops();
+  QualType Int64Ty = CGF.CGM.getContext().getIntTypeForBitwidth(
+  /*DestWidth=*/64, /*Signed=*/1);
+  llvm::SmallVector StoreValues;
+  for (unsigned I = 0; I < NumLoops; I++) {
+const Expr *CounterVal = C->getLoopData(I);
+assert(CounterVal);
+llvm::Value *StoreValue = CGF.EmitScalarConversion(
+CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
+CounterVal->getExprLoc());
+StoreValues.emplace_back(StoreValue);
+  }
+  OMPDoacrossKind ODK;
+  bool IsDependSource = ODK.isSource(C);
+  CGF.Builder.restoreIP(
+  OMPBuilder.createOrderedDepend(CGF.Builder, AllocaIP, NumLoops,
+  

[PATCH] D154180: [OPENMP52] Codegen support for doacross clause.

2023-07-03 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 added inline comments.



Comment at: clang/lib/CodeGen/CGOpenMPRuntime.cpp:11410
   } else {
-assert(C->getDependencyKind() == OMPC_DEPEND_sink);
+assert(ODK.isSink(C));
 RTLFn = OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),

ABataev wrote:
> Add a message, please
Added.  Thanks for the review.



Comment at: clang/lib/CodeGen/CGOpenMPRuntime.h:2279
+public:
+  bool isSink(const T *) { return false; }
+};

ABataev wrote:
> Add isSOurce 
Opps..  Sorry.  Added.  Thanks!!!  Jennifer



Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:5860-5862
+  bool IsDependSource = false;
+  if (ODK.isSource(C))
+IsDependSource = true;

ABataev wrote:
> bool IsDependSource = ODK.isSource(C);
Thanks.  Changed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154180

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


[PATCH] D154378: [LinkerWrapper] Set the GPU LTO job to be freestanding

2023-07-03 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: JonChesterfield, jdoerfert, yaxunl, tianshilei1992.
Herald added a subscriber: inglorion.
Herald added a project: All.
jhuber6 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The LTO config allows us to set whether or not the build is
freestanding. This pretty much prevents emission of library calls and
should cause them to be treated like normal functions. This is in
relation to D154364 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154378

Files:
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp


Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -570,6 +570,10 @@
   Conf.CGFileType =
   (Triple.isNVPTX() || SaveTemps) ? CGFT_AssemblyFile : CGFT_ObjectFile;
 
+  // We consider the GPU to be a freestanding target so we shouldn't emit any
+  // builtin library calls.
+  Conf.Freestanding = true;
+
   // TODO: Handle remark files
   Conf.HasWholeProgramVisibility = Args.hasArg(OPT_whole_program);
 


Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -570,6 +570,10 @@
   Conf.CGFileType =
   (Triple.isNVPTX() || SaveTemps) ? CGFT_AssemblyFile : CGFT_ObjectFile;
 
+  // We consider the GPU to be a freestanding target so we shouldn't emit any
+  // builtin library calls.
+  Conf.Freestanding = true;
+
   // TODO: Handle remark files
   Conf.HasWholeProgramVisibility = Args.hasArg(OPT_whole_program);
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D154357: [Driver] Recognize powerpc-unknown-eabi as a bare-metal toolchain

2023-07-03 Thread Jon Roelofs via Phabricator via cfe-commits
jroelofs added a comment.

> It seems to me that maybe anything with OS none (although that doesn’t seem 
> to be distinguished from unknown)

I considered splitting `none` from `unknown` in Triple, but never had the time 
to do it. I think this would be good for baremetal toolchains in light of the 
gcc installation detection machinery taking over whenever there isn't otherwise 
a match.

> or with environment eabi should be treated as bare-metal, but I don’t have a 
> lot of experience in this regard.

IIRC there are `arm-linux-eabi` toolchains in the wild, which are not baremetal.




Comment at: clang/lib/Driver/ToolChains/BareMetal.cpp:168
+
+  if (Triple.getVendor() != llvm::Triple::UnknownVendor)
+return false;

does this break your use cases re: having `indel` as the vendor? or will you 
have a downstream patch to exempt `indel` from this check?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154357

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


[PATCH] D154382: [ClangRepl] support code completion at a REPL

2023-07-03 Thread Fred Fu via Phabricator via cfe-commits
capfredf created this revision.
capfredf added a reviewer: v.g.vassilev.
Herald added a project: All.
capfredf requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch enabled users to use code completion in a REPL session. The solution 
is based on LineEditor and Sema/CodeCompletion.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154382

Files:
  clang/include/clang/Interpreter/CodeCompletion.h
  clang/include/clang/Interpreter/Interpreter.h
  clang/lib/Interpreter/CMakeLists.txt
  clang/lib/Interpreter/CodeCompletion.cpp
  clang/lib/Interpreter/ExternalSource.cpp
  clang/lib/Interpreter/ExternalSource.h
  clang/lib/Interpreter/IncrementalParser.cpp
  clang/lib/Interpreter/IncrementalParser.h
  clang/lib/Interpreter/Interpreter.cpp
  clang/tools/clang-repl/ClangRepl.cpp
  clang/unittests/Interpreter/CMakeLists.txt
  clang/unittests/Interpreter/CodeCompletionTest.cpp

Index: clang/unittests/Interpreter/CodeCompletionTest.cpp
===
--- /dev/null
+++ clang/unittests/Interpreter/CodeCompletionTest.cpp
@@ -0,0 +1,61 @@
+#include "clang/Interpreter/CodeCompletion.h"
+#include "clang/Interpreter/Interpreter.h"
+
+#include "llvm/LineEditor/LineEditor.h"
+
+#include "clang/Frontend/CompilerInstance.h"
+#include "llvm/Support/Error.h"
+
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+namespace {
+auto CB = clang::IncrementalCompilerBuilder();
+
+static std::unique_ptr createInterpreter() {
+  auto CI = cantFail(CB.CreateCpp());
+  return cantFail(clang::Interpreter::create(std::move(CI)));
+}
+
+TEST(CodeCompletionTest, Sanity) {
+  auto Interp = createInterpreter();
+  if (auto R = Interp->ParseAndExecute("int foo = 12;")) {
+consumeError(std::move(R));
+return;
+  }
+  auto Completer = ReplListCompleter(CB, *Interp);
+  std::vector comps =
+  Completer(std::string("f"), 1);
+  EXPECT_EQ((size_t)2, comps.size()); // foo and float
+  EXPECT_EQ(comps[0].TypedText, std::string("oo"));
+}
+
+TEST(CodeCompletionTest, SanityNoneValid) {
+  auto Interp = createInterpreter();
+  if (auto R = Interp->ParseAndExecute("int foo = 12;")) {
+consumeError(std::move(R));
+return;
+  }
+  auto Completer = ReplListCompleter(CB, *Interp);
+  std::vector comps =
+  Completer(std::string("babanana"), 8);
+  EXPECT_EQ((size_t)0, comps.size()); // foo and float
+}
+
+TEST(CodeCompletionTest, TwoDecls) {
+  auto Interp = createInterpreter();
+  if (auto R = Interp->ParseAndExecute("int application = 12;")) {
+consumeError(std::move(R));
+return;
+  }
+  if (auto R = Interp->ParseAndExecute("int apple = 12;")) {
+consumeError(std::move(R));
+return;
+  }
+  auto Completer = ReplListCompleter(CB, *Interp);
+  std::vector comps =
+  Completer(std::string("app"), 3);
+  EXPECT_EQ((size_t)2, comps.size());
+}
+} // anonymous namespace
Index: clang/unittests/Interpreter/CMakeLists.txt
===
--- clang/unittests/Interpreter/CMakeLists.txt
+++ clang/unittests/Interpreter/CMakeLists.txt
@@ -9,6 +9,7 @@
 add_clang_unittest(ClangReplInterpreterTests
   IncrementalProcessingTest.cpp
   InterpreterTest.cpp
+  CodeCompletionTest.cpp
   )
 target_link_libraries(ClangReplInterpreterTests PUBLIC
   clangAST
Index: clang/tools/clang-repl/ClangRepl.cpp
===
--- clang/tools/clang-repl/ClangRepl.cpp
+++ clang/tools/clang-repl/ClangRepl.cpp
@@ -13,6 +13,7 @@
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
+#include "clang/Interpreter/CodeCompletion.h"
 #include "clang/Interpreter/Interpreter.h"
 
 #include "llvm/ExecutionEngine/Orc/LLJIT.h"
@@ -155,8 +156,8 @@
 
   if (OptInputs.empty()) {
 llvm::LineEditor LE("clang-repl");
-// FIXME: Add LE.setListCompleter
 std::string Input;
+LE.setListCompleter(clang::ReplListCompleter(CB, *Interp));
 while (std::optional Line = LE.readLine()) {
   llvm::StringRef L = *Line;
   L = L.trim();
@@ -168,10 +169,10 @@
   }
 
   Input += L;
-
   if (Input == R"(%quit)") {
 break;
-  } else if (Input == R"(%undo)") {
+  }
+  if (Input == R"(%undo)") {
 if (auto Err = Interp->Undo()) {
   llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "error: ");
   HasError = true;
Index: clang/lib/Interpreter/Interpreter.cpp
===
--- clang/lib/Interpreter/Interpreter.cpp
+++ clang/lib/Interpreter/Interpreter.cpp
@@ -14,6 +14,7 @@
 #include "clang/Interpreter/Interpreter.h"
 
 #include "DeviceOffload.h"
+#include "ExternalSource.h"
 #include "IncrementalExecutor.h"
 #include "IncrementalParser.h"
 
@@ -33,6 +34,7 @@
 #include "clang/Driver/Tool.h"
 #include "clang/Frontend

[PATCH] D135849: [llvm] Return canonical virtual path from `RedirectingFileSystem`

2023-07-03 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

Okay, I'll try to figure out how expensive this would be. I'd like Clang to be 
stricter in situations like these, but if that's not feasible, I'll probably 
implement the first workaround.

For the second workaround, I don't think that moves us in better direction - we 
should be able to assign one canonical real path to each `DirectoryEntry`.

The unfortunate aspect of the `ModuleMap::canonicalizeModuleMapPath()` 
implementation is that it uses 
`FileManager.getDirectoryRef(llvm::sys::path::parent_path(ModuleMapFilePath))`. 
If the request for getting the module map file fell through the VFS into the 
underlying FS, parent `DirectoryEntry` of that file is different than the 
virtual directory made for the VFS. Chopping off the file name and going 
through the VFS again doesn't guarantee falling through the VFS again, which 
that code doesn't account for. It'd be really nice to have 
`DirectoryEntry::getDir()` API, so that we can walk up the directory hierarchy 
while preserving the virtual/real distinction between directories in the 
overlay/on disk, never accidentally "bubbling up" into the overlay again. 
What's your take on that?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135849

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


[PATCH] D135849: [llvm] Return canonical virtual path from `RedirectingFileSystem`

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

In D135849#4469347 , @jansvoboda11 
wrote:

> It'd be really nice to have DirectoryEntry::getDir() API, so that we can walk 
> up the directory hierarchy while preserving the virtual/real distinction 
> between directories in the overlay/on disk, never accidentally "bubbling up" 
> into the overlay again. What's your take on that?

Can you say more about how you would do this and preserve the real/virtual 
distinction? Currently FileManager is just filling in the directory based on 
the parent path with a lookup to the VFS, so isn't it the same issue? Or did 
you mean we would keep more info?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135849

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


[PATCH] D154385: [HIP] Pass -fno-hip-fp32-correctly-rounded-divide-sqrt to clang -cc1

2023-07-03 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl created this revision.
yaxunl added reviewers: tra, MaskRay, arsenm.
Herald added a project: All.
yaxunl requested review of this revision.
Herald added a subscriber: wdng.

`-fno-hip-fp32-correctly-rounded-divide-sqrt` affects clang codegen
and should be passed to clang -cc1 by clang driver.

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


https://reviews.llvm.org/D154385

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/hip-options.hip


Index: clang/test/Driver/hip-options.hip
===
--- clang/test/Driver/hip-options.hip
+++ clang/test/Driver/hip-options.hip
@@ -154,3 +154,18 @@
 // RUN: %clang -### -nogpuinc -nogpulib -mamdgpu-ieee -mno-amdgpu-ieee 
-ffast-math \
 // RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck 
-check-prefixes=IEEE-OFF-NEG %s
 // IEEE-OFF-NEG-NOT: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} 
"-mamdgpu-ieee"
+
+// Check -fno-hip-fp32-correctly-rounded-divide-sqrt is passed to -cc1 but
+// (default) -fhip-fp32-correctly-rounded-divide-sqrt is not.
+
+// RUN: %clang -### -nogpuinc -nogpulib 
-fno-hip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=NOCRDS %s
+// NOCRDS: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} 
"-fno-hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib 
-fhip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -7223,6 +7223,11 @@
 }
   }
 
+  if (IsHIPDevice)
+Args.addOptOutFlag(CmdArgs,
+   options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
+   
options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
+
   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
   // to specify the result of the compile phase on the host, so the meaningful
   // device declarations can be identified. Also, -fopenmp-is-device is passed


Index: clang/test/Driver/hip-options.hip
===
--- clang/test/Driver/hip-options.hip
+++ clang/test/Driver/hip-options.hip
@@ -154,3 +154,18 @@
 // RUN: %clang -### -nogpuinc -nogpulib -mamdgpu-ieee -mno-amdgpu-ieee -ffast-math \
 // RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=IEEE-OFF-NEG %s
 // IEEE-OFF-NEG-NOT: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} "-mamdgpu-ieee"
+
+// Check -fno-hip-fp32-correctly-rounded-divide-sqrt is passed to -cc1 but
+// (default) -fhip-fp32-correctly-rounded-divide-sqrt is not.
+
+// RUN: %clang -### -nogpuinc -nogpulib -fno-hip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=NOCRDS %s
+// NOCRDS: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} "-fno-hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib -fhip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -7223,6 +7223,11 @@
 }
   }
 
+  if (IsHIPDevice)
+Args.addOptOutFlag(CmdArgs,
+   options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
+   options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
+
   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
   // to specify the result of the compile phase on the host, so the meaningful
   // device declarations can be identified. Also, -fopenmp-is-device is passed
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D154180: [OPENMP52] Codegen support for doacross clause.

2023-07-03 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev accepted this revision.
ABataev added a comment.
This revision is now accepted and ready to land.

LG with a nit




Comment at: clang/lib/CodeGen/CGOpenMPRuntime.h:2285-2297
+return (C->getDependencyKind() == OMPC_DEPEND_sink);
+  }
+  bool isSource(const OMPDependClause *C) {
+return (C->getDependencyKind() == OMPC_DEPEND_source);
+  }
+};
+template <> class OMPDoacrossKind {

remove parens from the expressions, they are not needed


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154180

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


[PATCH] D61508: [clang-tidy] bugprone-header-guard : a simple version of llvm-header-guard

2023-07-03 Thread Gary Miguel via Phabricator via cfe-commits
garymm added a comment.
Herald added subscribers: carlosgalvezp, mgehre.
Herald added a project: All.

@aaron.ballman what's remaining for this to be mergeable?


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D61508

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


[PATCH] D154334: [clang] Add `__has_extension ()` for C++11 features

2023-07-03 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added a comment.

Thank you or the quick fix!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154334

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


[PATCH] D154339: [clang][dataflow] Make `runDataflowReturnError()` a non-template function.

2023-07-03 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 accepted this revision.
gribozavr2 added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/unittests/Analysis/FlowSensitive/TestingSupport.h:389
 /// verify the results.
-template 
-llvm::Error
-runDataflowReturnError(llvm::StringRef Code, VerifyResultsT VerifyResults,
-   DataflowAnalysisOptions Options,
-   LangStandard::Kind Std = LangStandard::lang_cxx17,
-   llvm::StringRef TargetFun = "target") {
-  using ast_matchers::hasName;
-  llvm::SmallVector ASTBuildArgs = {
-  // -fnodelayed-template-parsing is the default everywhere but on Windows.
-  // Set it explicitly so that tests behave the same on Windows as on other
-  // platforms.
-  "-fsyntax-only", "-fno-delayed-template-parsing",
-  "-std=" +
-  std::string(LangStandard::getLangStandardForKind(Std).getName())};
-  AnalysisInputs AI(
-  Code, hasName(TargetFun),
-  [UseBuiltinModel = Options.BuiltinOpts.has_value()](ASTContext &C,
-  Environment &Env) {
-return NoopAnalysis(
-C,
-DataflowAnalysisOptions{
-UseBuiltinModel ? Env.getDataflowAnalysisContext().getOptions()
-: std::optional()});
-  });
-  AI.ASTBuildArgs = ASTBuildArgs;
-  if (Options.BuiltinOpts)
-AI.BuiltinOptions = *Options.BuiltinOpts;
-  return checkDataflow(
-  std::move(AI),
-  /*VerifyResults=*/
-  [&VerifyResults](
-  const llvm::StringMap> &Results,
-  const AnalysisOutputs &AO) { VerifyResults(Results, AO.ASTCtx); });
-}
+llvm::Error runDataflowReturnError(
+llvm::StringRef Code,

I don't quite understand your comment from the previous patch:

> This is really just moved from TransferTest.cpp -- and it's more closely 
> related to the `runDataflow()` functions there and in the newly added 
> RecordOps.cpp. (I can't call it `runDataflow()` because then it would differ 
> only in return type from one of the functions in the overload set.)

I don't see another `checkDataflow()` function with the same signature. 
Furthermore, `checkDataflow()` overloads above already return an `llvm::Error`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154339

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


[PATCH] D154385: [HIP] Pass -fno-hip-fp32-correctly-rounded-divide-sqrt to clang -cc1

2023-07-03 Thread Yaxun Liu 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 rG4eef52885341: [HIP] Pass 
-fno-hip-fp32-correctly-rounded-divide-sqrt to clang -cc1 (authored by yaxunl).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154385

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/hip-options.hip


Index: clang/test/Driver/hip-options.hip
===
--- clang/test/Driver/hip-options.hip
+++ clang/test/Driver/hip-options.hip
@@ -154,3 +154,18 @@
 // RUN: %clang -### -nogpuinc -nogpulib -mamdgpu-ieee -mno-amdgpu-ieee 
-ffast-math \
 // RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck 
-check-prefixes=IEEE-OFF-NEG %s
 // IEEE-OFF-NEG-NOT: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} 
"-mamdgpu-ieee"
+
+// Check -fno-hip-fp32-correctly-rounded-divide-sqrt is passed to -cc1 but
+// (default) -fhip-fp32-correctly-rounded-divide-sqrt is not.
+
+// RUN: %clang -### -nogpuinc -nogpulib 
-fno-hip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=NOCRDS %s
+// NOCRDS: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} 
"-fno-hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib 
-fhip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -7223,6 +7223,11 @@
 }
   }
 
+  if (IsHIPDevice)
+Args.addOptOutFlag(CmdArgs,
+   options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
+   
options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
+
   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
   // to specify the result of the compile phase on the host, so the meaningful
   // device declarations can be identified. Also, -fopenmp-is-device is passed


Index: clang/test/Driver/hip-options.hip
===
--- clang/test/Driver/hip-options.hip
+++ clang/test/Driver/hip-options.hip
@@ -154,3 +154,18 @@
 // RUN: %clang -### -nogpuinc -nogpulib -mamdgpu-ieee -mno-amdgpu-ieee -ffast-math \
 // RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=IEEE-OFF-NEG %s
 // IEEE-OFF-NEG-NOT: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} "-mamdgpu-ieee"
+
+// Check -fno-hip-fp32-correctly-rounded-divide-sqrt is passed to -cc1 but
+// (default) -fhip-fp32-correctly-rounded-divide-sqrt is not.
+
+// RUN: %clang -### -nogpuinc -nogpulib -fno-hip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=NOCRDS %s
+// NOCRDS: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} "-fno-hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib -fhip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -7223,6 +7223,11 @@
 }
   }
 
+  if (IsHIPDevice)
+Args.addOptOutFlag(CmdArgs,
+   options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
+   options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
+
   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
   // to specify the result of the compile phase on the host, so the meaningful
   // device declarations can be identified. Also, -fopenmp-is-device is passed
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 4eef528 - [HIP] Pass -fno-hip-fp32-correctly-rounded-divide-sqrt to clang -cc1

2023-07-03 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2023-07-03T16:19:25-04:00
New Revision: 4eef528853418fd72bffbb139d953520bb7b4c73

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

LOG: [HIP] Pass -fno-hip-fp32-correctly-rounded-divide-sqrt to clang -cc1

-fno-hip-fp32-correctly-rounded-divide-sqrt affects clang codegen
and should be passed to clang -cc1 by clang driver.

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

Reviewed by: Matt Arsenault

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/Driver/hip-options.hip

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 6f3d86b900edfb..f85584b3335e4b 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -7223,6 +7223,11 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
 }
   }
 
+  if (IsHIPDevice)
+Args.addOptOutFlag(CmdArgs,
+   options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
+   
options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
+
   // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
   // to specify the result of the compile phase on the host, so the meaningful
   // device declarations can be identified. Also, -fopenmp-is-device is passed

diff  --git a/clang/test/Driver/hip-options.hip 
b/clang/test/Driver/hip-options.hip
index 7a6965caf5e001..edbe4ff3acbedf 100644
--- a/clang/test/Driver/hip-options.hip
+++ b/clang/test/Driver/hip-options.hip
@@ -154,3 +154,18 @@
 // RUN: %clang -### -nogpuinc -nogpulib -mamdgpu-ieee -mno-amdgpu-ieee 
-ffast-math \
 // RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck 
-check-prefixes=IEEE-OFF-NEG %s
 // IEEE-OFF-NEG-NOT: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} 
"-mamdgpu-ieee"
+
+// Check -fno-hip-fp32-correctly-rounded-divide-sqrt is passed to -cc1 but
+// (default) -fhip-fp32-correctly-rounded-divide-sqrt is not.
+
+// RUN: %clang -### -nogpuinc -nogpulib 
-fno-hip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=NOCRDS %s
+// NOCRDS: clang{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} 
"-fno-hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
+
+// RUN: %clang -### -nogpuinc -nogpulib 
-fhip-fp32-correctly-rounded-divide-sqrt \
+// RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
+// CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"



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


  1   2   >