================
@@ -16,58 +16,131 @@
 
 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
 #include "mlir/IR/BuiltinOps.h"
+#include "mlir/IR/Matchers.h"
 #include "clang/CIR/Dialect/IR/CIRDialect.h"
+#include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SparseBitVector.h"
 #include "llvm/Support/MathExtras.h"
+#include "llvm/TargetParser/Triple.h"
 #include "llvm/Transforms/Utils/AMDGPUEmitPrintf.h"
 
 namespace cir {
 namespace direct {
 
 namespace {
 
+// One entry per operand, format first. A string entry means the
+// operand is a constant string; a unit entry means it is not.
+constexpr llvm::StringLiteral kPrintfConstStringsAttrName =
+    "cir.printf.const_strings";
+
+// Fold a constant through widening integral casts, each at its own width.
+// TODO: use the regular fold helpers once they fold widening cast chains
+// without also folding narrowing casts. CastOp is not ConstantLike and
+// its fold folds narrowing casts, so the chain stays hand written today.
+std::optional<llvm::APInt>
+foldConstantInt(mlir::Value value,
+                llvm::SmallPtrSetImpl<mlir::Operation *> &seen) {
+  mlir::Operation *def = value.getDefiningOp();
+  if (!def || !seen.insert(def).second)
+    return std::nullopt;
+  cir::IntAttr intAttr;
+  if (mlir::matchPattern(value, mlir::m_Constant(&intAttr)))
+    return intAttr.getValue();
+  auto cast = mlir::dyn_cast<cir::CastOp>(def);
+  if (!cast || cast.getKind() != cir::CastKind::integral)
+    return std::nullopt;
+  auto srcTy = mlir::dyn_cast<cir::IntType>(cast.getSrc().getType());
+  auto dstTy = mlir::dyn_cast<cir::IntType>(cast.getType());
+  if (!srcTy || !dstTy || dstTy.getWidth() < srcTy.getWidth() ||
+      dstTy.getWidth() > 64)
+    return std::nullopt;
+  // One widening step from a direct constant is the op's own fold;
+  // chains recurse, since fold sees only the immediate source.
+  llvm::SmallVector<mlir::OpFoldResult, 1> folded;
+  if (succeeded(cast->fold(folded)) && folded.size() == 1)
+    if (auto attr = mlir::dyn_cast<mlir::Attribute>(folded[0]))
+      if (auto foldedInt = mlir::dyn_cast<cir::IntAttr>(attr))
+        return foldedInt.getValue();
+  std::optional<llvm::APInt> foldedSrc = foldConstantInt(cast.getSrc(), seen);
+  if (!foldedSrc)
+    return std::nullopt;
+  return srcTy.isUnsigned() ? foldedSrc->zextOrTrunc(dstTy.getWidth())
+                            : foldedSrc->sextOrTrunc(dstTy.getWidth());
+}
+
 std::optional<int64_t> getConstantInt(mlir::Value value) {
-  auto constOp = value.getDefiningOp<cir::ConstantOp>();
-  auto intAttr =
-      constOp ? mlir::dyn_cast<cir::IntAttr>(constOp.getValue()) : nullptr;
-  if (!intAttr)
+  bool isUnsigned = false;
+  if (auto intTy = mlir::dyn_cast<cir::IntType>(value.getType()))
+    isUnsigned = !intTy.isSigned();
+  llvm::SmallPtrSet<mlir::Operation *, 4> seen;
+  std::optional<llvm::APInt> result = foldConstantInt(value, seen);
+  if (!result || result->getBitWidth() > 64)
     return std::nullopt;
-  const llvm::APInt &v = intAttr.getValue();
-  if (mlir::cast<cir::IntType>(intAttr.getType()).isSigned()
-          ? v.getSignificantBits() > 64
-          : v.getActiveBits() > 63)
+  // An unsigned value past INT64_MAX cannot be a byte offset here:
+  // returning it would wrap negative in the signed offset below.
+  if (isUnsigned ? result->getActiveBits() > 63
+                 : result->getSignificantBits() > 64)
     return std::nullopt;
-  return v.getSExtValue();
+  return isUnsigned ? result->getZExtValue() : result->getSExtValue();
 }
 
 bool isByteType(mlir::Type ty) {
-  auto intTy = mlir::dyn_cast<cir::IntType>(ty);
-  return intTy && intTy.getWidth() == 8;
+  if (auto intTy = mlir::dyn_cast<cir::IntType>(ty))
+    return intTy.getWidth() == 8;
+  return ty.isInteger(8);
+}
+
+std::optional<int64_t> scaledOffset(int64_t index, mlir::Type elemTy,
+                                    const mlir::DataLayout &dataLayout) {
+  llvm::TypeSize size = dataLayout.getTypeAllocSize(elemTy);
+  if (size.isScalable() || size.getFixedValue() >= (1ULL << 63))
+    return std::nullopt;
+  int64_t offset;
+  if (llvm::MulOverflow(index, static_cast<int64_t>(size.getFixedValue()),
+                        offset))
+    return std::nullopt;
+  return offset;
 }
 
 bool getConstantStringInfo(mlir::Value ptr, mlir::ModuleOp mod,
+                           const mlir::DataLayout &dataLayout,
                            mlir::SymbolTableCollection &symbolTables,
                            std::string &str) {
   int64_t offset = 0;
+  llvm::SmallPtrSet<mlir::Operation *, 8> seen;
   while (mlir::Operation *def = ptr.getDefiningOp()) {
+    if (!seen.insert(def).second)
+      return false;
     if (auto cast = mlir::dyn_cast<cir::CastOp>(def)) {
       if (cast.getKind() != cir::CastKind::array_to_ptrdecay &&
           cast.getKind() != cir::CastKind::bitcast &&
           cast.getKind() != cir::CastKind::address_space)
         break;
       ptr = cast.getSrc();
-    } else if (auto elt = mlir::dyn_cast<cir::GetElementOp>(def)) {
-      std::optional<int64_t> index = getConstantInt(elt.getIndex());
-      if (!index || !isByteType(elt.getElementType()) ||
-          llvm::AddOverflow(offset, *index, offset))
-        return false;
-      ptr = elt.getBase();
     } else if (auto stride = mlir::dyn_cast<cir::PtrStrideOp>(def)) {
+      mlir::Type elemTy = stride.getElementType();
+      // Lowering treats void and function elements as bytes, and
+      // neither has a data layout entry.
+      if (mlir::isa<cir::VoidType, cir::FuncType>(elemTy))
+        elemTy = cir::IntType::get(elemTy.getContext(), 8, false);
       std::optional<int64_t> index = getConstantInt(stride.getStride());
-      if (!index || !isByteType(stride.getElementType()) ||
-          llvm::AddOverflow(offset, *index, offset))
+      std::optional<int64_t> step =
+          index ? scaledOffset(*index, elemTy, dataLayout) : std::nullopt;
+      if (!step || llvm::AddOverflow(offset, *step, offset))
         return false;
       ptr = stride.getBase();
+    } else if (auto elt = mlir::dyn_cast<cir::GetElementOp>(def)) {
+      auto arrayTy =
----------------
steffenlarsen wrote:

I don't see `arrayTy` being used. Should it be used in `scaledOffset` or can we 
replace this with an `isa`?

https://github.com/llvm/llvm-project/pull/242111
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to