[clang] [CIR] Implement emitNewArrayInit for constant and strings (PR #192666)

Andy Kaylor via cfe-commits cfe-commits at lists.llvm.org
Fri Apr 17 15:02:44 PDT 2026


================
@@ -1006,8 +1010,55 @@ void CIRGenFunction::emitNewArrayInitializer(
     // Initializing from a (braced) string literal is a special case; the init
     // list element does not initialize a (single) array element.
     if ((ile && ile->isStringLiteralInit()) || sl || ocee) {
-      cgm.errorNYI(ile->getSourceRange(),
-                   "emitNewArrayInitializer: string literal init");
+      if (!ile)
+        init = ignoreParen;
+
+      // Initialize the initial portion of length equal to that of the string
+      // literal. The allocation must be for at least this much; we emitted a
+      // check for that earlier. Since we intend to use a cir.copy here, we must
+      // introduce a cast to the string-literal-size here, so that cir.copy does
+      // the right thing.
+
+      const Expr *initExpr = ile ? ile->getInit(0) : init;
+      mlir::Type initExprTy = convertType(initExpr->getType());
+      Address coercedPtrTy{
+          builder.createBitcast(curPtr.getPointer(),
+                                builder.getPointerTo(initExprTy)),
+          curPtr.getAlignment()};
+
+      AggValueSlot slot = AggValueSlot::forAddr(
+          coercedPtrTy, elementType.getQualifiers(), AggValueSlot::IsDestructed,
+          AggValueSlot::IsNotAliased, AggValueSlot::DoesNotOverlap,
+          AggValueSlot::IsNotZeroed);
+      emitAggExpr(initExpr, slot);
+
+      // Move past these elements.
+      initListElements =
+          cast<ConstantArrayType>(init->getType()->getAsArrayTypeUnsafe())
+              ->getZExtSize();
+
+      bool alreadyInitedAll = false;
+      auto constElts =
+          mlir::dyn_cast<cir::ConstantOp>(numElements.getDefiningOp());
+      if (constElts) {
+        if (auto constIntAttr =
+                mlir::dyn_cast<cir::IntAttr>(constElts.getValue()))
----------------
andykaylor wrote:

```suggestion
        int64_t constVal = getZExtIntValueFromConstOp(numElements);
```
You still need to check that numElements is defined by ConstantOp before calling this, but I think we can assume that it is an integer constant.

We could roll all of this up into a single `isConstantIntEqualTo(numElements, initListElements)` function, but I'm not sure how often this comes up.

https://github.com/llvm/llvm-project/pull/192666


More information about the cfe-commits mailing list