[llvm-branch-commits] [flang] 748b17c - Revert "[flang] Align runtime info and lowering regarding passing ABIs (#81166)"

2024-02-09 Thread via llvm-branch-commits

Author: jeanPerier
Date: 2024-02-09T09:37:12+01:00
New Revision: 748b17c66400aaf6fe85eaf8dde56de80322b73e

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

LOG: Revert "[flang] Align runtime info and lowering regarding passing ABIs 
(#81166)"

This reverts commit b477d39bf6811ac12a1e7e98f308cf4c9a8de26f.

Added: 


Modified: 
flang/include/flang/Evaluate/characteristics.h
flang/lib/Evaluate/characteristics.cpp
flang/lib/Lower/CallInterface.cpp
flang/lib/Semantics/runtime-type-info.cpp

Removed: 
flang/test/Semantics/typeinfo09.f90



diff  --git a/flang/include/flang/Evaluate/characteristics.h 
b/flang/include/flang/Evaluate/characteristics.h
index 04a0d71e1adebe..fd4af157f79374 100644
--- a/flang/include/flang/Evaluate/characteristics.h
+++ b/flang/include/flang/Evaluate/characteristics.h
@@ -229,7 +229,6 @@ struct DummyDataObject {
   static std::optional Characterize(
   const semantics::Symbol &, FoldingContext &);
   bool CanBePassedViaImplicitInterface(std::string *whyNot = nullptr) const;
-  bool IsPassedByDescriptor(bool isBindC) const;
   llvm::raw_ostream &Dump(llvm::raw_ostream &) const;
 
   TypeAndShape type;

diff  --git a/flang/lib/Evaluate/characteristics.cpp 
b/flang/lib/Evaluate/characteristics.cpp
index c14a422ad038f0..d480050d354fb9 100644
--- a/flang/lib/Evaluate/characteristics.cpp
+++ b/flang/lib/Evaluate/characteristics.cpp
@@ -461,30 +461,6 @@ bool DummyDataObject::CanBePassedViaImplicitInterface(
   }
 }
 
-bool DummyDataObject::IsPassedByDescriptor(bool isBindC) const {
-  constexpr TypeAndShape::Attrs shapeRequiringBox = {
-  TypeAndShape::Attr::AssumedShape, TypeAndShape::Attr::DeferredShape,
-  TypeAndShape::Attr::AssumedRank, TypeAndShape::Attr::Coarray};
-  if ((attrs & Attrs{Attr::Allocatable, Attr::Pointer}).any()) {
-return true;
-  } else if ((type.attrs() & shapeRequiringBox).any()) {
-// Need to pass shape/coshape info in a descriptor.
-return true;
-  } else if (type.type().IsPolymorphic() && !type.type().IsAssumedType()) {
-// Need to pass dynamic type info in a descriptor.
-return true;
-  } else if (const auto *derived{GetDerivedTypeSpec(type.type())}) {
-if (const semantics::Scope *scope = derived->scope()) {
-  // Need to pass length type parameters in a descriptor if any.
-  return scope->IsDerivedTypeWithLengthParameter();
-}
-  } else if (isBindC && type.type().IsAssumedLengthCharacter()) {
-// Fortran 2018 18.3.6 point 2 (5)
-return true;
-  }
-  return false;
-}
-
 llvm::raw_ostream &DummyDataObject::Dump(llvm::raw_ostream &o) const {
   attrs.Dump(o, EnumToString);
   if (intent != common::Intent::Default) {

diff  --git a/flang/lib/Lower/CallInterface.cpp 
b/flang/lib/Lower/CallInterface.cpp
index f67ee880a2ff7b..4c297ceffc536d 100644
--- a/flang/lib/Lower/CallInterface.cpp
+++ b/flang/lib/Lower/CallInterface.cpp
@@ -916,6 +916,31 @@ class Fortran::lower::CallInterfaceImpl {
 }
   }
 
+  // Define when an explicit argument must be passed in a fir.box.
+  bool dummyRequiresBox(
+  const Fortran::evaluate::characteristics::DummyDataObject &obj,
+  bool isBindC) {
+using ShapeAttr = Fortran::evaluate::characteristics::TypeAndShape::Attr;
+using ShapeAttrs = Fortran::evaluate::characteristics::TypeAndShape::Attrs;
+constexpr ShapeAttrs shapeRequiringBox = {
+ShapeAttr::AssumedShape, ShapeAttr::DeferredShape,
+ShapeAttr::AssumedRank, ShapeAttr::Coarray};
+if ((obj.type.attrs() & shapeRequiringBox).any())
+  // Need to pass shape/coshape info in fir.box.
+  return true;
+if (obj.type.type().IsPolymorphic() && !obj.type.type().IsAssumedType())
+  // Need to pass dynamic type info in fir.box.
+  return true;
+if (const Fortran::semantics::DerivedTypeSpec *derived =
+Fortran::evaluate::GetDerivedTypeSpec(obj.type.type()))
+  if (const Fortran::semantics::Scope *scope = derived->scope())
+// Need to pass length type parameters in fir.box if any.
+return scope->IsDerivedTypeWithLengthParameter();
+if (isBindC && obj.type.type().IsAssumedLengthCharacter())
+  return true; // Fortran 2018 18.3.6 point 2 (5)
+return false;
+  }
+
   mlir::Type
   translateDynamicType(const Fortran::evaluate::DynamicType &dynamicType) {
 Fortran::common::TypeCategory cat = dynamicType.category();
@@ -1002,7 +1027,7 @@ class Fortran::lower::CallInterfaceImpl {
   addFirOperand(boxRefType, nextPassedArgPosition(), Property::MutableBox,
 attrs);
   addPassedArg(PassEntityBy::MutableBox, entity, characteristics);
-} else if (obj.IsPassedByDescriptor(isBindC)) {
+} else if (dummyRequiresBox(obj, isBindC)) {
   // Pass as fir.box or fir.class
  

[llvm-branch-commits] [mlir] [mlir][Transforms][NFC] Modularize block actions (PR #81237)

2024-02-09 Thread Matthias Springer via llvm-branch-commits

https://github.com/matthias-springer created 
https://github.com/llvm/llvm-project/pull/81237

Throughout the rewrite process, the dialect conversion maintains a list of 
"block actions" that can be rolled back upon failure. This commit encapsulates 
the existing block actions into separate classes, making it easier to add 
additional actions in the future.

This commit also renames "block actions" to "rewrite actions". In a subsequent 
commit, an "operation action" that allows rolling back movements of single 
operations is added. This is to support `moveOpBefore` in the dialect 
conversion.

Rewrite actions have two methods: `commit()` commits an action. It can no 
longer be rolled back afterwards. `rollback()` undoes an action. It can no 
longer be committed afterwards.

>From 956717ee48940279edfbe84794d6f9575c14d075 Mon Sep 17 00:00:00 2001
From: Matthias Springer 
Date: Fri, 9 Feb 2024 09:29:10 +
Subject: [PATCH] [mlir][Transforms][NFC] Modularize block actions

Throughout the rewrite process, the dialect conversion maintains a list
of "block actions" that can be rolled back upon failure. This commit
encapsulates the existing block actions into separate classes, making it
easier to add additional actions in the future.

This commit also renames "block actions" to "rewrite actions". In a
subsequent commit, an "operation action" that allows rolling back
movements of single operations is added. This is to support
`moveOpBefore` in the dialect conversion.

Rewrite actions have two methods: `commit()` commits an action. It can
no longer be rolled back afterwards. `rollback()` undoes an action. It
can no longer be committed afterwards.
---
 .../Transforms/Utils/DialectConversion.cpp| 466 +++---
 1 file changed, 283 insertions(+), 183 deletions(-)

diff --git a/mlir/lib/Transforms/Utils/DialectConversion.cpp 
b/mlir/lib/Transforms/Utils/DialectConversion.cpp
index e41231d7cbd390..44c107c8733f3d 100644
--- a/mlir/lib/Transforms/Utils/DialectConversion.cpp
+++ b/mlir/lib/Transforms/Utils/DialectConversion.cpp
@@ -154,13 +154,13 @@ namespace {
 struct RewriterState {
   RewriterState(unsigned numCreatedOps, unsigned numUnresolvedMaterializations,
 unsigned numReplacements, unsigned numArgReplacements,
-unsigned numBlockActions, unsigned numIgnoredOperations,
+unsigned numRewriteActions, unsigned numIgnoredOperations,
 unsigned numRootUpdates)
   : numCreatedOps(numCreatedOps),
 numUnresolvedMaterializations(numUnresolvedMaterializations),
 numReplacements(numReplacements),
 numArgReplacements(numArgReplacements),
-numBlockActions(numBlockActions),
+numRewriteActions(numRewriteActions),
 numIgnoredOperations(numIgnoredOperations),
 numRootUpdates(numRootUpdates) {}
 
@@ -176,8 +176,8 @@ struct RewriterState {
   /// The current number of argument replacements queued.
   unsigned numArgReplacements;
 
-  /// The current number of block actions performed.
-  unsigned numBlockActions;
+  /// The current number of rewrite actions performed.
+  unsigned numRewriteActions;
 
   /// The current number of ignored operations.
   unsigned numIgnoredOperations;
@@ -235,86 +235,6 @@ struct OpReplacement {
   const TypeConverter *converter;
 };
 
-//===--===//
-// BlockAction
-
-/// The kind of the block action performed during the rewrite.  Actions can be
-/// undone if the conversion fails.
-enum class BlockActionKind {
-  Create,
-  Erase,
-  Inline,
-  Move,
-  Split,
-  TypeConversion
-};
-
-/// Original position of the given block in its parent region. During undo
-/// actions, the block needs to be placed before `insertBeforeBlock`.
-struct BlockPosition {
-  Region *region;
-  Block *insertBeforeBlock;
-};
-
-/// Information needed to undo inlining actions.
-/// - the source block
-/// - the first inlined operation (could be null if the source block was empty)
-/// - the last inlined operation (could be null if the source block was empty)
-struct InlineInfo {
-  Block *sourceBlock;
-  Operation *firstInlinedInst;
-  Operation *lastInlinedInst;
-};
-
-/// The storage class for an undoable block action (one of BlockActionKind),
-/// contains the information necessary to undo this action.
-struct BlockAction {
-  static BlockAction getCreate(Block *block) {
-return {BlockActionKind::Create, block, {}};
-  }
-  static BlockAction getErase(Block *block, BlockPosition originalPosition) {
-return {BlockActionKind::Erase, block, {originalPosition}};
-  }
-  static BlockAction getInline(Block *block, Block *srcBlock,
-   Block::iterator before) {
-BlockAction action{BlockActionKind::Inline, block, {}};
-action.inlineInfo = {srcBlock,
- srcBlock->empty() ? nullptr : &srcBlock->front(),
- srcBlock->empty() ? nullptr : &srcBlock-

[llvm-branch-commits] [mlir] [mlir][Transforms][NFC] Modularize block actions (PR #81237)

2024-02-09 Thread via llvm-branch-commits

llvmbot wrote:




@llvm/pr-subscribers-mlir

Author: Matthias Springer (matthias-springer)


Changes

Throughout the rewrite process, the dialect conversion maintains a list of 
"block actions" that can be rolled back upon failure. This commit encapsulates 
the existing block actions into separate classes, making it easier to add 
additional actions in the future.

This commit also renames "block actions" to "rewrite actions". In a subsequent 
commit, an "operation action" that allows rolling back movements of single 
operations is added. This is to support `moveOpBefore` in the dialect 
conversion.

Rewrite actions have two methods: `commit()` commits an action. It can no 
longer be rolled back afterwards. `rollback()` undoes an action. It can no 
longer be committed afterwards.

---

Patch is 23.31 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/81237.diff


1 Files Affected:

- (modified) mlir/lib/Transforms/Utils/DialectConversion.cpp (+283-183) 


``diff
diff --git a/mlir/lib/Transforms/Utils/DialectConversion.cpp 
b/mlir/lib/Transforms/Utils/DialectConversion.cpp
index e41231d7cbd390..44c107c8733f3d 100644
--- a/mlir/lib/Transforms/Utils/DialectConversion.cpp
+++ b/mlir/lib/Transforms/Utils/DialectConversion.cpp
@@ -154,13 +154,13 @@ namespace {
 struct RewriterState {
   RewriterState(unsigned numCreatedOps, unsigned numUnresolvedMaterializations,
 unsigned numReplacements, unsigned numArgReplacements,
-unsigned numBlockActions, unsigned numIgnoredOperations,
+unsigned numRewriteActions, unsigned numIgnoredOperations,
 unsigned numRootUpdates)
   : numCreatedOps(numCreatedOps),
 numUnresolvedMaterializations(numUnresolvedMaterializations),
 numReplacements(numReplacements),
 numArgReplacements(numArgReplacements),
-numBlockActions(numBlockActions),
+numRewriteActions(numRewriteActions),
 numIgnoredOperations(numIgnoredOperations),
 numRootUpdates(numRootUpdates) {}
 
@@ -176,8 +176,8 @@ struct RewriterState {
   /// The current number of argument replacements queued.
   unsigned numArgReplacements;
 
-  /// The current number of block actions performed.
-  unsigned numBlockActions;
+  /// The current number of rewrite actions performed.
+  unsigned numRewriteActions;
 
   /// The current number of ignored operations.
   unsigned numIgnoredOperations;
@@ -235,86 +235,6 @@ struct OpReplacement {
   const TypeConverter *converter;
 };
 
-//===--===//
-// BlockAction
-
-/// The kind of the block action performed during the rewrite.  Actions can be
-/// undone if the conversion fails.
-enum class BlockActionKind {
-  Create,
-  Erase,
-  Inline,
-  Move,
-  Split,
-  TypeConversion
-};
-
-/// Original position of the given block in its parent region. During undo
-/// actions, the block needs to be placed before `insertBeforeBlock`.
-struct BlockPosition {
-  Region *region;
-  Block *insertBeforeBlock;
-};
-
-/// Information needed to undo inlining actions.
-/// - the source block
-/// - the first inlined operation (could be null if the source block was empty)
-/// - the last inlined operation (could be null if the source block was empty)
-struct InlineInfo {
-  Block *sourceBlock;
-  Operation *firstInlinedInst;
-  Operation *lastInlinedInst;
-};
-
-/// The storage class for an undoable block action (one of BlockActionKind),
-/// contains the information necessary to undo this action.
-struct BlockAction {
-  static BlockAction getCreate(Block *block) {
-return {BlockActionKind::Create, block, {}};
-  }
-  static BlockAction getErase(Block *block, BlockPosition originalPosition) {
-return {BlockActionKind::Erase, block, {originalPosition}};
-  }
-  static BlockAction getInline(Block *block, Block *srcBlock,
-   Block::iterator before) {
-BlockAction action{BlockActionKind::Inline, block, {}};
-action.inlineInfo = {srcBlock,
- srcBlock->empty() ? nullptr : &srcBlock->front(),
- srcBlock->empty() ? nullptr : &srcBlock->back()};
-return action;
-  }
-  static BlockAction getMove(Block *block, BlockPosition originalPosition) {
-return {BlockActionKind::Move, block, {originalPosition}};
-  }
-  static BlockAction getSplit(Block *block, Block *originalBlock) {
-BlockAction action{BlockActionKind::Split, block, {}};
-action.originalBlock = originalBlock;
-return action;
-  }
-  static BlockAction getTypeConversion(Block *block) {
-return BlockAction{BlockActionKind::TypeConversion, block, {}};
-  }
-
-  // The action kind.
-  BlockActionKind kind;
-
-  // A pointer to the block that was created by the action.
-  Block *block;
-
-  union {
-// In use if kind == BlockActionKind::Inline or BlockActionKind::Erase, and
-// contains a pointer to the reg

[llvm-branch-commits] [mlir] [mlir][Transforms][NFC] Modularize block actions (PR #81237)

2024-02-09 Thread Matthias Springer via llvm-branch-commits

https://github.com/matthias-springer updated 
https://github.com/llvm/llvm-project/pull/81237

>From ae9dcbbcf4a23cd9f5a28195ceb3687957fa730f Mon Sep 17 00:00:00 2001
From: Matthias Springer 
Date: Fri, 9 Feb 2024 09:29:10 +
Subject: [PATCH] [mlir][Transforms][NFC] Modularize block actions

Throughout the rewrite process, the dialect conversion maintains a list
of "block actions" that can be rolled back upon failure. This commit
encapsulates the existing block actions into separate classes, making it
easier to add additional actions in the future.

This commit also renames "block actions" to "rewrite actions". In a
subsequent commit, an "operation action" that allows rolling back
movements of single operations is added. This is to support
`moveOpBefore` in the dialect conversion.

Rewrite actions have two methods: `commit()` commits an action. It can
no longer be rolled back afterwards. `rollback()` undoes an action. It
can no longer be committed afterwards.
---
 .../Transforms/Utils/DialectConversion.cpp| 466 +++---
 1 file changed, 283 insertions(+), 183 deletions(-)

diff --git a/mlir/lib/Transforms/Utils/DialectConversion.cpp 
b/mlir/lib/Transforms/Utils/DialectConversion.cpp
index e41231d7cbd390..44c107c8733f3d 100644
--- a/mlir/lib/Transforms/Utils/DialectConversion.cpp
+++ b/mlir/lib/Transforms/Utils/DialectConversion.cpp
@@ -154,13 +154,13 @@ namespace {
 struct RewriterState {
   RewriterState(unsigned numCreatedOps, unsigned numUnresolvedMaterializations,
 unsigned numReplacements, unsigned numArgReplacements,
-unsigned numBlockActions, unsigned numIgnoredOperations,
+unsigned numRewriteActions, unsigned numIgnoredOperations,
 unsigned numRootUpdates)
   : numCreatedOps(numCreatedOps),
 numUnresolvedMaterializations(numUnresolvedMaterializations),
 numReplacements(numReplacements),
 numArgReplacements(numArgReplacements),
-numBlockActions(numBlockActions),
+numRewriteActions(numRewriteActions),
 numIgnoredOperations(numIgnoredOperations),
 numRootUpdates(numRootUpdates) {}
 
@@ -176,8 +176,8 @@ struct RewriterState {
   /// The current number of argument replacements queued.
   unsigned numArgReplacements;
 
-  /// The current number of block actions performed.
-  unsigned numBlockActions;
+  /// The current number of rewrite actions performed.
+  unsigned numRewriteActions;
 
   /// The current number of ignored operations.
   unsigned numIgnoredOperations;
@@ -235,86 +235,6 @@ struct OpReplacement {
   const TypeConverter *converter;
 };
 
-//===--===//
-// BlockAction
-
-/// The kind of the block action performed during the rewrite.  Actions can be
-/// undone if the conversion fails.
-enum class BlockActionKind {
-  Create,
-  Erase,
-  Inline,
-  Move,
-  Split,
-  TypeConversion
-};
-
-/// Original position of the given block in its parent region. During undo
-/// actions, the block needs to be placed before `insertBeforeBlock`.
-struct BlockPosition {
-  Region *region;
-  Block *insertBeforeBlock;
-};
-
-/// Information needed to undo inlining actions.
-/// - the source block
-/// - the first inlined operation (could be null if the source block was empty)
-/// - the last inlined operation (could be null if the source block was empty)
-struct InlineInfo {
-  Block *sourceBlock;
-  Operation *firstInlinedInst;
-  Operation *lastInlinedInst;
-};
-
-/// The storage class for an undoable block action (one of BlockActionKind),
-/// contains the information necessary to undo this action.
-struct BlockAction {
-  static BlockAction getCreate(Block *block) {
-return {BlockActionKind::Create, block, {}};
-  }
-  static BlockAction getErase(Block *block, BlockPosition originalPosition) {
-return {BlockActionKind::Erase, block, {originalPosition}};
-  }
-  static BlockAction getInline(Block *block, Block *srcBlock,
-   Block::iterator before) {
-BlockAction action{BlockActionKind::Inline, block, {}};
-action.inlineInfo = {srcBlock,
- srcBlock->empty() ? nullptr : &srcBlock->front(),
- srcBlock->empty() ? nullptr : &srcBlock->back()};
-return action;
-  }
-  static BlockAction getMove(Block *block, BlockPosition originalPosition) {
-return {BlockActionKind::Move, block, {originalPosition}};
-  }
-  static BlockAction getSplit(Block *block, Block *originalBlock) {
-BlockAction action{BlockActionKind::Split, block, {}};
-action.originalBlock = originalBlock;
-return action;
-  }
-  static BlockAction getTypeConversion(Block *block) {
-return BlockAction{BlockActionKind::TypeConversion, block, {}};
-  }
-
-  // The action kind.
-  BlockActionKind kind;
-
-  // A pointer to the block that was created by the action.
-  Block *block;
-
-  union {
-// In use if kind == BlockActionK

[llvm-branch-commits] [mlir] [mlir][Transforms] Support `moveOpBefore`/`After` in dialect conversion (PR #81240)

2024-02-09 Thread Matthias Springer via llvm-branch-commits

https://github.com/matthias-springer created 
https://github.com/llvm/llvm-project/pull/81240

Add a new rewrite action for "operation movements". This action can roll back 
`moveOpBefore` and `moveOpAfter`.

`RewriterBase::moveOpBefore` and `RewriterBase::moveOpAfter` is no longer 
virtual. (The dialect conversion can gather all required information for 
rollbacks from listener notifications.)


>From 7503c0cb484c54249ff66c5780197d46937c660d Mon Sep 17 00:00:00 2001
From: Matthias Springer 
Date: Fri, 9 Feb 2024 09:58:46 +
Subject: [PATCH] [mlir][Transforms] Support `moveOpBefore`/`After` in dialect
 conversion

Add a new rewrite action for "operation movements". This action can roll back 
`moveOpBefore` and `moveOpAfter`.

`RewriterBase::moveOpBefore` and `RewriterBase::moveOpAfter` is no longer 
virtual. (The dialect conversion can gather all required information for 
rollbacks from listener notifications.)
---
 mlir/include/mlir/IR/PatternMatch.h   |  6 +-
 .../mlir/Transforms/DialectConversion.h   |  5 --
 .../Transforms/Utils/DialectConversion.cpp| 74 +++
 mlir/test/Transforms/test-legalizer.mlir  | 14 
 mlir/test/lib/Dialect/Test/TestPatterns.cpp   | 20 -
 5 files changed, 93 insertions(+), 26 deletions(-)

diff --git a/mlir/include/mlir/IR/PatternMatch.h 
b/mlir/include/mlir/IR/PatternMatch.h
index 78dcfe7f6fc3d2..b8aeea0d23475b 100644
--- a/mlir/include/mlir/IR/PatternMatch.h
+++ b/mlir/include/mlir/IR/PatternMatch.h
@@ -588,8 +588,7 @@ class RewriterBase : public OpBuilder {
 
   /// Unlink this operation from its current block and insert it right before
   /// `iterator` in the specified block.
-  virtual void moveOpBefore(Operation *op, Block *block,
-Block::iterator iterator);
+  void moveOpBefore(Operation *op, Block *block, Block::iterator iterator);
 
   /// Unlink this operation from its current block and insert it right after
   /// `existingOp` which may be in the same or another block in the same
@@ -598,8 +597,7 @@ class RewriterBase : public OpBuilder {
 
   /// Unlink this operation from its current block and insert it right after
   /// `iterator` in the specified block.
-  virtual void moveOpAfter(Operation *op, Block *block,
-   Block::iterator iterator);
+  void moveOpAfter(Operation *op, Block *block, Block::iterator iterator);
 
   /// Unlink this block and insert it right before `existingBlock`.
   void moveBlockBefore(Block *block, Block *anotherBlock);
diff --git a/mlir/include/mlir/Transforms/DialectConversion.h 
b/mlir/include/mlir/Transforms/DialectConversion.h
index f061d761ecefbb..c0c702a7d34821 100644
--- a/mlir/include/mlir/Transforms/DialectConversion.h
+++ b/mlir/include/mlir/Transforms/DialectConversion.h
@@ -738,11 +738,6 @@ class ConversionPatternRewriter final : public 
PatternRewriter {
   // Hide unsupported pattern rewriter API.
   using OpBuilder::setListener;
 
-  void moveOpBefore(Operation *op, Block *block,
-Block::iterator iterator) override;
-  void moveOpAfter(Operation *op, Block *block,
-   Block::iterator iterator) override;
-
   std::unique_ptr impl;
 };
 
diff --git a/mlir/lib/Transforms/Utils/DialectConversion.cpp 
b/mlir/lib/Transforms/Utils/DialectConversion.cpp
index 44c107c8733f3d..ffdb069f6e9b81 100644
--- a/mlir/lib/Transforms/Utils/DialectConversion.cpp
+++ b/mlir/lib/Transforms/Utils/DialectConversion.cpp
@@ -757,7 +757,8 @@ class RewriteAction {
 InlineBlock,
 MoveBlock,
 SplitBlock,
-BlockTypeConversion
+BlockTypeConversion,
+MoveOperation
   };
 
   virtual ~RewriteAction() = default;
@@ -970,6 +971,54 @@ class BlockTypeConversionAction : public BlockAction {
 
   void rollback() override;
 };
+
+/// An operation rewrite.
+class OperationAction : public RewriteAction {
+public:
+  /// Return the operation that this action operates on.
+  Operation *getOperation() const { return op; }
+
+  static bool classof(const RewriteAction *action) {
+return action->getKind() >= Kind::MoveOperation &&
+   action->getKind() <= Kind::MoveOperation;
+  }
+
+protected:
+  OperationAction(Kind kind, ConversionPatternRewriterImpl &rewriterImpl,
+  Operation *op)
+  : RewriteAction(kind, rewriterImpl), op(op) {}
+
+  // The operation that this action operates on.
+  Operation *op;
+};
+
+/// Rewrite action that represent the moving of a block.
+class MoveOperationAction : public OperationAction {
+public:
+  MoveOperationAction(ConversionPatternRewriterImpl &rewriterImpl,
+  Operation *op, Block *block, Operation *insertBeforeOp)
+  : OperationAction(Kind::MoveOperation, rewriterImpl, op), block(block),
+insertBeforeOp(insertBeforeOp) {}
+
+  static bool classof(const RewriteAction *action) {
+return action->getKind() == Kind::MoveOperation;
+  }
+
+  void rollback() override {
+// Move the operation back to its original pos

[llvm-branch-commits] [mlir] [mlir][Transforms] Support `moveOpBefore`/`After` in dialect conversion (PR #81240)

2024-02-09 Thread via llvm-branch-commits

llvmbot wrote:



@llvm/pr-subscribers-mlir-core

@llvm/pr-subscribers-mlir

Author: Matthias Springer (matthias-springer)


Changes

Add a new rewrite action for "operation movements". This action can roll back 
`moveOpBefore` and `moveOpAfter`.

`RewriterBase::moveOpBefore` and `RewriterBase::moveOpAfter` is no longer 
virtual. (The dialect conversion can gather all required information for 
rollbacks from listener notifications.)


---
Full diff: https://github.com/llvm/llvm-project/pull/81240.diff


5 Files Affected:

- (modified) mlir/include/mlir/IR/PatternMatch.h (+2-4) 
- (modified) mlir/include/mlir/Transforms/DialectConversion.h (-5) 
- (modified) mlir/lib/Transforms/Utils/DialectConversion.cpp (+59-15) 
- (modified) mlir/test/Transforms/test-legalizer.mlir (+14) 
- (modified) mlir/test/lib/Dialect/Test/TestPatterns.cpp (+18-2) 


``diff
diff --git a/mlir/include/mlir/IR/PatternMatch.h 
b/mlir/include/mlir/IR/PatternMatch.h
index 78dcfe7f6fc3d..b8aeea0d23475 100644
--- a/mlir/include/mlir/IR/PatternMatch.h
+++ b/mlir/include/mlir/IR/PatternMatch.h
@@ -588,8 +588,7 @@ class RewriterBase : public OpBuilder {
 
   /// Unlink this operation from its current block and insert it right before
   /// `iterator` in the specified block.
-  virtual void moveOpBefore(Operation *op, Block *block,
-Block::iterator iterator);
+  void moveOpBefore(Operation *op, Block *block, Block::iterator iterator);
 
   /// Unlink this operation from its current block and insert it right after
   /// `existingOp` which may be in the same or another block in the same
@@ -598,8 +597,7 @@ class RewriterBase : public OpBuilder {
 
   /// Unlink this operation from its current block and insert it right after
   /// `iterator` in the specified block.
-  virtual void moveOpAfter(Operation *op, Block *block,
-   Block::iterator iterator);
+  void moveOpAfter(Operation *op, Block *block, Block::iterator iterator);
 
   /// Unlink this block and insert it right before `existingBlock`.
   void moveBlockBefore(Block *block, Block *anotherBlock);
diff --git a/mlir/include/mlir/Transforms/DialectConversion.h 
b/mlir/include/mlir/Transforms/DialectConversion.h
index f061d761ecefb..c0c702a7d3482 100644
--- a/mlir/include/mlir/Transforms/DialectConversion.h
+++ b/mlir/include/mlir/Transforms/DialectConversion.h
@@ -738,11 +738,6 @@ class ConversionPatternRewriter final : public 
PatternRewriter {
   // Hide unsupported pattern rewriter API.
   using OpBuilder::setListener;
 
-  void moveOpBefore(Operation *op, Block *block,
-Block::iterator iterator) override;
-  void moveOpAfter(Operation *op, Block *block,
-   Block::iterator iterator) override;
-
   std::unique_ptr impl;
 };
 
diff --git a/mlir/lib/Transforms/Utils/DialectConversion.cpp 
b/mlir/lib/Transforms/Utils/DialectConversion.cpp
index 44c107c8733f3..ffdb069f6e9b8 100644
--- a/mlir/lib/Transforms/Utils/DialectConversion.cpp
+++ b/mlir/lib/Transforms/Utils/DialectConversion.cpp
@@ -757,7 +757,8 @@ class RewriteAction {
 InlineBlock,
 MoveBlock,
 SplitBlock,
-BlockTypeConversion
+BlockTypeConversion,
+MoveOperation
   };
 
   virtual ~RewriteAction() = default;
@@ -970,6 +971,54 @@ class BlockTypeConversionAction : public BlockAction {
 
   void rollback() override;
 };
+
+/// An operation rewrite.
+class OperationAction : public RewriteAction {
+public:
+  /// Return the operation that this action operates on.
+  Operation *getOperation() const { return op; }
+
+  static bool classof(const RewriteAction *action) {
+return action->getKind() >= Kind::MoveOperation &&
+   action->getKind() <= Kind::MoveOperation;
+  }
+
+protected:
+  OperationAction(Kind kind, ConversionPatternRewriterImpl &rewriterImpl,
+  Operation *op)
+  : RewriteAction(kind, rewriterImpl), op(op) {}
+
+  // The operation that this action operates on.
+  Operation *op;
+};
+
+/// Rewrite action that represent the moving of a block.
+class MoveOperationAction : public OperationAction {
+public:
+  MoveOperationAction(ConversionPatternRewriterImpl &rewriterImpl,
+  Operation *op, Block *block, Operation *insertBeforeOp)
+  : OperationAction(Kind::MoveOperation, rewriterImpl, op), block(block),
+insertBeforeOp(insertBeforeOp) {}
+
+  static bool classof(const RewriteAction *action) {
+return action->getKind() == Kind::MoveOperation;
+  }
+
+  void rollback() override {
+// Move the operation back to its original position.
+Block::iterator before =
+insertBeforeOp ? Block::iterator(insertBeforeOp) : block->end();
+block->getOperations().splice(before, op->getBlock()->getOperations(), op);
+  }
+
+private:
+  // The block in which this operation was previously contained.
+  Block *block;
+
+  // The original successor of this operation before it was moved. "nullptr" if
+  // this operation was the only operation i

[llvm-branch-commits] [llvm] PR for llvm/llvm-project#79718 (PR #81241)

2024-02-09 Thread via llvm-branch-commits

https://github.com/llvmbot milestoned 
https://github.com/llvm/llvm-project/pull/81241
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] PR for llvm/llvm-project#79718 (PR #81241)

2024-02-09 Thread via llvm-branch-commits

llvmbot wrote:

@arsenm What do you think about merging this PR to the release branch?

https://github.com/llvm/llvm-project/pull/81241
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] PR for llvm/llvm-project#79718 (PR #81241)

2024-02-09 Thread via llvm-branch-commits

https://github.com/llvmbot created 
https://github.com/llvm/llvm-project/pull/81241

resolves llvm/llvm-project#79718

>From 6be29b485c73478cf98fde223cbb5ba440dca464 Mon Sep 17 00:00:00 2001
From: Quentin Dian 
Date: Fri, 9 Feb 2024 15:29:05 +0800
Subject: [PATCH] [RegisterCoalescer] Clear instructions not recorded in
 `ErasedInstrs` but erased (#79820)

Fixes #79718. Fixes #71178.

The same instructions may exist in an iteration. We cannot immediately
delete instructions in `ErasedInstrs`.

(cherry picked from commit 95b14da678f4670283240ef4cf60f3a39bed97b4)
---
 llvm/lib/CodeGen/RegisterCoalescer.cpp|  27 ++-
 .../register-coalescer-crash-pr79718.mir  | 213 ++
 .../X86/PR71178-register-coalescer-crash.ll   | 103 +
 3 files changed, 338 insertions(+), 5 deletions(-)
 create mode 100644 
llvm/test/CodeGen/LoongArch/register-coalescer-crash-pr79718.mir
 create mode 100644 llvm/test/CodeGen/X86/PR71178-register-coalescer-crash.ll

diff --git a/llvm/lib/CodeGen/RegisterCoalescer.cpp 
b/llvm/lib/CodeGen/RegisterCoalescer.cpp
index cbb1a74049fbd..7e9c992031f8d 100644
--- a/llvm/lib/CodeGen/RegisterCoalescer.cpp
+++ b/llvm/lib/CodeGen/RegisterCoalescer.cpp
@@ -236,7 +236,8 @@ namespace {
 /// was successfully coalesced away. If it is not currently possible to
 /// coalesce this interval, but it may be possible if other things get
 /// coalesced, then it returns true by reference in 'Again'.
-bool joinCopy(MachineInstr *CopyMI, bool &Again);
+bool joinCopy(MachineInstr *CopyMI, bool &Again,
+  SmallPtrSetImpl &CurrentErasedInstrs);
 
 /// Attempt to join these two intervals.  On failure, this
 /// returns false.  The output "SrcInt" will not have been modified, so we
@@ -1964,7 +1965,9 @@ void 
RegisterCoalescer::setUndefOnPrunedSubRegUses(LiveInterval &LI,
   LIS->shrinkToUses(&LI);
 }
 
-bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
+bool RegisterCoalescer::joinCopy(
+MachineInstr *CopyMI, bool &Again,
+SmallPtrSetImpl &CurrentErasedInstrs) {
   Again = false;
   LLVM_DEBUG(dbgs() << LIS->getInstructionIndex(*CopyMI) << '\t' << *CopyMI);
 
@@ -2156,7 +2159,9 @@ bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, 
bool &Again) {
   // CopyMI has been erased by joinIntervals at this point. Remove it from
   // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
   // to the work list. This keeps ErasedInstrs from growing needlessly.
-  ErasedInstrs.erase(CopyMI);
+  if (ErasedInstrs.erase(CopyMI))
+// But we may encounter the instruction again in this iteration.
+CurrentErasedInstrs.insert(CopyMI);
 
   // Rewrite all SrcReg operands to DstReg.
   // Also update DstReg operands to include DstIdx if it is set.
@@ -3982,21 +3987,33 @@ void RegisterCoalescer::lateLiveIntervalUpdate() {
 bool RegisterCoalescer::
 copyCoalesceWorkList(MutableArrayRef CurrList) {
   bool Progress = false;
+  SmallPtrSet CurrentErasedInstrs;
   for (MachineInstr *&MI : CurrList) {
 if (!MI)
   continue;
 // Skip instruction pointers that have already been erased, for example by
 // dead code elimination.
-if (ErasedInstrs.count(MI)) {
+if (ErasedInstrs.count(MI) || CurrentErasedInstrs.count(MI)) {
   MI = nullptr;
   continue;
 }
 bool Again = false;
-bool Success = joinCopy(MI, Again);
+bool Success = joinCopy(MI, Again, CurrentErasedInstrs);
 Progress |= Success;
 if (Success || !Again)
   MI = nullptr;
   }
+  // Clear instructions not recorded in `ErasedInstrs` but erased.
+  if (!CurrentErasedInstrs.empty()) {
+for (MachineInstr *&MI : CurrList) {
+  if (MI && CurrentErasedInstrs.count(MI))
+MI = nullptr;
+}
+for (MachineInstr *&MI : WorkList) {
+  if (MI && CurrentErasedInstrs.count(MI))
+MI = nullptr;
+}
+  }
   return Progress;
 }
 
diff --git a/llvm/test/CodeGen/LoongArch/register-coalescer-crash-pr79718.mir 
b/llvm/test/CodeGen/LoongArch/register-coalescer-crash-pr79718.mir
new file mode 100644
index 0..9bbb579b762e6
--- /dev/null
+++ b/llvm/test/CodeGen/LoongArch/register-coalescer-crash-pr79718.mir
@@ -0,0 +1,213 @@
+# NOTE: Assertions have been autogenerated by utils/update_mir_test_checks.py 
UTC_ARGS: --version 4
+# RUN: llc -o - %s -mtriple=loongarch64 \
+# RUN:  -run-pass=register-coalescer -join-liveintervals=1 -join-splitedges=0 
| FileCheck %s
+
+---
+name:foo
+tracksRegLiveness: true
+body: |
+  ; CHECK-LABEL: name: foo
+  ; CHECK: bb.0:
+  ; CHECK-NEXT:   successors: %bb.1(0x8000)
+  ; CHECK-NEXT:   liveins: $r4, $r5, $r6, $r7, $r8
+  ; CHECK-NEXT: {{  $}}
+  ; CHECK-NEXT:   [[COPY:%[0-9]+]]:gpr = COPY $r8
+  ; CHECK-NEXT:   [[COPY1:%[0-9]+]]:gpr = COPY $r7
+  ; CHECK-NEXT:   [[COPY2:%[0-9]+]]:gpr = COPY $r6
+  ; CHECK-NEXT:   [[COPY3:%[0-9]+]]:gpr = COPY $r5
+  ; CHECK-NEXT:   [[COPY4:%[0-9]+]]:gpr = COPY $r4
+  ; CHECK-NEXT:   [[AN

[llvm-branch-commits] [llvm] PR for llvm/llvm-project#79718 (PR #81241)

2024-02-09 Thread via llvm-branch-commits

llvmbot wrote:




@llvm/pr-subscribers-llvm-regalloc

Author: None (llvmbot)


Changes

resolves llvm/llvm-project#79718

---
Full diff: https://github.com/llvm/llvm-project/pull/81241.diff


3 Files Affected:

- (modified) llvm/lib/CodeGen/RegisterCoalescer.cpp (+22-5) 
- (added) llvm/test/CodeGen/LoongArch/register-coalescer-crash-pr79718.mir 
(+213) 
- (added) llvm/test/CodeGen/X86/PR71178-register-coalescer-crash.ll (+103) 


``diff
diff --git a/llvm/lib/CodeGen/RegisterCoalescer.cpp 
b/llvm/lib/CodeGen/RegisterCoalescer.cpp
index cbb1a74049fbd..7e9c992031f8d 100644
--- a/llvm/lib/CodeGen/RegisterCoalescer.cpp
+++ b/llvm/lib/CodeGen/RegisterCoalescer.cpp
@@ -236,7 +236,8 @@ namespace {
 /// was successfully coalesced away. If it is not currently possible to
 /// coalesce this interval, but it may be possible if other things get
 /// coalesced, then it returns true by reference in 'Again'.
-bool joinCopy(MachineInstr *CopyMI, bool &Again);
+bool joinCopy(MachineInstr *CopyMI, bool &Again,
+  SmallPtrSetImpl &CurrentErasedInstrs);
 
 /// Attempt to join these two intervals.  On failure, this
 /// returns false.  The output "SrcInt" will not have been modified, so we
@@ -1964,7 +1965,9 @@ void 
RegisterCoalescer::setUndefOnPrunedSubRegUses(LiveInterval &LI,
   LIS->shrinkToUses(&LI);
 }
 
-bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
+bool RegisterCoalescer::joinCopy(
+MachineInstr *CopyMI, bool &Again,
+SmallPtrSetImpl &CurrentErasedInstrs) {
   Again = false;
   LLVM_DEBUG(dbgs() << LIS->getInstructionIndex(*CopyMI) << '\t' << *CopyMI);
 
@@ -2156,7 +2159,9 @@ bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, 
bool &Again) {
   // CopyMI has been erased by joinIntervals at this point. Remove it from
   // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
   // to the work list. This keeps ErasedInstrs from growing needlessly.
-  ErasedInstrs.erase(CopyMI);
+  if (ErasedInstrs.erase(CopyMI))
+// But we may encounter the instruction again in this iteration.
+CurrentErasedInstrs.insert(CopyMI);
 
   // Rewrite all SrcReg operands to DstReg.
   // Also update DstReg operands to include DstIdx if it is set.
@@ -3982,21 +3987,33 @@ void RegisterCoalescer::lateLiveIntervalUpdate() {
 bool RegisterCoalescer::
 copyCoalesceWorkList(MutableArrayRef CurrList) {
   bool Progress = false;
+  SmallPtrSet CurrentErasedInstrs;
   for (MachineInstr *&MI : CurrList) {
 if (!MI)
   continue;
 // Skip instruction pointers that have already been erased, for example by
 // dead code elimination.
-if (ErasedInstrs.count(MI)) {
+if (ErasedInstrs.count(MI) || CurrentErasedInstrs.count(MI)) {
   MI = nullptr;
   continue;
 }
 bool Again = false;
-bool Success = joinCopy(MI, Again);
+bool Success = joinCopy(MI, Again, CurrentErasedInstrs);
 Progress |= Success;
 if (Success || !Again)
   MI = nullptr;
   }
+  // Clear instructions not recorded in `ErasedInstrs` but erased.
+  if (!CurrentErasedInstrs.empty()) {
+for (MachineInstr *&MI : CurrList) {
+  if (MI && CurrentErasedInstrs.count(MI))
+MI = nullptr;
+}
+for (MachineInstr *&MI : WorkList) {
+  if (MI && CurrentErasedInstrs.count(MI))
+MI = nullptr;
+}
+  }
   return Progress;
 }
 
diff --git a/llvm/test/CodeGen/LoongArch/register-coalescer-crash-pr79718.mir 
b/llvm/test/CodeGen/LoongArch/register-coalescer-crash-pr79718.mir
new file mode 100644
index 0..9bbb579b762e6
--- /dev/null
+++ b/llvm/test/CodeGen/LoongArch/register-coalescer-crash-pr79718.mir
@@ -0,0 +1,213 @@
+# NOTE: Assertions have been autogenerated by utils/update_mir_test_checks.py 
UTC_ARGS: --version 4
+# RUN: llc -o - %s -mtriple=loongarch64 \
+# RUN:  -run-pass=register-coalescer -join-liveintervals=1 -join-splitedges=0 
| FileCheck %s
+
+---
+name:foo
+tracksRegLiveness: true
+body: |
+  ; CHECK-LABEL: name: foo
+  ; CHECK: bb.0:
+  ; CHECK-NEXT:   successors: %bb.1(0x8000)
+  ; CHECK-NEXT:   liveins: $r4, $r5, $r6, $r7, $r8
+  ; CHECK-NEXT: {{  $}}
+  ; CHECK-NEXT:   [[COPY:%[0-9]+]]:gpr = COPY $r8
+  ; CHECK-NEXT:   [[COPY1:%[0-9]+]]:gpr = COPY $r7
+  ; CHECK-NEXT:   [[COPY2:%[0-9]+]]:gpr = COPY $r6
+  ; CHECK-NEXT:   [[COPY3:%[0-9]+]]:gpr = COPY $r5
+  ; CHECK-NEXT:   [[COPY4:%[0-9]+]]:gpr = COPY $r4
+  ; CHECK-NEXT:   [[ANDI:%[0-9]+]]:gpr = ANDI [[COPY3]], 1
+  ; CHECK-NEXT:   [[ORI:%[0-9]+]]:gpr = ORI $r0, 1
+  ; CHECK-NEXT:   [[ANDI1:%[0-9]+]]:gpr = ANDI [[COPY2]], 1
+  ; CHECK-NEXT:   [[ANDI2:%[0-9]+]]:gpr = ANDI [[COPY1]], 1
+  ; CHECK-NEXT:   [[ANDI3:%[0-9]+]]:gpr = ANDI [[COPY]], 1
+  ; CHECK-NEXT:   [[COPY5:%[0-9]+]]:gpr = COPY $r0
+  ; CHECK-NEXT:   [[COPY6:%[0-9]+]]:gpr = COPY $r0
+  ; CHECK-NEXT: {{  $}}
+  ; CHECK-NEXT: bb.1:
+  ; CHECK-NEXT:   successors: %bb.2(0x8000)
+  ; CHECK-NEXT: {{  $}}
+  ; CHECK-NEXT:   [[COPY7:%[0-9

[llvm-branch-commits] [mlir] [mlir][Transforms][NFC] Turn in-place op modifications into `RewriteAction`s (PR #81245)

2024-02-09 Thread Matthias Springer via llvm-branch-commits

https://github.com/matthias-springer created 
https://github.com/llvm/llvm-project/pull/81245

This commit simplifies the internal state of the dialect conversion. A separate 
field for the previous state of in-place op modifications is no longer needed.

>From cdbd92786887ba8f801cb0c4299f708f0a410465 Mon Sep 17 00:00:00 2001
From: Matthias Springer 
Date: Fri, 9 Feb 2024 11:36:59 +
Subject: [PATCH] [mlir][Transforms][NFC] Turn in-place op modifications into
 `RewriteAction`s

This commit simplifies the internal state of the dialect conversion. A separate 
field for the previous state of in-place op modifications is no longer needed.
---
 .../Transforms/Utils/DialectConversion.cpp| 128 --
 1 file changed, 58 insertions(+), 70 deletions(-)

diff --git a/mlir/lib/Transforms/Utils/DialectConversion.cpp 
b/mlir/lib/Transforms/Utils/DialectConversion.cpp
index ffdb069f6e9b81..d0114a148cd374 100644
--- a/mlir/lib/Transforms/Utils/DialectConversion.cpp
+++ b/mlir/lib/Transforms/Utils/DialectConversion.cpp
@@ -154,15 +154,13 @@ namespace {
 struct RewriterState {
   RewriterState(unsigned numCreatedOps, unsigned numUnresolvedMaterializations,
 unsigned numReplacements, unsigned numArgReplacements,
-unsigned numRewriteActions, unsigned numIgnoredOperations,
-unsigned numRootUpdates)
+unsigned numRewriteActions, unsigned numIgnoredOperations)
   : numCreatedOps(numCreatedOps),
 numUnresolvedMaterializations(numUnresolvedMaterializations),
 numReplacements(numReplacements),
 numArgReplacements(numArgReplacements),
 numRewriteActions(numRewriteActions),
-numIgnoredOperations(numIgnoredOperations),
-numRootUpdates(numRootUpdates) {}
+numIgnoredOperations(numIgnoredOperations) {}
 
   /// The current number of created operations.
   unsigned numCreatedOps;
@@ -181,44 +179,6 @@ struct RewriterState {
 
   /// The current number of ignored operations.
   unsigned numIgnoredOperations;
-
-  /// The current number of operations that were updated in place.
-  unsigned numRootUpdates;
-};
-
-//===--===//
-// OperationTransactionState
-
-/// The state of an operation that was updated by a pattern in-place. This
-/// contains all of the necessary information to reconstruct an operation that
-/// was updated in place.
-class OperationTransactionState {
-public:
-  OperationTransactionState() = default;
-  OperationTransactionState(Operation *op)
-  : op(op), loc(op->getLoc()), attrs(op->getAttrDictionary()),
-operands(op->operand_begin(), op->operand_end()),
-successors(op->successor_begin(), op->successor_end()) {}
-
-  /// Discard the transaction state and reset the state of the original
-  /// operation.
-  void resetOperation() const {
-op->setLoc(loc);
-op->setAttrs(attrs);
-op->setOperands(operands);
-for (const auto &it : llvm::enumerate(successors))
-  op->setSuccessor(it.value(), it.index());
-  }
-
-  /// Return the original operation of this state.
-  Operation *getOperation() const { return op; }
-
-private:
-  Operation *op;
-  LocationAttr loc;
-  DictionaryAttr attrs;
-  SmallVector operands;
-  SmallVector successors;
 };
 
 
//===--===//
@@ -758,7 +718,8 @@ class RewriteAction {
 MoveBlock,
 SplitBlock,
 BlockTypeConversion,
-MoveOperation
+MoveOperation,
+ModifyOperation
   };
 
   virtual ~RewriteAction() = default;
@@ -980,7 +941,7 @@ class OperationAction : public RewriteAction {
 
   static bool classof(const RewriteAction *action) {
 return action->getKind() >= Kind::MoveOperation &&
-   action->getKind() <= Kind::MoveOperation;
+   action->getKind() <= Kind::ModifyOperation;
   }
 
 protected:
@@ -1019,6 +980,34 @@ class MoveOperationAction : public OperationAction {
   // this operation was the only operation in the region.
   Operation *insertBeforeOp;
 };
+
+/// Rewrite action that represents the in-place modification of an operation.
+/// The previous state of the operation is stored in this action.
+class ModifyOperationAction : public OperationAction {
+public:
+  ModifyOperationAction(ConversionPatternRewriterImpl &rewriterImpl,
+Operation *op)
+  : OperationAction(Kind::ModifyOperation, rewriterImpl, op),
+loc(op->getLoc()), attrs(op->getAttrDictionary()),
+operands(op->operand_begin(), op->operand_end()),
+successors(op->successor_begin(), op->successor_end()) {}
+
+  /// Discard the transaction state and reset the state of the original
+  /// operation.
+  void rollback() override {
+op->setLoc(loc);
+op->setAttrs(attrs);
+op->setOperands(operands);
+for (const auto &it : llvm::enumerate(successors))
+  op->setSuccessor(it.value(), it.index());
+  }
+
+private:
+

[llvm-branch-commits] [mlir] [mlir][Transforms][NFC] Turn in-place op modifications into `RewriteAction`s (PR #81245)

2024-02-09 Thread via llvm-branch-commits

llvmbot wrote:



@llvm/pr-subscribers-mlir-core

@llvm/pr-subscribers-mlir

Author: Matthias Springer (matthias-springer)


Changes

This commit simplifies the internal state of the dialect conversion. A separate 
field for the previous state of in-place op modifications is no longer needed.

---
Full diff: https://github.com/llvm/llvm-project/pull/81245.diff


1 Files Affected:

- (modified) mlir/lib/Transforms/Utils/DialectConversion.cpp (+58-70) 


``diff
diff --git a/mlir/lib/Transforms/Utils/DialectConversion.cpp 
b/mlir/lib/Transforms/Utils/DialectConversion.cpp
index ffdb069f6e9b8..d0114a148cd37 100644
--- a/mlir/lib/Transforms/Utils/DialectConversion.cpp
+++ b/mlir/lib/Transforms/Utils/DialectConversion.cpp
@@ -154,15 +154,13 @@ namespace {
 struct RewriterState {
   RewriterState(unsigned numCreatedOps, unsigned numUnresolvedMaterializations,
 unsigned numReplacements, unsigned numArgReplacements,
-unsigned numRewriteActions, unsigned numIgnoredOperations,
-unsigned numRootUpdates)
+unsigned numRewriteActions, unsigned numIgnoredOperations)
   : numCreatedOps(numCreatedOps),
 numUnresolvedMaterializations(numUnresolvedMaterializations),
 numReplacements(numReplacements),
 numArgReplacements(numArgReplacements),
 numRewriteActions(numRewriteActions),
-numIgnoredOperations(numIgnoredOperations),
-numRootUpdates(numRootUpdates) {}
+numIgnoredOperations(numIgnoredOperations) {}
 
   /// The current number of created operations.
   unsigned numCreatedOps;
@@ -181,44 +179,6 @@ struct RewriterState {
 
   /// The current number of ignored operations.
   unsigned numIgnoredOperations;
-
-  /// The current number of operations that were updated in place.
-  unsigned numRootUpdates;
-};
-
-//===--===//
-// OperationTransactionState
-
-/// The state of an operation that was updated by a pattern in-place. This
-/// contains all of the necessary information to reconstruct an operation that
-/// was updated in place.
-class OperationTransactionState {
-public:
-  OperationTransactionState() = default;
-  OperationTransactionState(Operation *op)
-  : op(op), loc(op->getLoc()), attrs(op->getAttrDictionary()),
-operands(op->operand_begin(), op->operand_end()),
-successors(op->successor_begin(), op->successor_end()) {}
-
-  /// Discard the transaction state and reset the state of the original
-  /// operation.
-  void resetOperation() const {
-op->setLoc(loc);
-op->setAttrs(attrs);
-op->setOperands(operands);
-for (const auto &it : llvm::enumerate(successors))
-  op->setSuccessor(it.value(), it.index());
-  }
-
-  /// Return the original operation of this state.
-  Operation *getOperation() const { return op; }
-
-private:
-  Operation *op;
-  LocationAttr loc;
-  DictionaryAttr attrs;
-  SmallVector operands;
-  SmallVector successors;
 };
 
 
//===--===//
@@ -758,7 +718,8 @@ class RewriteAction {
 MoveBlock,
 SplitBlock,
 BlockTypeConversion,
-MoveOperation
+MoveOperation,
+ModifyOperation
   };
 
   virtual ~RewriteAction() = default;
@@ -980,7 +941,7 @@ class OperationAction : public RewriteAction {
 
   static bool classof(const RewriteAction *action) {
 return action->getKind() >= Kind::MoveOperation &&
-   action->getKind() <= Kind::MoveOperation;
+   action->getKind() <= Kind::ModifyOperation;
   }
 
 protected:
@@ -1019,6 +980,34 @@ class MoveOperationAction : public OperationAction {
   // this operation was the only operation in the region.
   Operation *insertBeforeOp;
 };
+
+/// Rewrite action that represents the in-place modification of an operation.
+/// The previous state of the operation is stored in this action.
+class ModifyOperationAction : public OperationAction {
+public:
+  ModifyOperationAction(ConversionPatternRewriterImpl &rewriterImpl,
+Operation *op)
+  : OperationAction(Kind::ModifyOperation, rewriterImpl, op),
+loc(op->getLoc()), attrs(op->getAttrDictionary()),
+operands(op->operand_begin(), op->operand_end()),
+successors(op->successor_begin(), op->successor_end()) {}
+
+  /// Discard the transaction state and reset the state of the original
+  /// operation.
+  void rollback() override {
+op->setLoc(loc);
+op->setAttrs(attrs);
+op->setOperands(operands);
+for (const auto &it : llvm::enumerate(successors))
+  op->setSuccessor(it.value(), it.index());
+  }
+
+private:
+  LocationAttr loc;
+  DictionaryAttr attrs;
+  SmallVector operands;
+  SmallVector successors;
+};
 } // namespace
 
 
//===--===//
@@ -1172,9 +1161,6 @@ struct ConversionPatternRewriterImpl : public 
RewriterBase::Listener {
   /// o

[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Peter Smith via llvm-branch-commits


@@ -1124,11 +1127,15 @@ template  void 
Writer::setReservedSymbolSections() {
   }
 
   if (last) {
-// _edata points to the end of the last mapped initialized section.
+// _edata points to the end of the last mapped initialized section before

smithp35 wrote:

Apart from the comment about .ldata may be after _edata, is this something we 
had wrong prior to this patch?

If so it could be worth splitting out into a separate patch so we can 
identify/test it separately. Ideally we'd want a test case for each of the 
conditions below. 

https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Peter Smith via llvm-branch-commits

https://github.com/smithp35 edited 
https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Peter Smith via llvm-branch-commits

https://github.com/smithp35 commented:

Matching GNU ld seems sensible to me, although best get this reviewed by 
someone with an X86_64 background.

https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] PR for llvm/llvm-project#79718 (PR #81241)

2024-02-09 Thread Matt Arsenault via llvm-branch-commits

https://github.com/arsenm approved this pull request.


https://github.com/llvm/llvm-project/pull/81241
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [TBAA] Only clear TBAAStruct if field can be extracted. (PR #81285)

2024-02-09 Thread Florian Hahn via llvm-branch-commits

https://github.com/fhahn created https://github.com/llvm/llvm-project/pull/81285

Retain TBAAStruct if we fail to match the access to a single field. All users 
at the moment use this when using the full size of the original access. SROA 
also retains the original TBAAStruct when accessing parts at offset 0.

Motivation for this and follow-on patches is to improve codegen for libc++, 
where using memcpy limits optimizations, like vectorization for code iteration 
over std::vector>: https://godbolt.org/z/f3vqYos3c

Depends on https://github.com/llvm/llvm-project/pull/81284

>From 99cf032dfabb21b820559bae61d2354e56336fdd Mon Sep 17 00:00:00 2001
From: Florian Hahn 
Date: Fri, 9 Feb 2024 16:25:32 +
Subject: [PATCH] [TBAA] Only clear TBAAStruct if field can be extracted.

Retain TBAAStruct if we fail to match the access to a single field. All
users at the moment use this when using the full size of the original
access. SROA also retains the original TBAAStruct when accessing parts
at offset 0.

Motivation for this and follow-on patches is to improve codegen for
libc++, where using memcpy limits optimizations, like vectorization for
code iteration over std::vector>:
https://godbolt.org/z/f3vqYos3c

Depends on https://github.com/llvm/llvm-project/pull/81284
---
 llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp   | 8 +---
 llvm/test/Transforms/InstCombine/struct-assign-tbaa.ll | 5 +++--
 2 files changed, 8 insertions(+), 5 deletions(-)

diff --git a/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp 
b/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
index edc08cde686f1f..bfd70414c0340c 100644
--- a/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
+++ b/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
@@ -821,13 +821,15 @@ MDNode *AAMDNodes::extendToTBAA(MDNode *MD, ssize_t Len) {
 AAMDNodes AAMDNodes::adjustForAccess(unsigned AccessSize) {
   AAMDNodes New = *this;
   MDNode *M = New.TBAAStruct;
-  New.TBAAStruct = nullptr;
   if (M && M->getNumOperands() == 3 && M->getOperand(0) &&
   mdconst::hasa(M->getOperand(0)) &&
   mdconst::extract(M->getOperand(0))->isZero() &&
   M->getOperand(1) && mdconst::hasa(M->getOperand(1)) &&
-  mdconst::extract(M->getOperand(1))->getValue() == 
AccessSize &&
-  M->getOperand(2) && isa(M->getOperand(2)))
+  mdconst::extract(M->getOperand(1))->getValue() ==
+  AccessSize &&
+  M->getOperand(2) && isa(M->getOperand(2))) {
+New.TBAAStruct = nullptr;
 New.TBAA = cast(M->getOperand(2));
+  }
   return New;
 }
diff --git a/llvm/test/Transforms/InstCombine/struct-assign-tbaa.ll 
b/llvm/test/Transforms/InstCombine/struct-assign-tbaa.ll
index 1042c413fbb7bb..996d2c0e67e165 100644
--- a/llvm/test/Transforms/InstCombine/struct-assign-tbaa.ll
+++ b/llvm/test/Transforms/InstCombine/struct-assign-tbaa.ll
@@ -38,8 +38,8 @@ define ptr @test2() {
 define void @test3_multiple_fields(ptr nocapture %a, ptr nocapture %b) {
 ; CHECK-LABEL: @test3_multiple_fields(
 ; CHECK-NEXT:  entry:
-; CHECK-NEXT:[[TMP0:%.*]] = load i64, ptr [[B:%.*]], align 4
-; CHECK-NEXT:store i64 [[TMP0]], ptr [[A:%.*]], align 4
+; CHECK-NEXT:[[TMP0:%.*]] = load i64, ptr [[B:%.*]], align 4, !tbaa.struct 
[[TBAA_STRUCT3:![0-9]+]]
+; CHECK-NEXT:store i64 [[TMP0]], ptr [[A:%.*]], align 4, !tbaa.struct 
[[TBAA_STRUCT3]]
 ; CHECK-NEXT:ret void
 ;
 entry:
@@ -86,4 +86,5 @@ entry:
 ; CHECK: [[TBAA0]] = !{[[META1:![0-9]+]], [[META1]], i64 0}
 ; CHECK: [[META1]] = !{!"float", [[META2:![0-9]+]]}
 ; CHECK: [[META2]] = !{!"Simple C/C++ TBAA"}
+; CHECK: [[TBAA_STRUCT3]] = !{i64 0, i64 4, [[TBAA0]], i64 4, i64 4, [[TBAA0]]}
 ;.

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


[llvm-branch-commits] [llvm] [TBAA] Only clear TBAAStruct if field can be extracted. (PR #81285)

2024-02-09 Thread via llvm-branch-commits

llvmbot wrote:



@llvm/pr-subscribers-llvm-transforms

@llvm/pr-subscribers-llvm-analysis

Author: Florian Hahn (fhahn)


Changes

Retain TBAAStruct if we fail to match the access to a single field. All users 
at the moment use this when using the full size of the original access. SROA 
also retains the original TBAAStruct when accessing parts at offset 0.

Motivation for this and follow-on patches is to improve codegen for libc++, 
where using memcpy limits optimizations, like vectorization for code iteration 
over std::vector>: 
https://godbolt.org/z/f3vqYos3c

Depends on https://github.com/llvm/llvm-project/pull/81284

---
Full diff: https://github.com/llvm/llvm-project/pull/81285.diff


2 Files Affected:

- (modified) llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp (+5-3) 
- (modified) llvm/test/Transforms/InstCombine/struct-assign-tbaa.ll (+3-2) 


``diff
diff --git a/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp 
b/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
index edc08cde686f1f..bfd70414c0340c 100644
--- a/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
+++ b/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
@@ -821,13 +821,15 @@ MDNode *AAMDNodes::extendToTBAA(MDNode *MD, ssize_t Len) {
 AAMDNodes AAMDNodes::adjustForAccess(unsigned AccessSize) {
   AAMDNodes New = *this;
   MDNode *M = New.TBAAStruct;
-  New.TBAAStruct = nullptr;
   if (M && M->getNumOperands() == 3 && M->getOperand(0) &&
   mdconst::hasa(M->getOperand(0)) &&
   mdconst::extract(M->getOperand(0))->isZero() &&
   M->getOperand(1) && mdconst::hasa(M->getOperand(1)) &&
-  mdconst::extract(M->getOperand(1))->getValue() == 
AccessSize &&
-  M->getOperand(2) && isa(M->getOperand(2)))
+  mdconst::extract(M->getOperand(1))->getValue() ==
+  AccessSize &&
+  M->getOperand(2) && isa(M->getOperand(2))) {
+New.TBAAStruct = nullptr;
 New.TBAA = cast(M->getOperand(2));
+  }
   return New;
 }
diff --git a/llvm/test/Transforms/InstCombine/struct-assign-tbaa.ll 
b/llvm/test/Transforms/InstCombine/struct-assign-tbaa.ll
index 1042c413fbb7bb..996d2c0e67e165 100644
--- a/llvm/test/Transforms/InstCombine/struct-assign-tbaa.ll
+++ b/llvm/test/Transforms/InstCombine/struct-assign-tbaa.ll
@@ -38,8 +38,8 @@ define ptr @test2() {
 define void @test3_multiple_fields(ptr nocapture %a, ptr nocapture %b) {
 ; CHECK-LABEL: @test3_multiple_fields(
 ; CHECK-NEXT:  entry:
-; CHECK-NEXT:[[TMP0:%.*]] = load i64, ptr [[B:%.*]], align 4
-; CHECK-NEXT:store i64 [[TMP0]], ptr [[A:%.*]], align 4
+; CHECK-NEXT:[[TMP0:%.*]] = load i64, ptr [[B:%.*]], align 4, !tbaa.struct 
[[TBAA_STRUCT3:![0-9]+]]
+; CHECK-NEXT:store i64 [[TMP0]], ptr [[A:%.*]], align 4, !tbaa.struct 
[[TBAA_STRUCT3]]
 ; CHECK-NEXT:ret void
 ;
 entry:
@@ -86,4 +86,5 @@ entry:
 ; CHECK: [[TBAA0]] = !{[[META1:![0-9]+]], [[META1]], i64 0}
 ; CHECK: [[META1]] = !{!"float", [[META2:![0-9]+]]}
 ; CHECK: [[META2]] = !{!"Simple C/C++ TBAA"}
+; CHECK: [[TBAA_STRUCT3]] = !{i64 0, i64 4, [[TBAA0]], i64 4, i64 4, [[TBAA0]]}
 ;.

``




https://github.com/llvm/llvm-project/pull/81285
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Arthur Eubanks via llvm-branch-commits


@@ -988,10 +991,10 @@ static unsigned getSectionRank(OutputSection &osec) {
   osec.relro = true;
 else
   rank |= RF_NOT_RELRO;
-// Place .ldata and .lbss after .bss. Making .bss closer to .text 
alleviates
-// relocation overflow pressure.
+// Place .lbss/.lrodata/.ldata after .bss. .bss/.lbss being adjacent reuses
+// the NOBITS size optimization.
 if (osec.flags & SHF_X86_64_LARGE && config->emachine == EM_X86_64)
-  rank |= RF_LARGE;
+  rank |= osec.type == SHT_NOBITS ? 1 : RF_LARGE;

aeubanks wrote:

the `1` should have a `RF_*` name to better express intent

https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Arthur Eubanks via llvm-branch-commits


@@ -1124,11 +1127,15 @@ template  void 
Writer::setReservedSymbolSections() {
   }
 
   if (last) {
-// _edata points to the end of the last mapped initialized section.
+// _edata points to the end of the last mapped initialized section before

aeubanks wrote:

+1

https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Arthur Eubanks via llvm-branch-commits

aeubanks wrote:

thanks for doing this!

https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [SROA] Use !tbaa instead of !tbaa.struct if op matches field. (PR #81289)

2024-02-09 Thread Florian Hahn via llvm-branch-commits

https://github.com/fhahn created https://github.com/llvm/llvm-project/pull/81289

If a split memory access introduced by SROA accesses precisely a single field 
of the original operation's !tbaa.struct, use the !tbaa tag for the accessed 
field directly instead of the full !tbaa.struct.

InstCombine already had a similar logic.

Motivation for this and follow-on patches is to improve codegen for libc++, 
where using memcpy limits optimizations, like vectorization for code iteration 
over std::vector>: https://godbolt.org/z/f3vqYos3c

Depends on https://github.com/llvm/llvm-project/pull/81285.

>From 90639e9131670863ebb4c199a9861b2b0094d601 Mon Sep 17 00:00:00 2001
From: Florian Hahn 
Date: Fri, 9 Feb 2024 15:17:09 +
Subject: [PATCH] [SROA] Use !tbaa instead of !tbaa.struct if op matches field.

If a split memory access introduced by SROA accesses precisely a single
field of the original operation's !tbaa.struct, use the !tbaa tag for
the accessed field directly instead of the full !tbaa.struct.

InstCombine already had a similar logic.

Motivation for this and follow-on patches is to improve codegen for
libc++, where using memcpy limits optimizations, like vectorization for
code iteration over std::vector>:
https://godbolt.org/z/f3vqYos3c

Depends on https://github.com/llvm/llvm-project/pull/81285.
---
 llvm/include/llvm/IR/Metadata.h  |  2 +
 llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp | 13 ++
 llvm/lib/Transforms/Scalar/SROA.cpp  | 48 ++--
 llvm/test/Transforms/SROA/tbaa-struct2.ll| 21 -
 llvm/test/Transforms/SROA/tbaa-struct3.ll| 16 +++
 5 files changed, 67 insertions(+), 33 deletions(-)

diff --git a/llvm/include/llvm/IR/Metadata.h b/llvm/include/llvm/IR/Metadata.h
index 6f23ac44dee968..33363a271d4823 100644
--- a/llvm/include/llvm/IR/Metadata.h
+++ b/llvm/include/llvm/IR/Metadata.h
@@ -849,6 +849,8 @@ struct AAMDNodes {
   /// If his AAMDNode has !tbaa.struct and \p AccessSize matches the size of 
the
   /// field at offset 0, get the TBAA tag describing the accessed field.
   AAMDNodes adjustForAccess(unsigned AccessSize);
+  AAMDNodes adjustForAccess(size_t Offset, Type *AccessTy,
+const DataLayout &DL);
 };
 
 // Specialize DenseMapInfo for AAMDNodes.
diff --git a/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp 
b/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
index bfd70414c0340c..b2dc451d581939 100644
--- a/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
+++ b/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
@@ -833,3 +833,16 @@ AAMDNodes AAMDNodes::adjustForAccess(unsigned AccessSize) {
   }
   return New;
 }
+
+AAMDNodes AAMDNodes::adjustForAccess(size_t Offset, Type *AccessTy,
+ const DataLayout &DL) {
+
+  AAMDNodes New = shift(Offset);
+  if (!DL.typeSizeEqualsStoreSize(AccessTy))
+return New;
+  TypeSize Size = DL.getTypeStoreSize(AccessTy);
+  if (Size.isScalable())
+return New;
+
+  return New.adjustForAccess(Size.getKnownMinValue());
+}
diff --git a/llvm/lib/Transforms/Scalar/SROA.cpp 
b/llvm/lib/Transforms/Scalar/SROA.cpp
index 138dc38b5c14ce..f24cbbc1fe0591 100644
--- a/llvm/lib/Transforms/Scalar/SROA.cpp
+++ b/llvm/lib/Transforms/Scalar/SROA.cpp
@@ -2914,7 +2914,8 @@ class AllocaSliceRewriter : public 
InstVisitor {
 
   // Do this after copyMetadataForLoad() to preserve the TBAA shift.
   if (AATags)
-NewLI->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
+NewLI->setAAMetadata(AATags.adjustForAccess(
+NewBeginOffset - BeginOffset, NewLI->getType(), DL));
 
   // Try to preserve nonnull metadata
   V = NewLI;
@@ -2936,7 +2937,9 @@ class AllocaSliceRewriter : public 
InstVisitor {
   IRB.CreateAlignedLoad(TargetTy, getNewAllocaSlicePtr(IRB, LTy),
 getSliceAlign(), LI.isVolatile(), 
LI.getName());
   if (AATags)
-NewLI->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
+NewLI->setAAMetadata(AATags.adjustForAccess(
+NewBeginOffset - BeginOffset, NewLI->getType(), DL));
+
   if (LI.isVolatile())
 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
   NewLI->copyMetadata(LI, {LLVMContext::MD_mem_parallel_loop_access,
@@ -3011,7 +3014,8 @@ class AllocaSliceRewriter : public 
InstVisitor {
 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
  LLVMContext::MD_access_group});
 if (AATags)
-  Store->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
+  Store->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
+  V->getType(), DL));
 Pass.DeadInsts.push_back(&SI);
 
 // NOTE: Careful to use OrigV rather than V.
@@ -3038,7 +3042,8 @@ class AllocaSliceRewriter : public 
InstVisitor {
 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,

[llvm-branch-commits] [llvm] [SROA] Use !tbaa instead of !tbaa.struct if op matches field. (PR #81289)

2024-02-09 Thread via llvm-branch-commits

llvmbot wrote:



@llvm/pr-subscribers-llvm-ir

@llvm/pr-subscribers-llvm-transforms

Author: Florian Hahn (fhahn)


Changes

If a split memory access introduced by SROA accesses precisely a single field 
of the original operation's !tbaa.struct, use the !tbaa tag for the accessed 
field directly instead of the full !tbaa.struct.

InstCombine already had a similar logic.

Motivation for this and follow-on patches is to improve codegen for libc++, 
where using memcpy limits optimizations, like vectorization for code iteration 
over std::vector>: 
https://godbolt.org/z/f3vqYos3c

Depends on https://github.com/llvm/llvm-project/pull/81285.

---
Full diff: https://github.com/llvm/llvm-project/pull/81289.diff


5 Files Affected:

- (modified) llvm/include/llvm/IR/Metadata.h (+2) 
- (modified) llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp (+13) 
- (modified) llvm/lib/Transforms/Scalar/SROA.cpp (+34-14) 
- (modified) llvm/test/Transforms/SROA/tbaa-struct2.ll (+10-11) 
- (modified) llvm/test/Transforms/SROA/tbaa-struct3.ll (+8-8) 


``diff
diff --git a/llvm/include/llvm/IR/Metadata.h b/llvm/include/llvm/IR/Metadata.h
index 6f23ac44dee968..33363a271d4823 100644
--- a/llvm/include/llvm/IR/Metadata.h
+++ b/llvm/include/llvm/IR/Metadata.h
@@ -849,6 +849,8 @@ struct AAMDNodes {
   /// If his AAMDNode has !tbaa.struct and \p AccessSize matches the size of 
the
   /// field at offset 0, get the TBAA tag describing the accessed field.
   AAMDNodes adjustForAccess(unsigned AccessSize);
+  AAMDNodes adjustForAccess(size_t Offset, Type *AccessTy,
+const DataLayout &DL);
 };
 
 // Specialize DenseMapInfo for AAMDNodes.
diff --git a/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp 
b/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
index bfd70414c0340c..b2dc451d581939 100644
--- a/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
+++ b/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
@@ -833,3 +833,16 @@ AAMDNodes AAMDNodes::adjustForAccess(unsigned AccessSize) {
   }
   return New;
 }
+
+AAMDNodes AAMDNodes::adjustForAccess(size_t Offset, Type *AccessTy,
+ const DataLayout &DL) {
+
+  AAMDNodes New = shift(Offset);
+  if (!DL.typeSizeEqualsStoreSize(AccessTy))
+return New;
+  TypeSize Size = DL.getTypeStoreSize(AccessTy);
+  if (Size.isScalable())
+return New;
+
+  return New.adjustForAccess(Size.getKnownMinValue());
+}
diff --git a/llvm/lib/Transforms/Scalar/SROA.cpp 
b/llvm/lib/Transforms/Scalar/SROA.cpp
index 138dc38b5c14ce..f24cbbc1fe0591 100644
--- a/llvm/lib/Transforms/Scalar/SROA.cpp
+++ b/llvm/lib/Transforms/Scalar/SROA.cpp
@@ -2914,7 +2914,8 @@ class AllocaSliceRewriter : public 
InstVisitor {
 
   // Do this after copyMetadataForLoad() to preserve the TBAA shift.
   if (AATags)
-NewLI->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
+NewLI->setAAMetadata(AATags.adjustForAccess(
+NewBeginOffset - BeginOffset, NewLI->getType(), DL));
 
   // Try to preserve nonnull metadata
   V = NewLI;
@@ -2936,7 +2937,9 @@ class AllocaSliceRewriter : public 
InstVisitor {
   IRB.CreateAlignedLoad(TargetTy, getNewAllocaSlicePtr(IRB, LTy),
 getSliceAlign(), LI.isVolatile(), 
LI.getName());
   if (AATags)
-NewLI->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
+NewLI->setAAMetadata(AATags.adjustForAccess(
+NewBeginOffset - BeginOffset, NewLI->getType(), DL));
+
   if (LI.isVolatile())
 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
   NewLI->copyMetadata(LI, {LLVMContext::MD_mem_parallel_loop_access,
@@ -3011,7 +3014,8 @@ class AllocaSliceRewriter : public 
InstVisitor {
 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
  LLVMContext::MD_access_group});
 if (AATags)
-  Store->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
+  Store->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
+  V->getType(), DL));
 Pass.DeadInsts.push_back(&SI);
 
 // NOTE: Careful to use OrigV rather than V.
@@ -3038,7 +3042,8 @@ class AllocaSliceRewriter : public 
InstVisitor {
 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
  LLVMContext::MD_access_group});
 if (AATags)
-  Store->setAAMetadata(AATags.shift(NewBeginOffset - BeginOffset));
+  Store->setAAMetadata(AATags.adjustForAccess(NewBeginOffset - BeginOffset,
+  V->getType(), DL));
 
 migrateDebugInfo(&OldAI, IsSplit, NewBeginOffset * 8, SliceSize * 8, &SI,
  Store, Store->getPointerOperand(),
@@ -3097,8 +3102,10 @@ class AllocaSliceRewriter : public 
InstVisitor {
 }
 NewSI->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
  LLVMContext::

[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Fangrui Song via llvm-branch-commits


@@ -988,10 +991,10 @@ static unsigned getSectionRank(OutputSection &osec) {
   osec.relro = true;
 else
   rank |= RF_NOT_RELRO;
-// Place .ldata and .lbss after .bss. Making .bss closer to .text 
alleviates
-// relocation overflow pressure.
+// Place .lbss/.lrodata/.ldata after .bss. .bss/.lbss being adjacent reuses
+// the NOBITS size optimization.
 if (osec.flags & SHF_X86_64_LARGE && config->emachine == EM_X86_64)
-  rank |= RF_LARGE;
+  rank |= osec.type == SHT_NOBITS ? 1 : RF_LARGE;

MaskRay wrote:

I think we can treat `RF_*` as defining larger regions and integer immediates 
as a mechanism to pick a subregion within a larger region. The immediate use 
here is similar to `.interp/SHT_NOTE` and target-specific tunings (`.sdata`, 
`.got`, etc).

https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [TBAA] Only clear TBAAStruct if field can be extracted. (PR #81285)

2024-02-09 Thread via llvm-branch-commits

dobbelaj-snps wrote:

IMHO this testcase should be adapted to always take the tail of the lines into 
account for FileCheck. (aka, to ensure that lines that we do not expect to have 
a !tbaa.struct metadata check that)

https://github.com/llvm/llvm-project/pull/81285
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [TBAA] Only clear TBAAStruct if field can be extracted. (PR #81285)

2024-02-09 Thread via llvm-branch-commits


@@ -821,13 +821,15 @@ MDNode *AAMDNodes::extendToTBAA(MDNode *MD, ssize_t Len) {
 AAMDNodes AAMDNodes::adjustForAccess(unsigned AccessSize) {
   AAMDNodes New = *this;
   MDNode *M = New.TBAAStruct;
-  New.TBAAStruct = nullptr;
   if (M && M->getNumOperands() == 3 && M->getOperand(0) &&

dobbelaj-snps wrote:

Isn't this too strict ? Typically the TBAAStruct have operands in multiple of 3 
describing {offset, size, type }.

You can extract the 'first member' instead of matching the full struct. (Note: 
if we accept to track unions in more detail, this might get more complicated)

https://github.com/llvm/llvm-project/pull/81285
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [SROA] Use !tbaa instead of !tbaa.struct if op matches field. (PR #81289)

2024-02-09 Thread via llvm-branch-commits


@@ -4561,6 +4577,10 @@ bool SROA::presplitLoadsAndStores(AllocaInst &AI, 
AllocaSlices &AS) {
 PStore->copyMetadata(*SI, {LLVMContext::MD_mem_parallel_loop_access,
LLVMContext::MD_access_group,
LLVMContext::MD_DIAssignID});
+
+if (AATags)
+  PStore->setAAMetadata(

dobbelaj-snps wrote:

Is this part covered in a testcase ?

https://github.com/llvm/llvm-project/pull/81289
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [SROA] Use !tbaa instead of !tbaa.struct if op matches field. (PR #81289)

2024-02-09 Thread via llvm-branch-commits


@@ -7,9 +7,9 @@ define void @load_store_transfer_split_struct_tbaa_2_float(ptr 
dereferenceable(2
 ; CHECK-NEXT:  entry:
 ; CHECK-NEXT:[[TMP0:%.*]] = bitcast float [[A]] to i32
 ; CHECK-NEXT:[[TMP1:%.*]] = bitcast float [[B]] to i32
-; CHECK-NEXT:store i32 [[TMP0]], ptr [[RES]], align 4
+; CHECK-NEXT:store i32 [[TMP0]], ptr [[RES]], align 4, !tbaa.struct 
[[TBAA_STRUCT0:![0-9]+]]

dobbelaj-snps wrote:

Shouldn't we aim for also getting a !tbaa [[tbaa1]] here ? This is maybe 
related to my comment in #81285

https://github.com/llvm/llvm-project/pull/81289
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [SROA] Use !tbaa instead of !tbaa.struct if op matches field. (PR #81289)

2024-02-09 Thread via llvm-branch-commits

dobbelaj-snps wrote:

Hmm. 10 changes + 1 new usage of setAAMetaData, But only 4 relevant changes in 
tests.. That part of SROA might seems to lack some testing ?

https://github.com/llvm/llvm-project/pull/81289
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [TBAA] Only clear TBAAStruct if field can be extracted. (PR #81285)

2024-02-09 Thread Florian Hahn via llvm-branch-commits


@@ -821,13 +821,15 @@ MDNode *AAMDNodes::extendToTBAA(MDNode *MD, ssize_t Len) {
 AAMDNodes AAMDNodes::adjustForAccess(unsigned AccessSize) {
   AAMDNodes New = *this;
   MDNode *M = New.TBAAStruct;
-  New.TBAAStruct = nullptr;
   if (M && M->getNumOperands() == 3 && M->getOperand(0) &&

fhahn wrote:

Yep, I left this to here to keep the changes small, I'll soon share this one in 
the chain.

https://github.com/llvm/llvm-project/pull/81285
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [TBAA] Use !tbaa for first accessed field, even if there are others. (PR #81313)

2024-02-09 Thread Florian Hahn via llvm-branch-commits

https://github.com/fhahn created https://github.com/llvm/llvm-project/pull/81313

Motivation for this and follow-on patches is to improve codegen for libc++, 
where using memcpy limits optimizations, like vectorization for code iteration 
over std::vector>: https://godbolt.org/z/f3vqYos3c

Depends on https://github.com/llvm/llvm-project/pull/81289.

>From e879ab07a6b39d7cf47fbc3c17ff25918cdee628 Mon Sep 17 00:00:00 2001
From: Florian Hahn 
Date: Fri, 9 Feb 2024 16:48:26 +
Subject: [PATCH] [TBAA] Use !tbaa for first accessed field, even if there are
 others.

Motivation for this and follow-on patches is to improve codegen for
libc++, where using memcpy limits optimizations, like vectorization for
code iteration over std::vector>:
https://godbolt.org/z/f3vqYos3c

Depends on https://github.com/llvm/llvm-project/pull/81289.
---
 llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp |  3 +--
 llvm/test/Transforms/SROA/tbaa-struct2.ll| 21 +++
 llvm/test/Transforms/SROA/tbaa-struct3.ll| 28 ++--
 3 files changed, 25 insertions(+), 27 deletions(-)

diff --git a/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp 
b/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
index b2dc451d581939..25ac01db7633ee 100644
--- a/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
+++ b/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
@@ -821,8 +821,7 @@ MDNode *AAMDNodes::extendToTBAA(MDNode *MD, ssize_t Len) {
 AAMDNodes AAMDNodes::adjustForAccess(unsigned AccessSize) {
   AAMDNodes New = *this;
   MDNode *M = New.TBAAStruct;
-  if (M && M->getNumOperands() == 3 && M->getOperand(0) &&
-  mdconst::hasa(M->getOperand(0)) &&
+  if (M && M->getOperand(0) && mdconst::hasa(M->getOperand(0)) &&
   mdconst::extract(M->getOperand(0))->isZero() &&
   M->getOperand(1) && mdconst::hasa(M->getOperand(1)) &&
   mdconst::extract(M->getOperand(1))->getValue() ==
diff --git a/llvm/test/Transforms/SROA/tbaa-struct2.ll 
b/llvm/test/Transforms/SROA/tbaa-struct2.ll
index 02c99a2b329457..545fa47eecb2ce 100644
--- a/llvm/test/Transforms/SROA/tbaa-struct2.ll
+++ b/llvm/test/Transforms/SROA/tbaa-struct2.ll
@@ -11,11 +11,11 @@ declare double @subcall(double %g, i32 %m)
 define double @bar(ptr %wishart) {
 ; CHECK-LABEL: @bar(
 ; CHECK-NEXT:[[TMP_SROA_3:%.*]] = alloca [4 x i8], align 4
-; CHECK-NEXT:[[TMP_SROA_0_0_COPYLOAD:%.*]] = load double, ptr 
[[WISHART:%.*]], align 8, !tbaa.struct [[TBAA_STRUCT0:![0-9]+]]
+; CHECK-NEXT:[[TMP_SROA_0_0_COPYLOAD:%.*]] = load double, ptr 
[[WISHART:%.*]], align 8, !tbaa [[TBAA0:![0-9]+]]
 ; CHECK-NEXT:[[TMP_SROA_2_0_WISHART_SROA_IDX:%.*]] = getelementptr 
inbounds i8, ptr [[WISHART]], i64 8
-; CHECK-NEXT:[[TMP_SROA_2_0_COPYLOAD:%.*]] = load i32, ptr 
[[TMP_SROA_2_0_WISHART_SROA_IDX]], align 8, !tbaa [[TBAA5:![0-9]+]]
+; CHECK-NEXT:[[TMP_SROA_2_0_COPYLOAD:%.*]] = load i32, ptr 
[[TMP_SROA_2_0_WISHART_SROA_IDX]], align 8, !tbaa [[TBAA4:![0-9]+]]
 ; CHECK-NEXT:[[TMP_SROA_3_0_WISHART_SROA_IDX:%.*]] = getelementptr 
inbounds i8, ptr [[WISHART]], i64 12
-; CHECK-NEXT:call void @llvm.memcpy.p0.p0.i64(ptr align 4 [[TMP_SROA_3]], 
ptr align 4 [[TMP_SROA_3_0_WISHART_SROA_IDX]], i64 4, i1 false), !tbaa.struct 
[[TBAA_STRUCT7:![0-9]+]]
+; CHECK-NEXT:call void @llvm.memcpy.p0.p0.i64(ptr align 4 [[TMP_SROA_3]], 
ptr align 4 [[TMP_SROA_3_0_WISHART_SROA_IDX]], i64 4, i1 false), !tbaa.struct 
[[TBAA_STRUCT6:![0-9]+]]
 ; CHECK-NEXT:[[CALL:%.*]] = call double @subcall(double 
[[TMP_SROA_0_0_COPYLOAD]], i32 [[TMP_SROA_2_0_COPYLOAD]])
 ; CHECK-NEXT:ret double [[CALL]]
 ;
@@ -38,14 +38,13 @@ define double @bar(ptr %wishart) {
 ;.
 ; CHECK: attributes #[[ATTR0:[0-9]+]] = { nocallback nofree nounwind 
willreturn memory(argmem: readwrite) }
 ;.
-; CHECK: [[TBAA_STRUCT0]] = !{i64 0, i64 8, [[META1:![0-9]+]], i64 8, i64 4, 
[[TBAA5]]}
-; CHECK: [[META1]] = !{[[META2:![0-9]+]], [[META2]], i64 0}
-; CHECK: [[META2]] = !{!"double", [[META3:![0-9]+]], i64 0}
-; CHECK: [[META3]] = !{!"omnipotent char", [[META4:![0-9]+]], i64 0}
-; CHECK: [[META4]] = !{!"Simple C++ TBAA"}
-; CHECK: [[TBAA5]] = !{[[META6:![0-9]+]], [[META6]], i64 0}
-; CHECK: [[META6]] = !{!"int", [[META3]], i64 0}
-; CHECK: [[TBAA_STRUCT7]] = !{}
+; CHECK: [[TBAA0]] = !{[[META1:![0-9]+]], [[META1]], i64 0}
+; CHECK: [[META1]] = !{!"double", [[META2:![0-9]+]], i64 0}
+; CHECK: [[META2]] = !{!"omnipotent char", [[META3:![0-9]+]], i64 0}
+; CHECK: [[META3]] = !{!"Simple C++ TBAA"}
+; CHECK: [[TBAA4]] = !{[[META5:![0-9]+]], [[META5]], i64 0}
+; CHECK: [[META5]] = !{!"int", [[META2]], i64 0}
+; CHECK: [[TBAA_STRUCT6]] = !{}
 ;.
 ;; NOTE: These prefixes are unused and the list is autogenerated. Do not add 
tests below this line:
 ; CHECK-MODIFY-CFG: {{.*}}
diff --git a/llvm/test/Transforms/SROA/tbaa-struct3.ll 
b/llvm/test/Transforms/SROA/tbaa-struct3.ll
index 603e7d708647fc..68553d9b1a270b 100644
--- a/llvm/test/Transforms/SROA/tbaa-struct3.ll
+++ b/llvm/test/Transforms/SROA/tbaa-struct3.ll
@@ -7,9 +7,9 @@ define void @load

[llvm-branch-commits] [llvm] [TBAA] Only clear TBAAStruct if field can be extracted. (PR #81285)

2024-02-09 Thread Florian Hahn via llvm-branch-commits


@@ -821,13 +821,15 @@ MDNode *AAMDNodes::extendToTBAA(MDNode *MD, ssize_t Len) {
 AAMDNodes AAMDNodes::adjustForAccess(unsigned AccessSize) {
   AAMDNodes New = *this;
   MDNode *M = New.TBAAStruct;
-  New.TBAAStruct = nullptr;
   if (M && M->getNumOperands() == 3 && M->getOperand(0) &&

fhahn wrote:

Here it is: #81313

https://github.com/llvm/llvm-project/pull/81285
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [TBAA] Use !tbaa for first accessed field, even if there are others. (PR #81313)

2024-02-09 Thread via llvm-branch-commits

llvmbot wrote:



@llvm/pr-subscribers-llvm-transforms

@llvm/pr-subscribers-llvm-analysis

Author: Florian Hahn (fhahn)


Changes

Motivation for this and follow-on patches is to improve codegen for libc++, 
where using memcpy limits optimizations, like vectorization for code iteration 
over std::vector>: 
https://godbolt.org/z/f3vqYos3c

Depends on https://github.com/llvm/llvm-project/pull/81289.

---
Full diff: https://github.com/llvm/llvm-project/pull/81313.diff


3 Files Affected:

- (modified) llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp (+1-2) 
- (modified) llvm/test/Transforms/SROA/tbaa-struct2.ll (+10-11) 
- (modified) llvm/test/Transforms/SROA/tbaa-struct3.ll (+14-14) 


``diff
diff --git a/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp 
b/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
index b2dc451d581939..25ac01db7633ee 100644
--- a/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
+++ b/llvm/lib/Analysis/TypeBasedAliasAnalysis.cpp
@@ -821,8 +821,7 @@ MDNode *AAMDNodes::extendToTBAA(MDNode *MD, ssize_t Len) {
 AAMDNodes AAMDNodes::adjustForAccess(unsigned AccessSize) {
   AAMDNodes New = *this;
   MDNode *M = New.TBAAStruct;
-  if (M && M->getNumOperands() == 3 && M->getOperand(0) &&
-  mdconst::hasa(M->getOperand(0)) &&
+  if (M && M->getOperand(0) && mdconst::hasa(M->getOperand(0)) &&
   mdconst::extract(M->getOperand(0))->isZero() &&
   M->getOperand(1) && mdconst::hasa(M->getOperand(1)) &&
   mdconst::extract(M->getOperand(1))->getValue() ==
diff --git a/llvm/test/Transforms/SROA/tbaa-struct2.ll 
b/llvm/test/Transforms/SROA/tbaa-struct2.ll
index 02c99a2b329457..545fa47eecb2ce 100644
--- a/llvm/test/Transforms/SROA/tbaa-struct2.ll
+++ b/llvm/test/Transforms/SROA/tbaa-struct2.ll
@@ -11,11 +11,11 @@ declare double @subcall(double %g, i32 %m)
 define double @bar(ptr %wishart) {
 ; CHECK-LABEL: @bar(
 ; CHECK-NEXT:[[TMP_SROA_3:%.*]] = alloca [4 x i8], align 4
-; CHECK-NEXT:[[TMP_SROA_0_0_COPYLOAD:%.*]] = load double, ptr 
[[WISHART:%.*]], align 8, !tbaa.struct [[TBAA_STRUCT0:![0-9]+]]
+; CHECK-NEXT:[[TMP_SROA_0_0_COPYLOAD:%.*]] = load double, ptr 
[[WISHART:%.*]], align 8, !tbaa [[TBAA0:![0-9]+]]
 ; CHECK-NEXT:[[TMP_SROA_2_0_WISHART_SROA_IDX:%.*]] = getelementptr 
inbounds i8, ptr [[WISHART]], i64 8
-; CHECK-NEXT:[[TMP_SROA_2_0_COPYLOAD:%.*]] = load i32, ptr 
[[TMP_SROA_2_0_WISHART_SROA_IDX]], align 8, !tbaa [[TBAA5:![0-9]+]]
+; CHECK-NEXT:[[TMP_SROA_2_0_COPYLOAD:%.*]] = load i32, ptr 
[[TMP_SROA_2_0_WISHART_SROA_IDX]], align 8, !tbaa [[TBAA4:![0-9]+]]
 ; CHECK-NEXT:[[TMP_SROA_3_0_WISHART_SROA_IDX:%.*]] = getelementptr 
inbounds i8, ptr [[WISHART]], i64 12
-; CHECK-NEXT:call void @llvm.memcpy.p0.p0.i64(ptr align 4 [[TMP_SROA_3]], 
ptr align 4 [[TMP_SROA_3_0_WISHART_SROA_IDX]], i64 4, i1 false), !tbaa.struct 
[[TBAA_STRUCT7:![0-9]+]]
+; CHECK-NEXT:call void @llvm.memcpy.p0.p0.i64(ptr align 4 [[TMP_SROA_3]], 
ptr align 4 [[TMP_SROA_3_0_WISHART_SROA_IDX]], i64 4, i1 false), !tbaa.struct 
[[TBAA_STRUCT6:![0-9]+]]
 ; CHECK-NEXT:[[CALL:%.*]] = call double @subcall(double 
[[TMP_SROA_0_0_COPYLOAD]], i32 [[TMP_SROA_2_0_COPYLOAD]])
 ; CHECK-NEXT:ret double [[CALL]]
 ;
@@ -38,14 +38,13 @@ define double @bar(ptr %wishart) {
 ;.
 ; CHECK: attributes #[[ATTR0:[0-9]+]] = { nocallback nofree nounwind 
willreturn memory(argmem: readwrite) }
 ;.
-; CHECK: [[TBAA_STRUCT0]] = !{i64 0, i64 8, [[META1:![0-9]+]], i64 8, i64 4, 
[[TBAA5]]}
-; CHECK: [[META1]] = !{[[META2:![0-9]+]], [[META2]], i64 0}
-; CHECK: [[META2]] = !{!"double", [[META3:![0-9]+]], i64 0}
-; CHECK: [[META3]] = !{!"omnipotent char", [[META4:![0-9]+]], i64 0}
-; CHECK: [[META4]] = !{!"Simple C++ TBAA"}
-; CHECK: [[TBAA5]] = !{[[META6:![0-9]+]], [[META6]], i64 0}
-; CHECK: [[META6]] = !{!"int", [[META3]], i64 0}
-; CHECK: [[TBAA_STRUCT7]] = !{}
+; CHECK: [[TBAA0]] = !{[[META1:![0-9]+]], [[META1]], i64 0}
+; CHECK: [[META1]] = !{!"double", [[META2:![0-9]+]], i64 0}
+; CHECK: [[META2]] = !{!"omnipotent char", [[META3:![0-9]+]], i64 0}
+; CHECK: [[META3]] = !{!"Simple C++ TBAA"}
+; CHECK: [[TBAA4]] = !{[[META5:![0-9]+]], [[META5]], i64 0}
+; CHECK: [[META5]] = !{!"int", [[META2]], i64 0}
+; CHECK: [[TBAA_STRUCT6]] = !{}
 ;.
 ;; NOTE: These prefixes are unused and the list is autogenerated. Do not add 
tests below this line:
 ; CHECK-MODIFY-CFG: {{.*}}
diff --git a/llvm/test/Transforms/SROA/tbaa-struct3.ll 
b/llvm/test/Transforms/SROA/tbaa-struct3.ll
index 603e7d708647fc..68553d9b1a270b 100644
--- a/llvm/test/Transforms/SROA/tbaa-struct3.ll
+++ b/llvm/test/Transforms/SROA/tbaa-struct3.ll
@@ -7,9 +7,9 @@ define void @load_store_transfer_split_struct_tbaa_2_float(ptr 
dereferenceable(2
 ; CHECK-NEXT:  entry:
 ; CHECK-NEXT:[[TMP0:%.*]] = bitcast float [[A]] to i32
 ; CHECK-NEXT:[[TMP1:%.*]] = bitcast float [[B]] to i32
-; CHECK-NEXT:store i32 [[TMP0]], ptr [[RES]], align 4, !tbaa.struct 
[[TBAA_STRUCT0:![0-9]+]]
+; CHECK-NEXT:store i32 [[TMP0]], ptr [[RES]], alig

[llvm-branch-commits] [llvm] [SROA] Use !tbaa instead of !tbaa.struct if op matches field. (PR #81289)

2024-02-09 Thread Florian Hahn via llvm-branch-commits


@@ -7,9 +7,9 @@ define void @load_store_transfer_split_struct_tbaa_2_float(ptr 
dereferenceable(2
 ; CHECK-NEXT:  entry:
 ; CHECK-NEXT:[[TMP0:%.*]] = bitcast float [[A]] to i32
 ; CHECK-NEXT:[[TMP1:%.*]] = bitcast float [[B]] to i32
-; CHECK-NEXT:store i32 [[TMP0]], ptr [[RES]], align 4
+; CHECK-NEXT:store i32 [[TMP0]], ptr [[RES]], align 4, !tbaa.struct 
[[TBAA_STRUCT0:![0-9]+]]

fhahn wrote:

Yes, this should be solved by a separate improvement: #81313

https://github.com/llvm/llvm-project/pull/81289
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [SROA] Use !tbaa instead of !tbaa.struct if op matches field. (PR #81289)

2024-02-09 Thread Florian Hahn via llvm-branch-commits

fhahn wrote:

> Hmm. 10 changes + 1 new usage of setAAMetaData, But only 4 relevant changes 
> in tests.. That part of SROA seems to lack some testing ?

Yes, will add the missing coverage, just wanted to make sure this makes sense 
in general beforehand

https://github.com/llvm/llvm-project/pull/81289
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Fangrui Song via llvm-branch-commits

https://github.com/MaskRay edited 
https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Fangrui Song via llvm-branch-commits

https://github.com/MaskRay updated 
https://github.com/llvm/llvm-project/pull/81224


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


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Fangrui Song via llvm-branch-commits

https://github.com/MaskRay updated 
https://github.com/llvm/llvm-project/pull/81224


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


[llvm-branch-commits] [mlir] [mlir][Transforms] Support `moveOpBefore`/`After` in dialect conversion (PR #81240)

2024-02-09 Thread Mehdi Amini via llvm-branch-commits


@@ -970,6 +971,54 @@ class BlockTypeConversionAction : public BlockAction {
 
   void rollback() override;
 };
+
+/// An operation rewrite.

joker-eph wrote:

Can you expand on the role of the class, the context where it's used?

The "Action" name for this whole section is not great by the way, since the 
concept of "Actions" is now core to MLIR tracing...

https://github.com/llvm/llvm-project/pull/81240
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [mlir] [mlir][Transforms] Support `moveOpBefore`/`After` in dialect conversion (PR #81240)

2024-02-09 Thread Mehdi Amini via llvm-branch-commits

https://github.com/joker-eph approved this pull request.


https://github.com/llvm/llvm-project/pull/81240
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Fangrui Song via llvm-branch-commits


@@ -1124,11 +1127,15 @@ template  void 
Writer::setReservedSymbolSections() {
   }
 
   if (last) {
-// _edata points to the end of the last mapped initialized section.
+// _edata points to the end of the last mapped initialized section before

MaskRay wrote:

I find that `_etext` needs adjustment and just pushed a commit to fix it.

Hmm. I think splitting this part into a separate PR might be difficult due to 
the inflexible GitHub PR mechanism.

The test difference is in `lld/test/ELF/x86-64-section-layout.s` below:
```patch
-# CHECK-NEXT: 00205b0a 0 NOTYPE GLOBAL DEFAULT [[#]] (.ldata2) _edata
+# CHECK-NEXT: 00203307 0 NOTYPE GLOBAL DEFAULT [[#]] (.data) _edata
```

https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [mlir] [mlir][Transforms][NFC] Modularize block actions (PR #81237)

2024-02-09 Thread Mehdi Amini via llvm-branch-commits


@@ -820,6 +740,238 @@ void ArgConverter::insertConversion(Block *newBlock,
   conversionInfo.insert({newBlock, std::move(info)});
 }
 
+//===--===//
+// RewriteAction

joker-eph wrote:

Mentioned it in the other PR: do we have an alternative to "Action" here?

https://github.com/llvm/llvm-project/pull/81237
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Fangrui Song via llvm-branch-commits


@@ -1103,31 +1106,36 @@ template  void 
Writer::setReservedSymbolSections() {
   }
 
   PhdrEntry *last = nullptr;
-  PhdrEntry *lastRO = nullptr;
-
+  OutputSection *lastRO = nullptr;
+  auto isLarge = [](OutputSection *osec) {
+return config->emachine == EM_X86_64 && osec->flags & SHF_X86_64_LARGE;
+  };
   for (Partition &part : partitions) {
 for (PhdrEntry *p : part.phdrs) {
   if (p->p_type != PT_LOAD)
 continue;
   last = p;
-  if (!(p->p_flags & PF_W))
-lastRO = p;
+  if (!(p->p_flags & PF_W) && p->lastSec && !isLarge(p->lastSec))

MaskRay wrote:

This is a new change. We need to adjust `_etext` as there is now a read-only 
PT_LOAD segment after RW PT_LOAD segments. (Mentioned in the updated 
description).

https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Fangrui Song via llvm-branch-commits

https://github.com/MaskRay edited 
https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Fangrui Song via llvm-branch-commits

https://github.com/MaskRay edited 
https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Fangrui Song via llvm-branch-commits

https://github.com/MaskRay edited 
https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] PR for llvm/llvm-project#80844 (PR #80846)

2024-02-09 Thread Tom Stellard via llvm-branch-commits

https://github.com/tstellar closed 
https://github.com/llvm/llvm-project/pull/80846
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [compiler-rt] PR for llvm/llvm-project#79283 (PR #80068)

2024-02-09 Thread via llvm-branch-commits

https://github.com/llvmbot updated 
https://github.com/llvm/llvm-project/pull/80068

>From e6fa3ff6cc43f78000e56996a45f83acf53d2536 Mon Sep 17 00:00:00 2001
From: Fangrui Song 
Date: Tue, 30 Jan 2024 13:58:40 -0800
Subject: [PATCH] [dfsan] Wrap glibc 2.38 __isoc23_* functions (#79958)

Fix #79283: `test/dfsan/custom.cpp` has undefined symbol linker errors
on glibc 2.38 due to lack of wrappers for `__isoc23_strtol` and
`__isoc23_scanf` family functions.

Implement these wrappers as aliases to existing wrappers, similar to
https://reviews.llvm.org/D158943 for other sanitizers.

`strtol` in a user program, whether or not `_ISOC2X_SOURCE` is defined,
uses the C23 semantics (`strtol("0b1", 0, 0)` => 1), when
`libclang_rt.dfsan.a` is built on glibc 2.38+.

(cherry picked from commit 648560062af8deb4e6478130deb1dd8fa62929a8)
---
 compiler-rt/lib/dfsan/dfsan_custom.cpp| 203 +-
 compiler-rt/lib/dfsan/done_abilist.txt|   6 +
 .../lib/dfsan/libc_ubuntu1404_abilist.txt |   5 +
 3 files changed, 59 insertions(+), 155 deletions(-)

diff --git a/compiler-rt/lib/dfsan/dfsan_custom.cpp 
b/compiler-rt/lib/dfsan/dfsan_custom.cpp
index 85b796bd6349c8..3af26e9f64c925 100644
--- a/compiler-rt/lib/dfsan/dfsan_custom.cpp
+++ b/compiler-rt/lib/dfsan/dfsan_custom.cpp
@@ -55,6 +55,10 @@ using namespace __dfsan;
 #define DECLARE_WEAK_INTERCEPTOR_HOOK(f, ...) \
 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE void f(__VA_ARGS__);
 
+#define WRAPPER_ALIAS(fun, real)  \
+  SANITIZER_INTERFACE_ATTRIBUTE void __dfsw_##fun() ALIAS(__dfsw_##real); \
+  SANITIZER_INTERFACE_ATTRIBUTE void __dfso_##fun() ALIAS(__dfso_##real);
+
 // Async-safe, non-reentrant spin lock.
 class SignalSpinLocker {
  public:
@@ -1197,16 +1201,20 @@ char *__dfso_strcpy(char *dest, const char *src, 
dfsan_label dst_label,
   *ret_origin = dst_origin;
   return ret;
 }
+}
 
-static long int dfsan_strtol(const char *nptr, char **endptr, int base,
- char **tmp_endptr) {
+template 
+static ALWAYS_INLINE auto dfsan_strtol_impl(
+Fn real, const char *nptr, char **endptr, int base,
+char **tmp_endptr) -> decltype(real(nullptr, nullptr, 0)) {
   assert(tmp_endptr);
-  long int ret = strtol(nptr, tmp_endptr, base);
+  auto ret = real(nptr, tmp_endptr, base);
   if (endptr)
 *endptr = *tmp_endptr;
   return ret;
 }
 
+extern "C" {
 static void dfsan_strtolong_label(const char *nptr, const char *tmp_endptr,
   dfsan_label base_label,
   dfsan_label *ret_label) {
@@ -1236,30 +1244,6 @@ static void dfsan_strtolong_origin(const char *nptr, 
const char *tmp_endptr,
   }
 }
 
-SANITIZER_INTERFACE_ATTRIBUTE
-long int __dfsw_strtol(const char *nptr, char **endptr, int base,
-   dfsan_label nptr_label, dfsan_label endptr_label,
-   dfsan_label base_label, dfsan_label *ret_label) {
-  char *tmp_endptr;
-  long int ret = dfsan_strtol(nptr, endptr, base, &tmp_endptr);
-  dfsan_strtolong_label(nptr, tmp_endptr, base_label, ret_label);
-  return ret;
-}
-
-SANITIZER_INTERFACE_ATTRIBUTE
-long int __dfso_strtol(const char *nptr, char **endptr, int base,
-   dfsan_label nptr_label, dfsan_label endptr_label,
-   dfsan_label base_label, dfsan_label *ret_label,
-   dfsan_origin nptr_origin, dfsan_origin endptr_origin,
-   dfsan_origin base_origin, dfsan_origin *ret_origin) {
-  char *tmp_endptr;
-  long int ret = dfsan_strtol(nptr, endptr, base, &tmp_endptr);
-  dfsan_strtolong_label(nptr, tmp_endptr, base_label, ret_label);
-  dfsan_strtolong_origin(nptr, tmp_endptr, base_label, ret_label, base_origin,
- ret_origin);
-  return ret;
-}
-
 static double dfsan_strtod(const char *nptr, char **endptr, char **tmp_endptr) 
{
   assert(tmp_endptr);
   double ret = strtod(nptr, tmp_endptr);
@@ -1307,108 +1291,40 @@ double __dfso_strtod(const char *nptr, char **endptr, 
dfsan_label nptr_label,
   return ret;
 }
 
-static long long int dfsan_strtoll(const char *nptr, char **endptr, int base,
-   char **tmp_endptr) {
-  assert(tmp_endptr);
-  long long int ret = strtoll(nptr, tmp_endptr, base);
-  if (endptr)
-*endptr = *tmp_endptr;
-  return ret;
-}
-
-SANITIZER_INTERFACE_ATTRIBUTE
-long long int __dfsw_strtoll(const char *nptr, char **endptr, int base,
- dfsan_label nptr_label, dfsan_label endptr_label,
- dfsan_label base_label, dfsan_label *ret_label) {
-  char *tmp_endptr;
-  long long int ret = dfsan_strtoll(nptr, endptr, base, &tmp_endptr);
-  dfsan_strtolong_label(nptr, tmp_endptr, base_label, ret_label);
-  return ret;
-}
-
-SANITIZER_INTERFACE_ATTRIBUTE
-long long int __dfso_strtoll(const char *nptr, char **endptr, int base,
- dfsan_label nptr_label, dfsa

[llvm-branch-commits] [compiler-rt] e6fa3ff - [dfsan] Wrap glibc 2.38 __isoc23_* functions (#79958)

2024-02-09 Thread Tom Stellard via llvm-branch-commits

Author: Fangrui Song
Date: 2024-02-09T13:18:45-08:00
New Revision: e6fa3ff6cc43f78000e56996a45f83acf53d2536

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

LOG: [dfsan] Wrap glibc 2.38 __isoc23_* functions (#79958)

Fix #79283: `test/dfsan/custom.cpp` has undefined symbol linker errors
on glibc 2.38 due to lack of wrappers for `__isoc23_strtol` and
`__isoc23_scanf` family functions.

Implement these wrappers as aliases to existing wrappers, similar to
https://reviews.llvm.org/D158943 for other sanitizers.

`strtol` in a user program, whether or not `_ISOC2X_SOURCE` is defined,
uses the C23 semantics (`strtol("0b1", 0, 0)` => 1), when
`libclang_rt.dfsan.a` is built on glibc 2.38+.

(cherry picked from commit 648560062af8deb4e6478130deb1dd8fa62929a8)

Added: 


Modified: 
compiler-rt/lib/dfsan/dfsan_custom.cpp
compiler-rt/lib/dfsan/done_abilist.txt
compiler-rt/lib/dfsan/libc_ubuntu1404_abilist.txt

Removed: 




diff  --git a/compiler-rt/lib/dfsan/dfsan_custom.cpp 
b/compiler-rt/lib/dfsan/dfsan_custom.cpp
index 85b796bd6349c8..3af26e9f64c925 100644
--- a/compiler-rt/lib/dfsan/dfsan_custom.cpp
+++ b/compiler-rt/lib/dfsan/dfsan_custom.cpp
@@ -55,6 +55,10 @@ using namespace __dfsan;
 #define DECLARE_WEAK_INTERCEPTOR_HOOK(f, ...) \
 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE void f(__VA_ARGS__);
 
+#define WRAPPER_ALIAS(fun, real)  \
+  SANITIZER_INTERFACE_ATTRIBUTE void __dfsw_##fun() ALIAS(__dfsw_##real); \
+  SANITIZER_INTERFACE_ATTRIBUTE void __dfso_##fun() ALIAS(__dfso_##real);
+
 // Async-safe, non-reentrant spin lock.
 class SignalSpinLocker {
  public:
@@ -1197,16 +1201,20 @@ char *__dfso_strcpy(char *dest, const char *src, 
dfsan_label dst_label,
   *ret_origin = dst_origin;
   return ret;
 }
+}
 
-static long int dfsan_strtol(const char *nptr, char **endptr, int base,
- char **tmp_endptr) {
+template 
+static ALWAYS_INLINE auto dfsan_strtol_impl(
+Fn real, const char *nptr, char **endptr, int base,
+char **tmp_endptr) -> decltype(real(nullptr, nullptr, 0)) {
   assert(tmp_endptr);
-  long int ret = strtol(nptr, tmp_endptr, base);
+  auto ret = real(nptr, tmp_endptr, base);
   if (endptr)
 *endptr = *tmp_endptr;
   return ret;
 }
 
+extern "C" {
 static void dfsan_strtolong_label(const char *nptr, const char *tmp_endptr,
   dfsan_label base_label,
   dfsan_label *ret_label) {
@@ -1236,30 +1244,6 @@ static void dfsan_strtolong_origin(const char *nptr, 
const char *tmp_endptr,
   }
 }
 
-SANITIZER_INTERFACE_ATTRIBUTE
-long int __dfsw_strtol(const char *nptr, char **endptr, int base,
-   dfsan_label nptr_label, dfsan_label endptr_label,
-   dfsan_label base_label, dfsan_label *ret_label) {
-  char *tmp_endptr;
-  long int ret = dfsan_strtol(nptr, endptr, base, &tmp_endptr);
-  dfsan_strtolong_label(nptr, tmp_endptr, base_label, ret_label);
-  return ret;
-}
-
-SANITIZER_INTERFACE_ATTRIBUTE
-long int __dfso_strtol(const char *nptr, char **endptr, int base,
-   dfsan_label nptr_label, dfsan_label endptr_label,
-   dfsan_label base_label, dfsan_label *ret_label,
-   dfsan_origin nptr_origin, dfsan_origin endptr_origin,
-   dfsan_origin base_origin, dfsan_origin *ret_origin) {
-  char *tmp_endptr;
-  long int ret = dfsan_strtol(nptr, endptr, base, &tmp_endptr);
-  dfsan_strtolong_label(nptr, tmp_endptr, base_label, ret_label);
-  dfsan_strtolong_origin(nptr, tmp_endptr, base_label, ret_label, base_origin,
- ret_origin);
-  return ret;
-}
-
 static double dfsan_strtod(const char *nptr, char **endptr, char **tmp_endptr) 
{
   assert(tmp_endptr);
   double ret = strtod(nptr, tmp_endptr);
@@ -1307,108 +1291,40 @@ double __dfso_strtod(const char *nptr, char **endptr, 
dfsan_label nptr_label,
   return ret;
 }
 
-static long long int dfsan_strtoll(const char *nptr, char **endptr, int base,
-   char **tmp_endptr) {
-  assert(tmp_endptr);
-  long long int ret = strtoll(nptr, tmp_endptr, base);
-  if (endptr)
-*endptr = *tmp_endptr;
-  return ret;
-}
-
-SANITIZER_INTERFACE_ATTRIBUTE
-long long int __dfsw_strtoll(const char *nptr, char **endptr, int base,
- dfsan_label nptr_label, dfsan_label endptr_label,
- dfsan_label base_label, dfsan_label *ret_label) {
-  char *tmp_endptr;
-  long long int ret = dfsan_strtoll(nptr, endptr, base, &tmp_endptr);
-  dfsan_strtolong_label(nptr, tmp_endptr, base_label, ret_label);
-  return ret;
-}
-
-SANITIZER_INTERFACE_ATTRIBUTE
-long long int __dfso_strtoll(cons

[llvm-branch-commits] [compiler-rt] PR for llvm/llvm-project#79283 (PR #80068)

2024-02-09 Thread Tom Stellard via llvm-branch-commits

https://github.com/tstellar closed 
https://github.com/llvm/llvm-project/pull/80068
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] PR for llvm/llvm-project#80961 (PR #80962)

2024-02-09 Thread via llvm-branch-commits

https://github.com/llvmbot updated 
https://github.com/llvm/llvm-project/pull/80962

>From a8158d8836e94ede76ea0cc749da2583511b7d89 Mon Sep 17 00:00:00 2001
From: Mariya Podchishchaeva 
Date: Tue, 6 Feb 2024 15:57:35 +0300
Subject: [PATCH] [clang] Fix unexpected `-Wconstant-logical-operand` in C23
 (#80724)

C23 has `bool`, but logical operators still return int. Check that
we're not in C to avoid false-positive -Wconstant-logical-operand.

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

(cherry picked from commit a18e92d020b895b712175a3b13a3d021608115a7)
---
 clang/docs/ReleaseNotes.rst|  4 
 clang/lib/Sema/SemaExpr.cpp|  2 +-
 clang/test/Sema/warn-int-in-bool-context.c | 11 +++
 3 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b05c72c7f2c3eb..95d44951ae7ee6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -861,6 +861,10 @@ Bug Fixes in This Version
 - Fixed assertion failure with deleted overloaded unary operators.
   Fixes (`#78314 `_)
 
+- Clang now doesn't produce false-positive warning `-Wconstant-logical-operand`
+  for logical operators in C23.
+  Fixes (`#64356 `_).
+
 Bug Fixes to Compiler Builtins
 ^^
 
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 4efcb359035576..0d9c087ed0cd19 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -14062,7 +14062,7 @@ inline QualType Sema::CheckLogicalOperands(ExprResult 
&LHS, ExprResult &RHS,
 Expr::EvalResult EVResult;
 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
   llvm::APSInt Result = EVResult.Val.getInt();
-  if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
+  if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
!RHS.get()->getExprLoc().isMacroID()) ||
   (Result != 0 && Result != 1)) {
 Diag(Loc, diag::warn_logical_instead_of_bitwise)
diff --git a/clang/test/Sema/warn-int-in-bool-context.c 
b/clang/test/Sema/warn-int-in-bool-context.c
index 0c94ebb391f3c5..99f3db9f8d41a7 100644
--- a/clang/test/Sema/warn-int-in-bool-context.c
+++ b/clang/test/Sema/warn-int-in-bool-context.c
@@ -72,3 +72,14 @@ int test(int a, unsigned b, enum num n) {
   // Don't warn in macros.
   return SHIFT(1, a);
 }
+
+int GH64356(int arg) {
+  if ((arg == 1) && (1 == 1)) return 1;
+return 0;
+
+  if ((64 > 32) && (32 < 64))
+return 2;
+
+  if ((1 == 1) && (arg == 1)) return 1;
+return 0;
+}

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


[llvm-branch-commits] [clang] a8158d8 - [clang] Fix unexpected `-Wconstant-logical-operand` in C23 (#80724)

2024-02-09 Thread Tom Stellard via llvm-branch-commits

Author: Mariya Podchishchaeva
Date: 2024-02-09T13:20:35-08:00
New Revision: a8158d8836e94ede76ea0cc749da2583511b7d89

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

LOG: [clang] Fix unexpected `-Wconstant-logical-operand` in C23 (#80724)

C23 has `bool`, but logical operators still return int. Check that
we're not in C to avoid false-positive -Wconstant-logical-operand.

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

(cherry picked from commit a18e92d020b895b712175a3b13a3d021608115a7)

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaExpr.cpp
clang/test/Sema/warn-int-in-bool-context.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b05c72c7f2c3eb..95d44951ae7ee6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -861,6 +861,10 @@ Bug Fixes in This Version
 - Fixed assertion failure with deleted overloaded unary operators.
   Fixes (`#78314 `_)
 
+- Clang now doesn't produce false-positive warning `-Wconstant-logical-operand`
+  for logical operators in C23.
+  Fixes (`#64356 `_).
+
 Bug Fixes to Compiler Builtins
 ^^
 

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 4efcb359035576..0d9c087ed0cd19 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -14062,7 +14062,7 @@ inline QualType Sema::CheckLogicalOperands(ExprResult 
&LHS, ExprResult &RHS,
 Expr::EvalResult EVResult;
 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
   llvm::APSInt Result = EVResult.Val.getInt();
-  if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
+  if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
!RHS.get()->getExprLoc().isMacroID()) ||
   (Result != 0 && Result != 1)) {
 Diag(Loc, diag::warn_logical_instead_of_bitwise)

diff  --git a/clang/test/Sema/warn-int-in-bool-context.c 
b/clang/test/Sema/warn-int-in-bool-context.c
index 0c94ebb391f3c5..99f3db9f8d41a7 100644
--- a/clang/test/Sema/warn-int-in-bool-context.c
+++ b/clang/test/Sema/warn-int-in-bool-context.c
@@ -72,3 +72,14 @@ int test(int a, unsigned b, enum num n) {
   // Don't warn in macros.
   return SHIFT(1, a);
 }
+
+int GH64356(int arg) {
+  if ((arg == 1) && (1 == 1)) return 1;
+return 0;
+
+  if ((64 > 32) && (32 < 64))
+return 2;
+
+  if ((1 == 1) && (arg == 1)) return 1;
+return 0;
+}



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


[llvm-branch-commits] [clang] PR for llvm/llvm-project#80961 (PR #80962)

2024-02-09 Thread Tom Stellard via llvm-branch-commits

https://github.com/tstellar closed 
https://github.com/llvm/llvm-project/pull/80962
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [libunwind] PR for llvm/llvm-project#81084 (PR #81085)

2024-02-09 Thread via llvm-branch-commits

https://github.com/llvmbot updated 
https://github.com/llvm/llvm-project/pull/81085

>From 2b033a32ea1b45c773158f67b48623ceffbb153d Mon Sep 17 00:00:00 2001
From: YunQiang Su 
Date: Thu, 8 Feb 2024 09:15:53 +0800
Subject: [PATCH] MIPS/libunwind: Use -mfp64 if compiler is FPXX (#68521)

Libunwind supports FP64 and FP32 modes, but not FPXX. The reason is
that, FP64 and FP32 have different way to save/restore FPRs. If
libunwind is built as FPXX, we have no idea which one should we use.

It's not due to the code bug, but rather the nature of FPXX.
FPXX is an ABI which uses only a common subset of FR=1(FP64) and FR=0
(FP32).
So that FPXX binaries can link with both FP64 and FP32 ones, aka.
FPXX + FP32 -> FP32
FPXX + FP64 -> FP64

While for libunwind, we should save/restore all of FPRs. If we use FPXX,
we can only save/restore a common subset of FPRs, instead of superset.

If libunwind is built as FP64, it will interoperatable with FPXX/FP64
APPs, and if it is built as FP32, it will interoperatable with
FP32/FPXX. Currently most of O32 APPs are FPXX or FP64, while few are
FP32.

So if the compiler is FPXX, which is the default value of most
toolchain, let's switch it to FP64.

Co-authored-by: YunQiang Su 
(cherry picked from commit 4520b478d2512b0f39764e0464dcb4cb961845b5)
---
 libunwind/CMakeLists.txt | 19 +++
 1 file changed, 19 insertions(+)

diff --git a/libunwind/CMakeLists.txt b/libunwind/CMakeLists.txt
index bb1b052f61d875..806d5a783ec39c 100644
--- a/libunwind/CMakeLists.txt
+++ b/libunwind/CMakeLists.txt
@@ -21,6 +21,7 @@ set(LIBUNWIND_LIBCXX_PATH 
"${CMAKE_CURRENT_LIST_DIR}/../libcxx" CACHE PATH
 "Specify path to libc++ source.")
 
 include(GNUInstallDirs)
+include(CheckSymbolExists)
 
 
#===
 # Setup CMake Options
@@ -96,6 +97,20 @@ endif()
 option(LIBUNWIND_HIDE_SYMBOLS
   "Do not export any symbols from the static library." 
${LIBUNWIND_DEFAULT_HIDE_SYMBOLS})
 
+# If toolchain is FPXX, we switch to FP64 to save the full FPRs. See:
+# 
https://web.archive.org/web/20180828210612/https://dmz-portal.mips.com/wiki/MIPS_O32_ABI_-_FR0_and_FR1_Interlinking
+check_symbol_exists(__mips_hard_float "" __MIPSHF)
+check_symbol_exists(_ABIO32 "" __MIPS_O32)
+if (__MIPSHF AND __MIPS_O32)
+  file(WRITE 
${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/mips_is_fpxx.c
+"#if __mips_fpr != 0\n"
+"# error\n"
+"#endif\n")
+  try_compile(MIPS_FPABI_FPXX ${CMAKE_BINARY_DIR}
+${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/mips_is_fpxx.c
+CMAKE_FLAGS -DCMAKE_C_LINK_EXECUTABLE='echo')
+endif()
+
 
#===
 # Configure System
 
#===
@@ -179,6 +194,10 @@ if (WIN32)
   add_compile_flags_if_supported(-Wno-dll-attribute-on-redeclaration)
 endif()
 
+if (MIPS_FPABI_FPXX)
+  add_compile_flags(-mfp64)
+endif()
+
 # Get feature flags.
 # Exceptions
 # Catches C++ exceptions only and tells the compiler to assume that extern C

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


[llvm-branch-commits] [libunwind] 2b033a3 - MIPS/libunwind: Use -mfp64 if compiler is FPXX (#68521)

2024-02-09 Thread Tom Stellard via llvm-branch-commits

Author: YunQiang Su
Date: 2024-02-09T13:22:24-08:00
New Revision: 2b033a32ea1b45c773158f67b48623ceffbb153d

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

LOG: MIPS/libunwind: Use -mfp64 if compiler is FPXX (#68521)

Libunwind supports FP64 and FP32 modes, but not FPXX. The reason is
that, FP64 and FP32 have different way to save/restore FPRs. If
libunwind is built as FPXX, we have no idea which one should we use.

It's not due to the code bug, but rather the nature of FPXX.
FPXX is an ABI which uses only a common subset of FR=1(FP64) and FR=0
(FP32).
So that FPXX binaries can link with both FP64 and FP32 ones, aka.
FPXX + FP32 -> FP32
FPXX + FP64 -> FP64

While for libunwind, we should save/restore all of FPRs. If we use FPXX,
we can only save/restore a common subset of FPRs, instead of superset.

If libunwind is built as FP64, it will interoperatable with FPXX/FP64
APPs, and if it is built as FP32, it will interoperatable with
FP32/FPXX. Currently most of O32 APPs are FPXX or FP64, while few are
FP32.

So if the compiler is FPXX, which is the default value of most
toolchain, let's switch it to FP64.

Co-authored-by: YunQiang Su 
(cherry picked from commit 4520b478d2512b0f39764e0464dcb4cb961845b5)

Added: 


Modified: 
libunwind/CMakeLists.txt

Removed: 




diff  --git a/libunwind/CMakeLists.txt b/libunwind/CMakeLists.txt
index bb1b052f61d875..806d5a783ec39c 100644
--- a/libunwind/CMakeLists.txt
+++ b/libunwind/CMakeLists.txt
@@ -21,6 +21,7 @@ set(LIBUNWIND_LIBCXX_PATH 
"${CMAKE_CURRENT_LIST_DIR}/../libcxx" CACHE PATH
 "Specify path to libc++ source.")
 
 include(GNUInstallDirs)
+include(CheckSymbolExists)
 
 
#===
 # Setup CMake Options
@@ -96,6 +97,20 @@ endif()
 option(LIBUNWIND_HIDE_SYMBOLS
   "Do not export any symbols from the static library." 
${LIBUNWIND_DEFAULT_HIDE_SYMBOLS})
 
+# If toolchain is FPXX, we switch to FP64 to save the full FPRs. See:
+# 
https://web.archive.org/web/20180828210612/https://dmz-portal.mips.com/wiki/MIPS_O32_ABI_-_FR0_and_FR1_Interlinking
+check_symbol_exists(__mips_hard_float "" __MIPSHF)
+check_symbol_exists(_ABIO32 "" __MIPS_O32)
+if (__MIPSHF AND __MIPS_O32)
+  file(WRITE 
${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/mips_is_fpxx.c
+"#if __mips_fpr != 0\n"
+"# error\n"
+"#endif\n")
+  try_compile(MIPS_FPABI_FPXX ${CMAKE_BINARY_DIR}
+${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/mips_is_fpxx.c
+CMAKE_FLAGS -DCMAKE_C_LINK_EXECUTABLE='echo')
+endif()
+
 
#===
 # Configure System
 
#===
@@ -179,6 +194,10 @@ if (WIN32)
   add_compile_flags_if_supported(-Wno-dll-attribute-on-redeclaration)
 endif()
 
+if (MIPS_FPABI_FPXX)
+  add_compile_flags(-mfp64)
+endif()
+
 # Get feature flags.
 # Exceptions
 # Catches C++ exceptions only and tells the compiler to assume that extern C



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


[llvm-branch-commits] [libunwind] PR for llvm/llvm-project#81084 (PR #81085)

2024-02-09 Thread Tom Stellard via llvm-branch-commits

https://github.com/tstellar closed 
https://github.com/llvm/llvm-project/pull/81085
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] PR for llvm/llvm-project#80628 (PR #81096)

2024-02-09 Thread via llvm-branch-commits

https://github.com/llvmbot updated 
https://github.com/llvm/llvm-project/pull/81096

>From 0135e048a1a0105d5842c3506345211c54001c54 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Wed, 7 Feb 2024 21:35:43 -0800
Subject: [PATCH] [clang-format] Fix a regression in dumping the config
 (#80628)

Commit d813af73f70f addressed a regression introduced by commit
3791b3fca6ea
but caused `clang-format -dump-config` to "hang".

This patch reverts changes to ClangFormat.cpp by both commits and
reworks the cleanup.

Fixes #80621.

(cherry picked from commit 8f6e13e6da84510c8321717860fd506e12118514)
---
 clang/test/Format/dump-config-objc-stdin.m |  3 ++
 clang/test/Format/verbose.cpp  | 10 +
 clang/tools/clang-format/ClangFormat.cpp   | 49 +++---
 3 files changed, 30 insertions(+), 32 deletions(-)

diff --git a/clang/test/Format/dump-config-objc-stdin.m 
b/clang/test/Format/dump-config-objc-stdin.m
index b22ff7b3328caa..d81711a84d79bf 100644
--- a/clang/test/Format/dump-config-objc-stdin.m
+++ b/clang/test/Format/dump-config-objc-stdin.m
@@ -1,5 +1,8 @@
+// RUN: clang-format -assume-filename=foo.m -dump-config | FileCheck %s
+
 // RUN: clang-format -dump-config - < %s | FileCheck %s
 
 // CHECK: Language: ObjC
+
 @interface Foo
 @end
diff --git a/clang/test/Format/verbose.cpp b/clang/test/Format/verbose.cpp
index dd625e3f67e55d..4ab03d8f62aefc 100644
--- a/clang/test/Format/verbose.cpp
+++ b/clang/test/Format/verbose.cpp
@@ -1,12 +1,6 @@
-// RUN: clang-format %s  2> %t.stderr
+// RUN: clang-format -verbose 2> %t.stderr
 // RUN: not grep "Formatting" %t.stderr
-// RUN: clang-format %s -verbose 2> %t.stderr
-// RUN: grep -E "Formatting (.*)verbose.cpp(.*)" %t.stderr
-// RUN: clang-format %s -verbose=false 2> %t.stderr
-// RUN: not grep "Formatting" %t.stderr
-
-int a;
-// RUN: clang-format %s  2> %t.stderr
+// RUN: clang-format %s 2> %t.stderr
 // RUN: not grep "Formatting" %t.stderr
 // RUN: clang-format %s -verbose 2> %t.stderr
 // RUN: grep -E "Formatting (.*)verbose.cpp(.*)" %t.stderr
diff --git a/clang/tools/clang-format/ClangFormat.cpp 
b/clang/tools/clang-format/ClangFormat.cpp
index 5ee6092bb9bb7f..e122cea50f7268 100644
--- a/clang/tools/clang-format/ClangFormat.cpp
+++ b/clang/tools/clang-format/ClangFormat.cpp
@@ -399,7 +399,8 @@ class ClangFormatDiagConsumer : public DiagnosticConsumer {
 };
 
 // Returns true on error.
-static bool format(StringRef FileName, bool IsSTDIN) {
+static bool format(StringRef FileName) {
+  const bool IsSTDIN = FileName == "-";
   if (!OutputXML && Inplace && IsSTDIN) {
 errs() << "error: cannot use -i when reading from stdin.\n";
 return false;
@@ -545,24 +546,25 @@ static void PrintVersion(raw_ostream &OS) {
 }
 
 // Dump the configuration.
-static int dumpConfig(bool IsSTDIN) {
+static int dumpConfig() {
   std::unique_ptr Code;
-
-  // `FileNames` must have at least "-" in it even if no file was specified.
-  assert(!FileNames.empty());
-
-  // Read in the code in case the filename alone isn't enough to detect the
-  // language.
-  ErrorOr> CodeOrErr =
-  MemoryBuffer::getFileOrSTDIN(FileNames[0]);
-  if (std::error_code EC = CodeOrErr.getError()) {
-llvm::errs() << EC.message() << "\n";
-return 1;
+  // We can't read the code to detect the language if there's no file name.
+  if (!FileNames.empty()) {
+// Read in the code in case the filename alone isn't enough to detect the
+// language.
+ErrorOr> CodeOrErr =
+MemoryBuffer::getFileOrSTDIN(FileNames[0]);
+if (std::error_code EC = CodeOrErr.getError()) {
+  llvm::errs() << EC.message() << "\n";
+  return 1;
+}
+Code = std::move(CodeOrErr.get());
   }
-  Code = std::move(CodeOrErr.get());
-
   llvm::Expected FormatStyle =
-  clang::format::getStyle(Style, IsSTDIN ? AssumeFileName : FileNames[0],
+  clang::format::getStyle(Style,
+  FileNames.empty() || FileNames[0] == "-"
+  ? AssumeFileName
+  : FileNames[0],
   FallbackStyle, Code ? Code->getBuffer() : "");
   if (!FormatStyle) {
 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
@@ -682,11 +684,8 @@ int main(int argc, const char **argv) {
 return 0;
   }
 
-  if (FileNames.empty())
-FileNames.push_back("-");
-
   if (DumpConfig)
-return dumpConfig(FileNames[0] == "-");
+return dumpConfig();
 
   if (!Files.empty()) {
 std::ifstream ExternalFileOfFiles{std::string(Files)};
@@ -699,7 +698,10 @@ int main(int argc, const char **argv) {
 errs() << "Clang-formating " << LineNo << " files\n";
   }
 
-  if (FileNames.size() != 1 &&
+  if (FileNames.empty())
+return clang::format::format("-");
+
+  if (FileNames.size() > 1 &&
   (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty())) {
 errs() << "error: -offset, -length and -lines can only be used for "
   "single file.\n";
@@ -709,14 +711,13 @

[llvm-branch-commits] [clang] 0135e04 - [clang-format] Fix a regression in dumping the config (#80628)

2024-02-09 Thread Tom Stellard via llvm-branch-commits

Author: Owen Pan
Date: 2024-02-09T13:24:35-08:00
New Revision: 0135e048a1a0105d5842c3506345211c54001c54

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

LOG: [clang-format] Fix a regression in dumping the config (#80628)

Commit d813af73f70f addressed a regression introduced by commit
3791b3fca6ea
but caused `clang-format -dump-config` to "hang".

This patch reverts changes to ClangFormat.cpp by both commits and
reworks the cleanup.

Fixes #80621.

(cherry picked from commit 8f6e13e6da84510c8321717860fd506e12118514)

Added: 


Modified: 
clang/test/Format/dump-config-objc-stdin.m
clang/test/Format/verbose.cpp
clang/tools/clang-format/ClangFormat.cpp

Removed: 




diff  --git a/clang/test/Format/dump-config-objc-stdin.m 
b/clang/test/Format/dump-config-objc-stdin.m
index b22ff7b3328caa..d81711a84d79bf 100644
--- a/clang/test/Format/dump-config-objc-stdin.m
+++ b/clang/test/Format/dump-config-objc-stdin.m
@@ -1,5 +1,8 @@
+// RUN: clang-format -assume-filename=foo.m -dump-config | FileCheck %s
+
 // RUN: clang-format -dump-config - < %s | FileCheck %s
 
 // CHECK: Language: ObjC
+
 @interface Foo
 @end

diff  --git a/clang/test/Format/verbose.cpp b/clang/test/Format/verbose.cpp
index dd625e3f67e55d..4ab03d8f62aefc 100644
--- a/clang/test/Format/verbose.cpp
+++ b/clang/test/Format/verbose.cpp
@@ -1,12 +1,6 @@
-// RUN: clang-format %s  2> %t.stderr
+// RUN: clang-format -verbose 2> %t.stderr
 // RUN: not grep "Formatting" %t.stderr
-// RUN: clang-format %s -verbose 2> %t.stderr
-// RUN: grep -E "Formatting (.*)verbose.cpp(.*)" %t.stderr
-// RUN: clang-format %s -verbose=false 2> %t.stderr
-// RUN: not grep "Formatting" %t.stderr
-
-int a;
-// RUN: clang-format %s  2> %t.stderr
+// RUN: clang-format %s 2> %t.stderr
 // RUN: not grep "Formatting" %t.stderr
 // RUN: clang-format %s -verbose 2> %t.stderr
 // RUN: grep -E "Formatting (.*)verbose.cpp(.*)" %t.stderr

diff  --git a/clang/tools/clang-format/ClangFormat.cpp 
b/clang/tools/clang-format/ClangFormat.cpp
index 5ee6092bb9bb7f..e122cea50f7268 100644
--- a/clang/tools/clang-format/ClangFormat.cpp
+++ b/clang/tools/clang-format/ClangFormat.cpp
@@ -399,7 +399,8 @@ class ClangFormatDiagConsumer : public DiagnosticConsumer {
 };
 
 // Returns true on error.
-static bool format(StringRef FileName, bool IsSTDIN) {
+static bool format(StringRef FileName) {
+  const bool IsSTDIN = FileName == "-";
   if (!OutputXML && Inplace && IsSTDIN) {
 errs() << "error: cannot use -i when reading from stdin.\n";
 return false;
@@ -545,24 +546,25 @@ static void PrintVersion(raw_ostream &OS) {
 }
 
 // Dump the configuration.
-static int dumpConfig(bool IsSTDIN) {
+static int dumpConfig() {
   std::unique_ptr Code;
-
-  // `FileNames` must have at least "-" in it even if no file was specified.
-  assert(!FileNames.empty());
-
-  // Read in the code in case the filename alone isn't enough to detect the
-  // language.
-  ErrorOr> CodeOrErr =
-  MemoryBuffer::getFileOrSTDIN(FileNames[0]);
-  if (std::error_code EC = CodeOrErr.getError()) {
-llvm::errs() << EC.message() << "\n";
-return 1;
+  // We can't read the code to detect the language if there's no file name.
+  if (!FileNames.empty()) {
+// Read in the code in case the filename alone isn't enough to detect the
+// language.
+ErrorOr> CodeOrErr =
+MemoryBuffer::getFileOrSTDIN(FileNames[0]);
+if (std::error_code EC = CodeOrErr.getError()) {
+  llvm::errs() << EC.message() << "\n";
+  return 1;
+}
+Code = std::move(CodeOrErr.get());
   }
-  Code = std::move(CodeOrErr.get());
-
   llvm::Expected FormatStyle =
-  clang::format::getStyle(Style, IsSTDIN ? AssumeFileName : FileNames[0],
+  clang::format::getStyle(Style,
+  FileNames.empty() || FileNames[0] == "-"
+  ? AssumeFileName
+  : FileNames[0],
   FallbackStyle, Code ? Code->getBuffer() : "");
   if (!FormatStyle) {
 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
@@ -682,11 +684,8 @@ int main(int argc, const char **argv) {
 return 0;
   }
 
-  if (FileNames.empty())
-FileNames.push_back("-");
-
   if (DumpConfig)
-return dumpConfig(FileNames[0] == "-");
+return dumpConfig();
 
   if (!Files.empty()) {
 std::ifstream ExternalFileOfFiles{std::string(Files)};
@@ -699,7 +698,10 @@ int main(int argc, const char **argv) {
 errs() << "Clang-formating " << LineNo << " files\n";
   }
 
-  if (FileNames.size() != 1 &&
+  if (FileNames.empty())
+return clang::format::format("-");
+
+  if (FileNames.size() > 1 &&
   (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty())) {
 errs() << "error: -offset, -len

[llvm-branch-commits] [clang] PR for llvm/llvm-project#80628 (PR #81096)

2024-02-09 Thread Tom Stellard via llvm-branch-commits

https://github.com/tstellar closed 
https://github.com/llvm/llvm-project/pull/81096
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] PR for llvm/llvm-project#81104 (PR #81106)

2024-02-09 Thread via llvm-branch-commits

https://github.com/llvmbot updated 
https://github.com/llvm/llvm-project/pull/81106

>From 8b2cb5f716f0367d98ceaba4b9505cc99aab0b7e Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Tue, 6 Feb 2024 09:00:15 -0800
Subject: [PATCH] Revert "[clang] Mark clang-format-ignore.cpp as unsupported
 on Windows"

This reverts commit dc61ebb44c11d2f5d03b7dd9cb80a0644a30775e.

See https://github.com/llvm/llvm-project/pull/76733#issuecomment-1890311152.

(cherry picked from commit a628f68a9c4ce6f3dcd0c8bb3650db45671ed15a)
---
 clang/test/Format/clang-format-ignore.cpp | 1 -
 1 file changed, 1 deletion(-)

diff --git a/clang/test/Format/clang-format-ignore.cpp 
b/clang/test/Format/clang-format-ignore.cpp
index b4e526463000ae..fb49fa9dd52c65 100644
--- a/clang/test/Format/clang-format-ignore.cpp
+++ b/clang/test/Format/clang-format-ignore.cpp
@@ -1,4 +1,3 @@
-// UNSUPPORTED: system-windows
 // RUN: rm -rf %t.dir
 // RUN: mkdir -p %t.dir/level1/level2
 

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


[llvm-branch-commits] [clang] 8b2cb5f - Revert "[clang] Mark clang-format-ignore.cpp as unsupported on Windows"

2024-02-09 Thread Tom Stellard via llvm-branch-commits

Author: Owen Pan
Date: 2024-02-09T13:26:28-08:00
New Revision: 8b2cb5f716f0367d98ceaba4b9505cc99aab0b7e

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

LOG: Revert "[clang] Mark clang-format-ignore.cpp as unsupported on Windows"

This reverts commit dc61ebb44c11d2f5d03b7dd9cb80a0644a30775e.

See https://github.com/llvm/llvm-project/pull/76733#issuecomment-1890311152.

(cherry picked from commit a628f68a9c4ce6f3dcd0c8bb3650db45671ed15a)

Added: 


Modified: 
clang/test/Format/clang-format-ignore.cpp

Removed: 




diff  --git a/clang/test/Format/clang-format-ignore.cpp 
b/clang/test/Format/clang-format-ignore.cpp
index b4e526463000ae..fb49fa9dd52c65 100644
--- a/clang/test/Format/clang-format-ignore.cpp
+++ b/clang/test/Format/clang-format-ignore.cpp
@@ -1,4 +1,3 @@
-// UNSUPPORTED: system-windows
 // RUN: rm -rf %t.dir
 // RUN: mkdir -p %t.dir/level1/level2
 



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


[llvm-branch-commits] [clang] PR for llvm/llvm-project#81104 (PR #81106)

2024-02-09 Thread Tom Stellard via llvm-branch-commits

https://github.com/tstellar closed 
https://github.com/llvm/llvm-project/pull/81106
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] PR for llvm/llvm-project#80831 (PR #81126)

2024-02-09 Thread via llvm-branch-commits

https://github.com/llvmbot updated 
https://github.com/llvm/llvm-project/pull/81126

>From d079fec440081f3e8e0a79dbbde2066cca077f77 Mon Sep 17 00:00:00 2001
From: Arthur Eubanks 
Date: Wed, 7 Feb 2024 10:16:36 -0700
Subject: [PATCH] [X86] Fix lowering TLS under darwin large code model (#80907)

OpFlag and WrapperKind should be chosen consistently with each other in
regards to PIC, otherwise we hit asserts later on.

Broken by c04a05d8.

Fixes #80831.

(cherry picked from commit 5a83bccb35d6b0e6914b52af6db067aa01dd3efb)
---
 llvm/lib/Target/X86/X86ISelLowering.cpp | 10 ++
 llvm/test/CodeGen/X86/tls-models.ll |  1 +
 2 files changed, 7 insertions(+), 4 deletions(-)

diff --git a/llvm/lib/Target/X86/X86ISelLowering.cpp 
b/llvm/lib/Target/X86/X86ISelLowering.cpp
index e158312caffdec..a071c5a3ca0326 100644
--- a/llvm/lib/Target/X86/X86ISelLowering.cpp
+++ b/llvm/lib/Target/X86/X86ISelLowering.cpp
@@ -18703,16 +18703,18 @@ X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, 
SelectionDAG &DAG) const {
   if (Subtarget.isTargetDarwin()) {
 // Darwin only has one model of TLS.  Lower to that.
 unsigned char OpFlag = 0;
-unsigned WrapperKind = Subtarget.isPICStyleRIPRel() ?
-   X86ISD::WrapperRIP : X86ISD::Wrapper;
+unsigned WrapperKind = 0;
 
 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
 // global base reg.
 bool PIC32 = PositionIndependent && !Subtarget.is64Bit();
-if (PIC32)
+if (PIC32) {
   OpFlag = X86II::MO_TLVP_PIC_BASE;
-else
+  WrapperKind = X86ISD::Wrapper;
+} else {
   OpFlag = X86II::MO_TLVP;
+  WrapperKind = X86ISD::WrapperRIP;
+}
 SDLoc DL(Op);
 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
 GA->getValueType(0),
diff --git a/llvm/test/CodeGen/X86/tls-models.ll 
b/llvm/test/CodeGen/X86/tls-models.ll
index fc8e302338d960..8de9de15a5f06e 100644
--- a/llvm/test/CodeGen/X86/tls-models.ll
+++ b/llvm/test/CodeGen/X86/tls-models.ll
@@ -5,6 +5,7 @@
 
 ; Darwin always uses the same model.
 ; RUN: llc < %s -mtriple=x86_64-apple-darwin | FileCheck -check-prefix=DARWIN 
%s
+; RUN: llc < %s -mtriple=x86_64-apple-darwin -code-model=large | FileCheck 
-check-prefix=DARWIN %s
 
 @external_gd = external thread_local global i32
 @internal_gd = internal thread_local global i32 42

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


[llvm-branch-commits] [llvm] d079fec - [X86] Fix lowering TLS under darwin large code model (#80907)

2024-02-09 Thread Tom Stellard via llvm-branch-commits

Author: Arthur Eubanks
Date: 2024-02-09T13:28:23-08:00
New Revision: d079fec440081f3e8e0a79dbbde2066cca077f77

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

LOG: [X86] Fix lowering TLS under darwin large code model (#80907)

OpFlag and WrapperKind should be chosen consistently with each other in
regards to PIC, otherwise we hit asserts later on.

Broken by c04a05d8.

Fixes #80831.

(cherry picked from commit 5a83bccb35d6b0e6914b52af6db067aa01dd3efb)

Added: 


Modified: 
llvm/lib/Target/X86/X86ISelLowering.cpp
llvm/test/CodeGen/X86/tls-models.ll

Removed: 




diff  --git a/llvm/lib/Target/X86/X86ISelLowering.cpp 
b/llvm/lib/Target/X86/X86ISelLowering.cpp
index e158312caffdec..a071c5a3ca0326 100644
--- a/llvm/lib/Target/X86/X86ISelLowering.cpp
+++ b/llvm/lib/Target/X86/X86ISelLowering.cpp
@@ -18703,16 +18703,18 @@ X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, 
SelectionDAG &DAG) const {
   if (Subtarget.isTargetDarwin()) {
 // Darwin only has one model of TLS.  Lower to that.
 unsigned char OpFlag = 0;
-unsigned WrapperKind = Subtarget.isPICStyleRIPRel() ?
-   X86ISD::WrapperRIP : X86ISD::Wrapper;
+unsigned WrapperKind = 0;
 
 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
 // global base reg.
 bool PIC32 = PositionIndependent && !Subtarget.is64Bit();
-if (PIC32)
+if (PIC32) {
   OpFlag = X86II::MO_TLVP_PIC_BASE;
-else
+  WrapperKind = X86ISD::Wrapper;
+} else {
   OpFlag = X86II::MO_TLVP;
+  WrapperKind = X86ISD::WrapperRIP;
+}
 SDLoc DL(Op);
 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
 GA->getValueType(0),

diff  --git a/llvm/test/CodeGen/X86/tls-models.ll 
b/llvm/test/CodeGen/X86/tls-models.ll
index fc8e302338d960..8de9de15a5f06e 100644
--- a/llvm/test/CodeGen/X86/tls-models.ll
+++ b/llvm/test/CodeGen/X86/tls-models.ll
@@ -5,6 +5,7 @@
 
 ; Darwin always uses the same model.
 ; RUN: llc < %s -mtriple=x86_64-apple-darwin | FileCheck -check-prefix=DARWIN 
%s
+; RUN: llc < %s -mtriple=x86_64-apple-darwin -code-model=large | FileCheck 
-check-prefix=DARWIN %s
 
 @external_gd = external thread_local global i32
 @internal_gd = internal thread_local global i32 42



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


[llvm-branch-commits] [llvm] PR for llvm/llvm-project#80831 (PR #81126)

2024-02-09 Thread Tom Stellard via llvm-branch-commits

https://github.com/tstellar closed 
https://github.com/llvm/llvm-project/pull/81126
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] PR for llvm/llvm-project#79718 (PR #81241)

2024-02-09 Thread via llvm-branch-commits

https://github.com/llvmbot updated 
https://github.com/llvm/llvm-project/pull/81241

>From 391d948748ffae0b79305773ed9b50e86bd29215 Mon Sep 17 00:00:00 2001
From: Quentin Dian 
Date: Fri, 9 Feb 2024 15:29:05 +0800
Subject: [PATCH] [RegisterCoalescer] Clear instructions not recorded in
 `ErasedInstrs` but erased (#79820)

Fixes #79718. Fixes #71178.

The same instructions may exist in an iteration. We cannot immediately
delete instructions in `ErasedInstrs`.

(cherry picked from commit 95b14da678f4670283240ef4cf60f3a39bed97b4)
---
 llvm/lib/CodeGen/RegisterCoalescer.cpp|  27 ++-
 .../register-coalescer-crash-pr79718.mir  | 213 ++
 .../X86/PR71178-register-coalescer-crash.ll   | 103 +
 3 files changed, 338 insertions(+), 5 deletions(-)
 create mode 100644 
llvm/test/CodeGen/LoongArch/register-coalescer-crash-pr79718.mir
 create mode 100644 llvm/test/CodeGen/X86/PR71178-register-coalescer-crash.ll

diff --git a/llvm/lib/CodeGen/RegisterCoalescer.cpp 
b/llvm/lib/CodeGen/RegisterCoalescer.cpp
index cbb1a74049fbd7..7e9c992031f8d3 100644
--- a/llvm/lib/CodeGen/RegisterCoalescer.cpp
+++ b/llvm/lib/CodeGen/RegisterCoalescer.cpp
@@ -236,7 +236,8 @@ namespace {
 /// was successfully coalesced away. If it is not currently possible to
 /// coalesce this interval, but it may be possible if other things get
 /// coalesced, then it returns true by reference in 'Again'.
-bool joinCopy(MachineInstr *CopyMI, bool &Again);
+bool joinCopy(MachineInstr *CopyMI, bool &Again,
+  SmallPtrSetImpl &CurrentErasedInstrs);
 
 /// Attempt to join these two intervals.  On failure, this
 /// returns false.  The output "SrcInt" will not have been modified, so we
@@ -1964,7 +1965,9 @@ void 
RegisterCoalescer::setUndefOnPrunedSubRegUses(LiveInterval &LI,
   LIS->shrinkToUses(&LI);
 }
 
-bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
+bool RegisterCoalescer::joinCopy(
+MachineInstr *CopyMI, bool &Again,
+SmallPtrSetImpl &CurrentErasedInstrs) {
   Again = false;
   LLVM_DEBUG(dbgs() << LIS->getInstructionIndex(*CopyMI) << '\t' << *CopyMI);
 
@@ -2156,7 +2159,9 @@ bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, 
bool &Again) {
   // CopyMI has been erased by joinIntervals at this point. Remove it from
   // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
   // to the work list. This keeps ErasedInstrs from growing needlessly.
-  ErasedInstrs.erase(CopyMI);
+  if (ErasedInstrs.erase(CopyMI))
+// But we may encounter the instruction again in this iteration.
+CurrentErasedInstrs.insert(CopyMI);
 
   // Rewrite all SrcReg operands to DstReg.
   // Also update DstReg operands to include DstIdx if it is set.
@@ -3982,21 +3987,33 @@ void RegisterCoalescer::lateLiveIntervalUpdate() {
 bool RegisterCoalescer::
 copyCoalesceWorkList(MutableArrayRef CurrList) {
   bool Progress = false;
+  SmallPtrSet CurrentErasedInstrs;
   for (MachineInstr *&MI : CurrList) {
 if (!MI)
   continue;
 // Skip instruction pointers that have already been erased, for example by
 // dead code elimination.
-if (ErasedInstrs.count(MI)) {
+if (ErasedInstrs.count(MI) || CurrentErasedInstrs.count(MI)) {
   MI = nullptr;
   continue;
 }
 bool Again = false;
-bool Success = joinCopy(MI, Again);
+bool Success = joinCopy(MI, Again, CurrentErasedInstrs);
 Progress |= Success;
 if (Success || !Again)
   MI = nullptr;
   }
+  // Clear instructions not recorded in `ErasedInstrs` but erased.
+  if (!CurrentErasedInstrs.empty()) {
+for (MachineInstr *&MI : CurrList) {
+  if (MI && CurrentErasedInstrs.count(MI))
+MI = nullptr;
+}
+for (MachineInstr *&MI : WorkList) {
+  if (MI && CurrentErasedInstrs.count(MI))
+MI = nullptr;
+}
+  }
   return Progress;
 }
 
diff --git a/llvm/test/CodeGen/LoongArch/register-coalescer-crash-pr79718.mir 
b/llvm/test/CodeGen/LoongArch/register-coalescer-crash-pr79718.mir
new file mode 100644
index 00..9bbb579b762e63
--- /dev/null
+++ b/llvm/test/CodeGen/LoongArch/register-coalescer-crash-pr79718.mir
@@ -0,0 +1,213 @@
+# NOTE: Assertions have been autogenerated by utils/update_mir_test_checks.py 
UTC_ARGS: --version 4
+# RUN: llc -o - %s -mtriple=loongarch64 \
+# RUN:  -run-pass=register-coalescer -join-liveintervals=1 -join-splitedges=0 
| FileCheck %s
+
+---
+name:foo
+tracksRegLiveness: true
+body: |
+  ; CHECK-LABEL: name: foo
+  ; CHECK: bb.0:
+  ; CHECK-NEXT:   successors: %bb.1(0x8000)
+  ; CHECK-NEXT:   liveins: $r4, $r5, $r6, $r7, $r8
+  ; CHECK-NEXT: {{  $}}
+  ; CHECK-NEXT:   [[COPY:%[0-9]+]]:gpr = COPY $r8
+  ; CHECK-NEXT:   [[COPY1:%[0-9]+]]:gpr = COPY $r7
+  ; CHECK-NEXT:   [[COPY2:%[0-9]+]]:gpr = COPY $r6
+  ; CHECK-NEXT:   [[COPY3:%[0-9]+]]:gpr = COPY $r5
+  ; CHECK-NEXT:   [[COPY4:%[0-9]+]]:gpr = COPY $r4
+  ; CHECK-NEXT:   [[ANDI:%[0-9]+]]:gpr = ANDI [[COPY

[llvm-branch-commits] [llvm] 391d948 - [RegisterCoalescer] Clear instructions not recorded in `ErasedInstrs` but erased (#79820)

2024-02-09 Thread Tom Stellard via llvm-branch-commits

Author: Quentin Dian
Date: 2024-02-09T13:29:49-08:00
New Revision: 391d948748ffae0b79305773ed9b50e86bd29215

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

LOG: [RegisterCoalescer] Clear instructions not recorded in `ErasedInstrs` but 
erased (#79820)

Fixes #79718. Fixes #71178.

The same instructions may exist in an iteration. We cannot immediately
delete instructions in `ErasedInstrs`.

(cherry picked from commit 95b14da678f4670283240ef4cf60f3a39bed97b4)

Added: 
llvm/test/CodeGen/LoongArch/register-coalescer-crash-pr79718.mir
llvm/test/CodeGen/X86/PR71178-register-coalescer-crash.ll

Modified: 
llvm/lib/CodeGen/RegisterCoalescer.cpp

Removed: 




diff  --git a/llvm/lib/CodeGen/RegisterCoalescer.cpp 
b/llvm/lib/CodeGen/RegisterCoalescer.cpp
index cbb1a74049fbd7..7e9c992031f8d3 100644
--- a/llvm/lib/CodeGen/RegisterCoalescer.cpp
+++ b/llvm/lib/CodeGen/RegisterCoalescer.cpp
@@ -236,7 +236,8 @@ namespace {
 /// was successfully coalesced away. If it is not currently possible to
 /// coalesce this interval, but it may be possible if other things get
 /// coalesced, then it returns true by reference in 'Again'.
-bool joinCopy(MachineInstr *CopyMI, bool &Again);
+bool joinCopy(MachineInstr *CopyMI, bool &Again,
+  SmallPtrSetImpl &CurrentErasedInstrs);
 
 /// Attempt to join these two intervals.  On failure, this
 /// returns false.  The output "SrcInt" will not have been modified, so we
@@ -1964,7 +1965,9 @@ void 
RegisterCoalescer::setUndefOnPrunedSubRegUses(LiveInterval &LI,
   LIS->shrinkToUses(&LI);
 }
 
-bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
+bool RegisterCoalescer::joinCopy(
+MachineInstr *CopyMI, bool &Again,
+SmallPtrSetImpl &CurrentErasedInstrs) {
   Again = false;
   LLVM_DEBUG(dbgs() << LIS->getInstructionIndex(*CopyMI) << '\t' << *CopyMI);
 
@@ -2156,7 +2159,9 @@ bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, 
bool &Again) {
   // CopyMI has been erased by joinIntervals at this point. Remove it from
   // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
   // to the work list. This keeps ErasedInstrs from growing needlessly.
-  ErasedInstrs.erase(CopyMI);
+  if (ErasedInstrs.erase(CopyMI))
+// But we may encounter the instruction again in this iteration.
+CurrentErasedInstrs.insert(CopyMI);
 
   // Rewrite all SrcReg operands to DstReg.
   // Also update DstReg operands to include DstIdx if it is set.
@@ -3982,21 +3987,33 @@ void RegisterCoalescer::lateLiveIntervalUpdate() {
 bool RegisterCoalescer::
 copyCoalesceWorkList(MutableArrayRef CurrList) {
   bool Progress = false;
+  SmallPtrSet CurrentErasedInstrs;
   for (MachineInstr *&MI : CurrList) {
 if (!MI)
   continue;
 // Skip instruction pointers that have already been erased, for example by
 // dead code elimination.
-if (ErasedInstrs.count(MI)) {
+if (ErasedInstrs.count(MI) || CurrentErasedInstrs.count(MI)) {
   MI = nullptr;
   continue;
 }
 bool Again = false;
-bool Success = joinCopy(MI, Again);
+bool Success = joinCopy(MI, Again, CurrentErasedInstrs);
 Progress |= Success;
 if (Success || !Again)
   MI = nullptr;
   }
+  // Clear instructions not recorded in `ErasedInstrs` but erased.
+  if (!CurrentErasedInstrs.empty()) {
+for (MachineInstr *&MI : CurrList) {
+  if (MI && CurrentErasedInstrs.count(MI))
+MI = nullptr;
+}
+for (MachineInstr *&MI : WorkList) {
+  if (MI && CurrentErasedInstrs.count(MI))
+MI = nullptr;
+}
+  }
   return Progress;
 }
 

diff  --git a/llvm/test/CodeGen/LoongArch/register-coalescer-crash-pr79718.mir 
b/llvm/test/CodeGen/LoongArch/register-coalescer-crash-pr79718.mir
new file mode 100644
index 00..9bbb579b762e63
--- /dev/null
+++ b/llvm/test/CodeGen/LoongArch/register-coalescer-crash-pr79718.mir
@@ -0,0 +1,213 @@
+# NOTE: Assertions have been autogenerated by utils/update_mir_test_checks.py 
UTC_ARGS: --version 4
+# RUN: llc -o - %s -mtriple=loongarch64 \
+# RUN:  -run-pass=register-coalescer -join-liveintervals=1 -join-splitedges=0 
| FileCheck %s
+
+---
+name:foo
+tracksRegLiveness: true
+body: |
+  ; CHECK-LABEL: name: foo
+  ; CHECK: bb.0:
+  ; CHECK-NEXT:   successors: %bb.1(0x8000)
+  ; CHECK-NEXT:   liveins: $r4, $r5, $r6, $r7, $r8
+  ; CHECK-NEXT: {{  $}}
+  ; CHECK-NEXT:   [[COPY:%[0-9]+]]:gpr = COPY $r8
+  ; CHECK-NEXT:   [[COPY1:%[0-9]+]]:gpr = COPY $r7
+  ; CHECK-NEXT:   [[COPY2:%[0-9]+]]:gpr = COPY $r6
+  ; CHECK-NEXT:   [[COPY3:%[0-9]+]]:gpr = COPY $r5
+  ; CHECK-NEXT:   [[COPY4:%[0-9]+]]:gpr = COPY $r4
+  ; CHECK-NEXT:   [[ANDI:%[0-9]+]]:gpr = ANDI [[COPY3]], 1
+  ; CHECK-NEXT:   [[ORI:%[0-9]+]]:gp

[llvm-branch-commits] [llvm] PR for llvm/llvm-project#79718 (PR #81241)

2024-02-09 Thread Tom Stellard via llvm-branch-commits

https://github.com/tstellar closed 
https://github.com/llvm/llvm-project/pull/81241
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Arthur Eubanks via llvm-branch-commits

https://github.com/aeubanks edited 
https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Arthur Eubanks via llvm-branch-commits


@@ -1103,31 +1106,36 @@ template  void 
Writer::setReservedSymbolSections() {
   }
 
   PhdrEntry *last = nullptr;
-  PhdrEntry *lastRO = nullptr;
-
+  OutputSection *lastRO = nullptr;
+  auto isLarge = [](OutputSection *osec) {
+return config->emachine == EM_X86_64 && osec->flags & SHF_X86_64_LARGE;
+  };
   for (Partition &part : partitions) {
 for (PhdrEntry *p : part.phdrs) {
   if (p->p_type != PT_LOAD)
 continue;
   last = p;
-  if (!(p->p_flags & PF_W))
-lastRO = p;
+  if (!(p->p_flags & PF_W) && p->lastSec && !isLarge(p->lastSec))
+lastRO = p->lastSec;
 }
   }
 
   if (lastRO) {
-// _etext is the first location after the last read-only loadable segment.
+// _etext is the first location after the last read-only loadable segment
+// that does not contain large sections.
 if (ElfSym::etext1)
-  ElfSym::etext1->section = lastRO->lastSec;
+  ElfSym::etext1->section = lastRO;
 if (ElfSym::etext2)
-  ElfSym::etext2->section = lastRO->lastSec;
+  ElfSym::etext2->section = lastRO;
   }
 
   if (last) {
-// _edata points to the end of the last mapped initialized section.
+// _edata points to the end of the last mapped initialized section before
+// the first regular NOBITS section (except .tbss and .relro_padding). In

aeubanks wrote:

if we don't have a .bss section, could this point to .tbss or .relro_padding?

https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Arthur Eubanks via llvm-branch-commits

https://github.com/aeubanks approved this pull request.

lgtm

https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Fangrui Song via llvm-branch-commits


@@ -1103,31 +1106,36 @@ template  void 
Writer::setReservedSymbolSections() {
   }
 
   PhdrEntry *last = nullptr;
-  PhdrEntry *lastRO = nullptr;
-
+  OutputSection *lastRO = nullptr;
+  auto isLarge = [](OutputSection *osec) {
+return config->emachine == EM_X86_64 && osec->flags & SHF_X86_64_LARGE;
+  };
   for (Partition &part : partitions) {
 for (PhdrEntry *p : part.phdrs) {
   if (p->p_type != PT_LOAD)
 continue;
   last = p;
-  if (!(p->p_flags & PF_W))
-lastRO = p;
+  if (!(p->p_flags & PF_W) && p->lastSec && !isLarge(p->lastSec))
+lastRO = p->lastSec;
 }
   }
 
   if (lastRO) {
-// _etext is the first location after the last read-only loadable segment.
+// _etext is the first location after the last read-only loadable segment
+// that does not contain large sections.
 if (ElfSym::etext1)
-  ElfSym::etext1->section = lastRO->lastSec;
+  ElfSym::etext1->section = lastRO;
 if (ElfSym::etext2)
-  ElfSym::etext2->section = lastRO->lastSec;
+  ElfSym::etext2->section = lastRO;
   }
 
   if (last) {
-// _edata points to the end of the last mapped initialized section.
+// _edata points to the end of the last mapped initialized section before
+// the first regular NOBITS section (except .tbss and .relro_padding). In

MaskRay wrote:

Thanks for the catch. After the update the comment no longer makes sense. I 
should change it to
`// _edata points to the end of the last non-large mapped initialized section.`

I think the primary uses of `_edata` are for linker scripts where our logic 
here does not matter.
Some code uses something like `p < _edata` to check whether a pointer is 
guaranteed to be in the read-only segment. It's possible that such code may 
need updates in case `p` now appears in `.lrodata`. From my experience 
migrating gold to lld I've only run into one or two instances like this.

https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Fangrui Song via llvm-branch-commits

https://github.com/MaskRay edited 
https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Fangrui Song via llvm-branch-commits

https://github.com/MaskRay updated 
https://github.com/llvm/llvm-project/pull/81224


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


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Fangrui Song via llvm-branch-commits

https://github.com/MaskRay updated 
https://github.com/llvm/llvm-project/pull/81224


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


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread James Y Knight via llvm-branch-commits

jyknight wrote:

Why not condition this on `-no-pic`, and keep the previous more-optimal layout 
for the normal case?

https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [openmp] release/18.x: [OpenMP] [cmake] Don't use -fno-semantic-interposition on Windows (#81113) (PR #81332)

2024-02-09 Thread via llvm-branch-commits

https://github.com/llvmbot milestoned 
https://github.com/llvm/llvm-project/pull/81332
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [openmp] release/18.x: [OpenMP] [cmake] Don't use -fno-semantic-interposition on Windows (#81113) (PR #81332)

2024-02-09 Thread via llvm-branch-commits

https://github.com/llvmbot created 
https://github.com/llvm/llvm-project/pull/81332

Backport 72f04fa0734f8559ad515f507a4a3ce3f461f196

Requested by: @mstorsjo

>From 9b34418e0883dba29b79a2c843055c7d7e632070 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Martin=20Storsj=C3=B6?= 
Date: Thu, 8 Feb 2024 15:28:46 +0200
Subject: [PATCH] [OpenMP] [cmake] Don't use -fno-semantic-interposition on
 Windows (#81113)

This was added in 4b7beab4187ab0766c3d7b272511d5751431a8da. When the
flag was added implicitly elsewhere, it was added via
llvm/cmake/modules/HandleLLVMOptions.cmake, where it wasn't added on
Windows/Cygwin targets.

This avoids one warning per object file in OpenMP.

(cherry picked from commit 72f04fa0734f8559ad515f507a4a3ce3f461f196)
---
 openmp/cmake/HandleOpenMPOptions.cmake | 6 +-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/openmp/cmake/HandleOpenMPOptions.cmake 
b/openmp/cmake/HandleOpenMPOptions.cmake
index 71346201129b68..9387d9b3b0ff75 100644
--- a/openmp/cmake/HandleOpenMPOptions.cmake
+++ b/openmp/cmake/HandleOpenMPOptions.cmake
@@ -46,7 +46,11 @@ append_if(OPENMP_HAVE_WEXTRA_FLAG "-Wno-extra" CMAKE_C_FLAGS 
CMAKE_CXX_FLAGS)
 append_if(OPENMP_HAVE_WPEDANTIC_FLAG "-Wno-pedantic" CMAKE_C_FLAGS 
CMAKE_CXX_FLAGS)
 append_if(OPENMP_HAVE_WMAYBE_UNINITIALIZED_FLAG "-Wno-maybe-uninitialized" 
CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
 
-append_if(OPENMP_HAVE_NO_SEMANTIC_INTERPOSITION "-fno-semantic-interposition" 
CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
+if (NOT (WIN32 OR CYGWIN))
+  # This flag is not relevant on Windows; the flag is accepted, but produces 
warnings
+  # about argument unused during compilation.
+  append_if(OPENMP_HAVE_NO_SEMANTIC_INTERPOSITION 
"-fno-semantic-interposition" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
+endif()
 append_if(OPENMP_HAVE_FUNCTION_SECTIONS "-ffunction-section" CMAKE_C_FLAGS 
CMAKE_CXX_FLAGS)
 append_if(OPENMP_HAVE_DATA_SECTIONS "-fdata-sections" CMAKE_C_FLAGS 
CMAKE_CXX_FLAGS)
 

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


[llvm-branch-commits] [openmp] release/18.x: [OpenMP] [cmake] Don't use -fno-semantic-interposition on Windows (#81113) (PR #81332)

2024-02-09 Thread via llvm-branch-commits

llvmbot wrote:

@jhuber6 What do you think about merging this PR to the release branch?

https://github.com/llvm/llvm-project/pull/81332
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [openmp] release/18.x: [OpenMP] [cmake] Don't use -fno-semantic-interposition on Windows (#81113) (PR #81332)

2024-02-09 Thread via llvm-branch-commits

https://github.com/llvmbot updated 
https://github.com/llvm/llvm-project/pull/81332

>From 47ec6be2d071e18111642473c70b96f5025dcef6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Martin=20Storsj=C3=B6?= 
Date: Thu, 8 Feb 2024 15:28:46 +0200
Subject: [PATCH] [OpenMP] [cmake] Don't use -fno-semantic-interposition on
 Windows (#81113)

This was added in 4b7beab4187ab0766c3d7b272511d5751431a8da. When the
flag was added implicitly elsewhere, it was added via
llvm/cmake/modules/HandleLLVMOptions.cmake, where it wasn't added on
Windows/Cygwin targets.

This avoids one warning per object file in OpenMP.

(cherry picked from commit 72f04fa0734f8559ad515f507a4a3ce3f461f196)
---
 openmp/cmake/HandleOpenMPOptions.cmake | 6 +-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/openmp/cmake/HandleOpenMPOptions.cmake 
b/openmp/cmake/HandleOpenMPOptions.cmake
index 71346201129b68..9387d9b3b0ff75 100644
--- a/openmp/cmake/HandleOpenMPOptions.cmake
+++ b/openmp/cmake/HandleOpenMPOptions.cmake
@@ -46,7 +46,11 @@ append_if(OPENMP_HAVE_WEXTRA_FLAG "-Wno-extra" CMAKE_C_FLAGS 
CMAKE_CXX_FLAGS)
 append_if(OPENMP_HAVE_WPEDANTIC_FLAG "-Wno-pedantic" CMAKE_C_FLAGS 
CMAKE_CXX_FLAGS)
 append_if(OPENMP_HAVE_WMAYBE_UNINITIALIZED_FLAG "-Wno-maybe-uninitialized" 
CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
 
-append_if(OPENMP_HAVE_NO_SEMANTIC_INTERPOSITION "-fno-semantic-interposition" 
CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
+if (NOT (WIN32 OR CYGWIN))
+  # This flag is not relevant on Windows; the flag is accepted, but produces 
warnings
+  # about argument unused during compilation.
+  append_if(OPENMP_HAVE_NO_SEMANTIC_INTERPOSITION 
"-fno-semantic-interposition" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
+endif()
 append_if(OPENMP_HAVE_FUNCTION_SECTIONS "-ffunction-section" CMAKE_C_FLAGS 
CMAKE_CXX_FLAGS)
 append_if(OPENMP_HAVE_DATA_SECTIONS "-fdata-sections" CMAKE_C_FLAGS 
CMAKE_CXX_FLAGS)
 

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


[llvm-branch-commits] [ELF] Place .lbss/.lrodata/.ldata after .bss (PR #81224)

2024-02-09 Thread Fangrui Song via llvm-branch-commits

MaskRay wrote:

> Why not condition this on `-no-pic`, and keep the previous more-optimal 
> layout for the normal case?

The motivation is to avoid layout differences between `-no-pie` and 
`-pie/-shared`. If someone uses a linker script fragment with `INSERT`, it 
would be difficult if there are two layouts.

My original objection to doing anything for the `-no-pie` issue (#78521) was 
because I did not want to pessimize `-pie` users.

I think having two layouts is still an opinion, and I am eager to hear more 
opinions.

We could also have an option to select between the two layouts and figure out 
which default it should use. I don't know whether it justifies an option.

https://github.com/llvm/llvm-project/pull/81224
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [BOLT] Add binary introspection/JIT manager (PR #81346)

2024-02-09 Thread Rafael Auler via llvm-branch-commits

https://github.com/rafaelauler created 
https://github.com/llvm/llvm-project/pull/81346

Add a class that allows a process to introspect or investigate itself by 
disassembling its memory contents just-in-time with BOLT. An example is shown 
in a new unittest binary.

This leverages the new ability to use BOLT as a library instead of as a regular 
executable that processes input binaries, demonstrating how to use BOLT as a 
library.

>From 1167a59a185cbc113d6ca30f223e09be1abc8494 Mon Sep 17 00:00:00 2001
From: Rafael Auler 
Date: Thu, 8 Feb 2024 19:57:14 -0800
Subject: [PATCH] [BOLT] Add binary introspection/JIT manager

Add a class that allows a process to introspect or investigate itself
by disassembling its memory contents just-in-time with BOLT. An
example is shown in a new unittest binary.

This leverages the new ability to use BOLT as a library instead of as
a regular executable that processes input binaries, demonstrating how
to use BOLT as a library.
---
 bolt/include/bolt/Core/BinaryContext.h|   9 +-
 bolt/include/bolt/Core/BinaryFunction.h   |   1 +
 bolt/include/bolt/Core/BinarySection.h|   3 +-
 .../include/bolt/Rewrite/JITRewriteInstance.h | 105 +
 bolt/lib/Core/BinaryContext.cpp   |  39 +-
 bolt/lib/Rewrite/CMakeLists.txt   |   1 +
 bolt/lib/Rewrite/DWARFRewriter.cpp|   2 +-
 bolt/lib/Rewrite/JITRewriteInstance.cpp   | 367 ++
 bolt/lib/Rewrite/MachORewriteInstance.cpp |  35 +-
 bolt/lib/Rewrite/RewriteInstance.cpp  |  19 +-
 bolt/unittests/CMakeLists.txt |   1 +
 bolt/unittests/Core/BinaryContext.cpp |   4 +-
 bolt/unittests/Core/MCPlusBuilder.cpp |   4 +-
 bolt/unittests/Rewrite/CMakeLists.txt |  27 ++
 bolt/unittests/Rewrite/JITRewriteInstance.cpp |  99 +
 15 files changed, 654 insertions(+), 62 deletions(-)
 create mode 100644 bolt/include/bolt/Rewrite/JITRewriteInstance.h
 create mode 100644 bolt/lib/Rewrite/JITRewriteInstance.cpp
 create mode 100644 bolt/unittests/Rewrite/CMakeLists.txt
 create mode 100644 bolt/unittests/Rewrite/JITRewriteInstance.cpp

diff --git a/bolt/include/bolt/Core/BinaryContext.h 
b/bolt/include/bolt/Core/BinaryContext.h
index 30336c4e3a74fe..e5af8685d9b0d0 100644
--- a/bolt/include/bolt/Core/BinaryContext.h
+++ b/bolt/include/bolt/Core/BinaryContext.h
@@ -212,9 +212,6 @@ class BinaryContext {
   /// input file to internal section representation.
   DenseMap SectionRefToBinarySection;
 
-  /// Low level section registration.
-  BinarySection ®isterSection(BinarySection *Section);
-
   /// Store all functions in the binary, sorted by original address.
   std::map BinaryFunctions;
 
@@ -265,7 +262,8 @@ class BinaryContext {
 
 public:
   static Expected>
-  createBinaryContext(const ObjectFile *File, bool IsPIC,
+  createBinaryContext(Triple TheTriple, StringRef InputFileName,
+  SubtargetFeatures *Features, bool IsPIC,
   std::unique_ptr DwCtx,
   JournalingStreams Logger);
 
@@ -1049,6 +1047,9 @@ class BinaryContext {
   BinarySection ®isterSection(const Twine &SectionName,
  const BinarySection &OriginalSection);
 
+  /// Low level section registration.
+  BinarySection ®isterSection(BinarySection *Section);
+
   /// Register or update the information for the section with the given
   /// /p Name.  If the section already exists, the information in the
   /// section will be updated with the new data.
diff --git a/bolt/include/bolt/Core/BinaryFunction.h 
b/bolt/include/bolt/Core/BinaryFunction.h
index a177178769e456..68c626d9a2f452 100644
--- a/bolt/include/bolt/Core/BinaryFunction.h
+++ b/bolt/include/bolt/Core/BinaryFunction.h
@@ -655,6 +655,7 @@ class BinaryFunction {
   BinaryFunction(const BinaryFunction &) = delete;
 
   friend class MachORewriteInstance;
+  friend class JITRewriteInstance;
   friend class RewriteInstance;
   friend class BinaryContext;
   friend class DataReader;
diff --git a/bolt/include/bolt/Core/BinarySection.h 
b/bolt/include/bolt/Core/BinarySection.h
index a85dbf28950e31..d4f9b5955b2029 100644
--- a/bolt/include/bolt/Core/BinarySection.h
+++ b/bolt/include/bolt/Core/BinarySection.h
@@ -50,7 +50,7 @@ class BinarySection {
   std::string Name;// Section name
   const SectionRef Section;// SectionRef for input binary sections.
   StringRef Contents;  // Input section contents
-  const uint64_t Address;  // Address of section in input binary (may be 0)
+  uint64_t Address;// Address of section in input binary (may be 0)
   const uint64_t Size; // Input section size
   uint64_t InputFileOffset{0}; // Offset in the input binary
   unsigned Alignment;  // alignment in bytes (must be > 0)
@@ -461,6 +461,7 @@ class BinarySection {
   uint32_t getIndex() const { return Index; }
 
   // mutation
+  void setAddress(uint64_t Address) { this->Address = Address; }
   voi

[llvm-branch-commits] [llvm] [BOLT] Add binary introspection/JIT manager (PR #81346)

2024-02-09 Thread Rafael Auler via llvm-branch-commits

rafaelauler wrote:

Depends on #81082 

https://github.com/llvm/llvm-project/pull/81346
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [BOLT] Add binary introspection/JIT manager (PR #81346)

2024-02-09 Thread Amir Ayupov via llvm-branch-commits


@@ -0,0 +1,105 @@
+//===- bolt/Rewrite/JITRewriteInstance.h - in-memory rewriter ---*- 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
+//
+//===--===//
+//
+// Interface to control BOLT as JIT library
+//
+//===--===//
+
+#ifndef BOLT_JIT_REWRITE_REWRITE_INSTANCE_H
+#define BOLT_JIT_REWRITE_REWRITE_INSTANCE_H
+
+#include "bolt/Utils/NameResolver.h"
+#include "llvm/Support/Error.h"
+#include "llvm/Support/StringSaver.h"
+#include 
+
+namespace llvm {
+
+namespace object {
+class ObjectFile;
+}
+
+namespace bolt {
+
+class BinaryContext;
+class ProfileReaderBase;
+struct JournalingStreams;
+
+/// Allows a process to instrospect itself by running BOLT to disassemble its
+/// its own address space.

aaupov wrote:

> introspect

https://github.com/llvm/llvm-project/pull/81346
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits